1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Generic MMIO clocksource support
4 */
5 #include <linux/clocksource.h>
6 #include <linux/errno.h>
7 #include <linux/init.h>
8 #include <linux/slab.h>
9
10 struct clocksource_mmio {
11 void __iomem *reg;
12 struct clocksource clksrc;
13 };
14
to_mmio_clksrc(struct clocksource * c)15 static inline struct clocksource_mmio *to_mmio_clksrc(struct clocksource *c)
16 {
17 return container_of(c, struct clocksource_mmio, clksrc);
18 }
19
clocksource_mmio_readl_up(struct clocksource * c)20 u64 clocksource_mmio_readl_up(struct clocksource *c)
21 {
22 return (u64)readl_relaxed(to_mmio_clksrc(c)->reg);
23 }
24 EXPORT_SYMBOL_GPL(clocksource_mmio_readl_up);
25
clocksource_mmio_readl_down(struct clocksource * c)26 u64 clocksource_mmio_readl_down(struct clocksource *c)
27 {
28 return ~(u64)readl_relaxed(to_mmio_clksrc(c)->reg) & c->mask;
29 }
30
clocksource_mmio_readw_up(struct clocksource * c)31 u64 clocksource_mmio_readw_up(struct clocksource *c)
32 {
33 return (u64)readw_relaxed(to_mmio_clksrc(c)->reg);
34 }
35
clocksource_mmio_readw_down(struct clocksource * c)36 u64 clocksource_mmio_readw_down(struct clocksource *c)
37 {
38 return ~(u64)readw_relaxed(to_mmio_clksrc(c)->reg) & c->mask;
39 }
40
41 /**
42 * clocksource_mmio_init - Initialize a simple mmio based clocksource
43 * @base: Virtual address of the clock readout register
44 * @name: Name of the clocksource
45 * @hz: Frequency of the clocksource in Hz
46 * @rating: Rating of the clocksource
47 * @bits: Number of valid bits
48 * @read: One of clocksource_mmio_read*() above
49 */
clocksource_mmio_init(void __iomem * base,const char * name,unsigned long hz,int rating,unsigned bits,u64 (* read)(struct clocksource *))50 int clocksource_mmio_init(void __iomem *base, const char *name,
51 unsigned long hz, int rating, unsigned bits,
52 u64 (*read)(struct clocksource *))
53 {
54 struct clocksource_mmio *cs;
55
56 if (bits > 64 || bits < 16)
57 return -EINVAL;
58
59 cs = kzalloc(sizeof(struct clocksource_mmio), GFP_KERNEL);
60 if (!cs)
61 return -ENOMEM;
62
63 cs->reg = base;
64 cs->clksrc.name = name;
65 cs->clksrc.rating = rating;
66 cs->clksrc.read = read;
67 cs->clksrc.mask = CLOCKSOURCE_MASK(bits);
68 cs->clksrc.flags = CLOCK_SOURCE_IS_CONTINUOUS;
69
70 return clocksource_register_hz(&cs->clksrc, hz);
71 }
72 EXPORT_SYMBOL_GPL(clocksource_mmio_init);
73