xref: /openbmc/qemu/hw/timer/aspeed_timer.c (revision f18793b0)
1 /*
2  * ASPEED AST2400 Timer
3  *
4  * Andrew Jeffery <andrew@aj.id.au>
5  *
6  * Copyright (C) 2016 IBM Corp.
7  *
8  * This code is licensed under the GPL version 2 or later.  See
9  * the COPYING file in the top-level directory.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qapi/error.h"
14 #include "hw/sysbus.h"
15 #include "hw/timer/aspeed_timer.h"
16 #include "hw/misc/aspeed_scu.h"
17 #include "qemu-common.h"
18 #include "qemu/bitops.h"
19 #include "qemu/timer.h"
20 #include "qemu/log.h"
21 #include "trace.h"
22 
23 #define TIMER_NR_REGS 4
24 
25 #define TIMER_CTRL_BITS 4
26 #define TIMER_CTRL_MASK ((1 << TIMER_CTRL_BITS) - 1)
27 
28 #define TIMER_CLOCK_USE_EXT true
29 #define TIMER_CLOCK_EXT_HZ 1000000
30 #define TIMER_CLOCK_USE_APB false
31 
32 #define TIMER_REG_STATUS 0
33 #define TIMER_REG_RELOAD 1
34 #define TIMER_REG_MATCH_FIRST 2
35 #define TIMER_REG_MATCH_SECOND 3
36 
37 #define TIMER_FIRST_CAP_PULSE 4
38 
39 enum timer_ctrl_op {
40     op_enable = 0,
41     op_external_clock,
42     op_overflow_interrupt,
43     op_pulse_enable
44 };
45 
46 /**
47  * Avoid mutual references between AspeedTimerCtrlState and AspeedTimer
48  * structs, as it's a waste of memory. The ptimer BH callback needs to know
49  * whether a specific AspeedTimer is enabled, but this information is held in
50  * AspeedTimerCtrlState. So, provide a helper to hoist ourselves from an
51  * arbitrary AspeedTimer to AspeedTimerCtrlState.
52  */
53 static inline AspeedTimerCtrlState *timer_to_ctrl(AspeedTimer *t)
54 {
55     const AspeedTimer (*timers)[] = (void *)t - (t->id * sizeof(*t));
56     return container_of(timers, AspeedTimerCtrlState, timers);
57 }
58 
59 static inline bool timer_ctrl_status(AspeedTimer *t, enum timer_ctrl_op op)
60 {
61     return !!(timer_to_ctrl(t)->ctrl & BIT(t->id * TIMER_CTRL_BITS + op));
62 }
63 
64 static inline bool timer_enabled(AspeedTimer *t)
65 {
66     return timer_ctrl_status(t, op_enable);
67 }
68 
69 static inline bool timer_overflow_interrupt(AspeedTimer *t)
70 {
71     return timer_ctrl_status(t, op_overflow_interrupt);
72 }
73 
74 static inline bool timer_can_pulse(AspeedTimer *t)
75 {
76     return t->id >= TIMER_FIRST_CAP_PULSE;
77 }
78 
79 static inline bool timer_external_clock(AspeedTimer *t)
80 {
81     return timer_ctrl_status(t, op_external_clock);
82 }
83 
84 static inline uint32_t calculate_rate(struct AspeedTimer *t)
85 {
86     AspeedTimerCtrlState *s = timer_to_ctrl(t);
87 
88     return timer_external_clock(t) ? TIMER_CLOCK_EXT_HZ : s->scu->apb_freq;
89 }
90 
91 static inline uint32_t calculate_ticks(struct AspeedTimer *t, uint64_t now_ns)
92 {
93     uint64_t delta_ns = now_ns - MIN(now_ns, t->start);
94     uint32_t rate = calculate_rate(t);
95     uint64_t ticks = muldiv64(delta_ns, rate, NANOSECONDS_PER_SECOND);
96 
97     return t->reload - MIN(t->reload, ticks);
98 }
99 
100 static inline uint64_t calculate_time(struct AspeedTimer *t, uint32_t ticks)
101 {
102     uint64_t delta_ns;
103     uint64_t delta_ticks;
104 
105     delta_ticks = t->reload - MIN(t->reload, ticks);
106     delta_ns = muldiv64(delta_ticks, NANOSECONDS_PER_SECOND, calculate_rate(t));
107 
108     return t->start + delta_ns;
109 }
110 
111 static uint64_t calculate_next(struct AspeedTimer *t)
112 {
113     uint64_t next = 0;
114     uint32_t rate = calculate_rate(t);
115 
116     while (!next) {
117         /* We don't know the relationship between the values in the match
118          * registers, so sort using MAX/MIN/zero. We sort in that order as the
119          * timer counts down to zero. */
120         uint64_t seq[] = {
121             calculate_time(t, MAX(t->match[0], t->match[1])),
122             calculate_time(t, MIN(t->match[0], t->match[1])),
123             calculate_time(t, 0),
124         };
125         uint64_t reload_ns;
126         uint64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
127 
128         if (now < seq[0]) {
129             next = seq[0];
130         } else if (now < seq[1]) {
131             next = seq[1];
132         } else if (now < seq[2]) {
133             next = seq[2];
134         } else if (t->reload) {
135             reload_ns = muldiv64(t->reload, NANOSECONDS_PER_SECOND, rate);
136             t->start = now - ((now - t->start) % reload_ns);
137         } else {
138             /* no reload value, return 0 */
139             break;
140         }
141     }
142 
143     return next;
144 }
145 
146 static void aspeed_timer_mod(AspeedTimer *t)
147 {
148     uint64_t next = calculate_next(t);
149     if (next) {
150         timer_mod(&t->timer, next);
151     }
152 }
153 
154 static void aspeed_timer_expire(void *opaque)
155 {
156     AspeedTimer *t = opaque;
157     bool interrupt = false;
158     uint32_t ticks;
159 
160     if (!timer_enabled(t)) {
161         return;
162     }
163 
164     ticks = calculate_ticks(t, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
165 
166     if (!ticks) {
167         interrupt = timer_overflow_interrupt(t) || !t->match[0] || !t->match[1];
168     } else if (ticks <= MIN(t->match[0], t->match[1])) {
169         interrupt = true;
170     } else if (ticks <= MAX(t->match[0], t->match[1])) {
171         interrupt = true;
172     }
173 
174     if (interrupt) {
175         t->level = !t->level;
176         qemu_set_irq(t->irq, t->level);
177     }
178 
179     aspeed_timer_mod(t);
180 }
181 
182 static uint64_t aspeed_timer_get_value(AspeedTimer *t, int reg)
183 {
184     uint64_t value;
185 
186     switch (reg) {
187     case TIMER_REG_STATUS:
188         value = calculate_ticks(t, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
189         break;
190     case TIMER_REG_RELOAD:
191         value = t->reload;
192         break;
193     case TIMER_REG_MATCH_FIRST:
194     case TIMER_REG_MATCH_SECOND:
195         value = t->match[reg - 2];
196         break;
197     default:
198         qemu_log_mask(LOG_UNIMP, "%s: Programming error: unexpected reg: %d\n",
199                       __func__, reg);
200         value = 0;
201         break;
202     }
203     return value;
204 }
205 
206 static uint64_t aspeed_timer_read(void *opaque, hwaddr offset, unsigned size)
207 {
208     AspeedTimerCtrlState *s = opaque;
209     const int reg = (offset & 0xf) / 4;
210     uint64_t value;
211 
212     switch (offset) {
213     case 0x30: /* Control Register */
214         value = s->ctrl;
215         break;
216     case 0x34: /* Control Register 2 */
217         value = s->ctrl2;
218         break;
219     case 0x00 ... 0x2c: /* Timers 1 - 4 */
220         value = aspeed_timer_get_value(&s->timers[(offset >> 4)], reg);
221         break;
222     case 0x40 ... 0x8c: /* Timers 5 - 8 */
223         value = aspeed_timer_get_value(&s->timers[(offset >> 4) - 1], reg);
224         break;
225     /* Illegal */
226     case 0x38:
227     case 0x3C:
228     default:
229         qemu_log_mask(LOG_GUEST_ERROR, "%s: Bad offset 0x%" HWADDR_PRIx "\n",
230                 __func__, offset);
231         value = 0;
232         break;
233     }
234     trace_aspeed_timer_read(offset, size, value);
235     return value;
236 }
237 
238 static void aspeed_timer_set_value(AspeedTimerCtrlState *s, int timer, int reg,
239                                    uint32_t value)
240 {
241     AspeedTimer *t;
242     uint32_t old_reload;
243 
244     trace_aspeed_timer_set_value(timer, reg, value);
245     t = &s->timers[timer];
246     switch (reg) {
247     case TIMER_REG_RELOAD:
248         old_reload = t->reload;
249         t->reload = value;
250 
251         /* If the reload value was not previously set, or zero, and
252          * the current value is valid, try to start the timer if it is
253          * enabled.
254          */
255         if (old_reload || !t->reload) {
256             break;
257         }
258 
259     case TIMER_REG_STATUS:
260         if (timer_enabled(t)) {
261             uint64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
262             int64_t delta = (int64_t) value - (int64_t) calculate_ticks(t, now);
263             uint32_t rate = calculate_rate(t);
264 
265             t->start += muldiv64(delta, NANOSECONDS_PER_SECOND, rate);
266             aspeed_timer_mod(t);
267         }
268         break;
269     case TIMER_REG_MATCH_FIRST:
270     case TIMER_REG_MATCH_SECOND:
271         t->match[reg - 2] = value;
272         if (timer_enabled(t)) {
273             aspeed_timer_mod(t);
274         }
275         break;
276     default:
277         qemu_log_mask(LOG_UNIMP, "%s: Programming error: unexpected reg: %d\n",
278                       __func__, reg);
279         break;
280     }
281 }
282 
283 /* Control register operations are broken out into helpers that can be
284  * explicitly called on aspeed_timer_reset(), but also from
285  * aspeed_timer_ctrl_op().
286  */
287 
288 static void aspeed_timer_ctrl_enable(AspeedTimer *t, bool enable)
289 {
290     trace_aspeed_timer_ctrl_enable(t->id, enable);
291     if (enable) {
292         t->start = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
293         aspeed_timer_mod(t);
294     } else {
295         timer_del(&t->timer);
296     }
297 }
298 
299 static void aspeed_timer_ctrl_external_clock(AspeedTimer *t, bool enable)
300 {
301     trace_aspeed_timer_ctrl_external_clock(t->id, enable);
302 }
303 
304 static void aspeed_timer_ctrl_overflow_interrupt(AspeedTimer *t, bool enable)
305 {
306     trace_aspeed_timer_ctrl_overflow_interrupt(t->id, enable);
307 }
308 
309 static void aspeed_timer_ctrl_pulse_enable(AspeedTimer *t, bool enable)
310 {
311     if (timer_can_pulse(t)) {
312         trace_aspeed_timer_ctrl_pulse_enable(t->id, enable);
313     } else {
314         qemu_log_mask(LOG_GUEST_ERROR,
315                 "%s: Timer does not support pulse mode\n", __func__);
316     }
317 }
318 
319 /**
320  * Given the actions are fixed in number and completely described in helper
321  * functions, dispatch with a lookup table rather than manage control flow with
322  * a switch statement.
323  */
324 static void (*const ctrl_ops[])(AspeedTimer *, bool) = {
325     [op_enable] = aspeed_timer_ctrl_enable,
326     [op_external_clock] = aspeed_timer_ctrl_external_clock,
327     [op_overflow_interrupt] = aspeed_timer_ctrl_overflow_interrupt,
328     [op_pulse_enable] = aspeed_timer_ctrl_pulse_enable,
329 };
330 
331 /**
332  * Conditionally affect changes chosen by a timer's control bit.
333  *
334  * The aspeed_timer_ctrl_op() interface is convenient for the
335  * aspeed_timer_set_ctrl() function as the "no change" early exit can be
336  * calculated for all operations, which cleans up the caller code. However the
337  * interface isn't convenient for the reset function where we want to enter a
338  * specific state without artificially constructing old and new values that
339  * will fall through the change guard (and motivates extracting the actions
340  * out to helper functions).
341  *
342  * @t: The timer to manipulate
343  * @op: The type of operation to be performed
344  * @old: The old state of the timer's control bits
345  * @new: The incoming state for the timer's control bits
346  */
347 static void aspeed_timer_ctrl_op(AspeedTimer *t, enum timer_ctrl_op op,
348                                  uint8_t old, uint8_t new)
349 {
350     const uint8_t mask = BIT(op);
351     const bool enable = !!(new & mask);
352     const bool changed = ((old ^ new) & mask);
353     if (!changed) {
354         return;
355     }
356     ctrl_ops[op](t, enable);
357 }
358 
359 static void aspeed_timer_set_ctrl(AspeedTimerCtrlState *s, uint32_t reg)
360 {
361     int i;
362     int shift;
363     uint8_t t_old, t_new;
364     AspeedTimer *t;
365     const uint8_t enable_mask = BIT(op_enable);
366 
367     /* Handle a dependency between the 'enable' and remaining three
368      * configuration bits - i.e. if more than one bit in the control set has
369      * changed, including the 'enable' bit, then we want either disable the
370      * timer and perform configuration, or perform configuration and then
371      * enable the timer
372      */
373     for (i = 0; i < ASPEED_TIMER_NR_TIMERS; i++) {
374         t = &s->timers[i];
375         shift = (i * TIMER_CTRL_BITS);
376         t_old = (s->ctrl >> shift) & TIMER_CTRL_MASK;
377         t_new = (reg >> shift) & TIMER_CTRL_MASK;
378 
379         /* If we are disabling, do so first */
380         if ((t_old & enable_mask) && !(t_new & enable_mask)) {
381             aspeed_timer_ctrl_enable(t, false);
382         }
383         aspeed_timer_ctrl_op(t, op_external_clock, t_old, t_new);
384         aspeed_timer_ctrl_op(t, op_overflow_interrupt, t_old, t_new);
385         aspeed_timer_ctrl_op(t, op_pulse_enable, t_old, t_new);
386         /* If we are enabling, do so last */
387         if (!(t_old & enable_mask) && (t_new & enable_mask)) {
388             aspeed_timer_ctrl_enable(t, true);
389         }
390     }
391     s->ctrl = reg;
392 }
393 
394 static void aspeed_timer_set_ctrl2(AspeedTimerCtrlState *s, uint32_t value)
395 {
396     trace_aspeed_timer_set_ctrl2(value);
397 }
398 
399 static void aspeed_timer_write(void *opaque, hwaddr offset, uint64_t value,
400                                unsigned size)
401 {
402     const uint32_t tv = (uint32_t)(value & 0xFFFFFFFF);
403     const int reg = (offset & 0xf) / 4;
404     AspeedTimerCtrlState *s = opaque;
405 
406     switch (offset) {
407     /* Control Registers */
408     case 0x30:
409         aspeed_timer_set_ctrl(s, tv);
410         break;
411     case 0x34:
412         aspeed_timer_set_ctrl2(s, tv);
413         break;
414     /* Timer Registers */
415     case 0x00 ... 0x2c:
416         aspeed_timer_set_value(s, (offset >> TIMER_NR_REGS), reg, tv);
417         break;
418     case 0x40 ... 0x8c:
419         aspeed_timer_set_value(s, (offset >> TIMER_NR_REGS) - 1, reg, tv);
420         break;
421     /* Illegal */
422     case 0x38:
423     case 0x3C:
424     default:
425         qemu_log_mask(LOG_GUEST_ERROR, "%s: Bad offset 0x%" HWADDR_PRIx "\n",
426                 __func__, offset);
427         break;
428     }
429 }
430 
431 static const MemoryRegionOps aspeed_timer_ops = {
432     .read = aspeed_timer_read,
433     .write = aspeed_timer_write,
434     .endianness = DEVICE_LITTLE_ENDIAN,
435     .valid.min_access_size = 4,
436     .valid.max_access_size = 4,
437     .valid.unaligned = false,
438 };
439 
440 static void aspeed_init_one_timer(AspeedTimerCtrlState *s, uint8_t id)
441 {
442     AspeedTimer *t = &s->timers[id];
443 
444     t->id = id;
445     timer_init_ns(&t->timer, QEMU_CLOCK_VIRTUAL, aspeed_timer_expire, t);
446 }
447 
448 static void aspeed_timer_realize(DeviceState *dev, Error **errp)
449 {
450     int i;
451     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
452     AspeedTimerCtrlState *s = ASPEED_TIMER(dev);
453     Object *obj;
454     Error *err = NULL;
455 
456     obj = object_property_get_link(OBJECT(dev), "scu", &err);
457     if (!obj) {
458         error_propagate(errp, err);
459         error_prepend(errp, "required link 'scu' not found: ");
460         return;
461     }
462     s->scu = ASPEED_SCU(obj);
463 
464     for (i = 0; i < ASPEED_TIMER_NR_TIMERS; i++) {
465         aspeed_init_one_timer(s, i);
466         sysbus_init_irq(sbd, &s->timers[i].irq);
467     }
468     memory_region_init_io(&s->iomem, OBJECT(s), &aspeed_timer_ops, s,
469                           TYPE_ASPEED_TIMER, 0x1000);
470     sysbus_init_mmio(sbd, &s->iomem);
471 }
472 
473 static void aspeed_timer_reset(DeviceState *dev)
474 {
475     int i;
476     AspeedTimerCtrlState *s = ASPEED_TIMER(dev);
477 
478     for (i = 0; i < ASPEED_TIMER_NR_TIMERS; i++) {
479         AspeedTimer *t = &s->timers[i];
480         /* Explicitly call helpers to avoid any conditional behaviour through
481          * aspeed_timer_set_ctrl().
482          */
483         aspeed_timer_ctrl_enable(t, false);
484         aspeed_timer_ctrl_external_clock(t, TIMER_CLOCK_USE_APB);
485         aspeed_timer_ctrl_overflow_interrupt(t, false);
486         aspeed_timer_ctrl_pulse_enable(t, false);
487         t->level = 0;
488         t->reload = 0;
489         t->match[0] = 0;
490         t->match[1] = 0;
491     }
492     s->ctrl = 0;
493     s->ctrl2 = 0;
494 }
495 
496 static const VMStateDescription vmstate_aspeed_timer = {
497     .name = "aspeed.timer",
498     .version_id = 2,
499     .minimum_version_id = 2,
500     .fields = (VMStateField[]) {
501         VMSTATE_UINT8(id, AspeedTimer),
502         VMSTATE_INT32(level, AspeedTimer),
503         VMSTATE_TIMER(timer, AspeedTimer),
504         VMSTATE_UINT32(reload, AspeedTimer),
505         VMSTATE_UINT32_ARRAY(match, AspeedTimer, 2),
506         VMSTATE_END_OF_LIST()
507     }
508 };
509 
510 static const VMStateDescription vmstate_aspeed_timer_state = {
511     .name = "aspeed.timerctrl",
512     .version_id = 1,
513     .minimum_version_id = 1,
514     .fields = (VMStateField[]) {
515         VMSTATE_UINT32(ctrl, AspeedTimerCtrlState),
516         VMSTATE_UINT32(ctrl2, AspeedTimerCtrlState),
517         VMSTATE_STRUCT_ARRAY(timers, AspeedTimerCtrlState,
518                              ASPEED_TIMER_NR_TIMERS, 1, vmstate_aspeed_timer,
519                              AspeedTimer),
520         VMSTATE_END_OF_LIST()
521     }
522 };
523 
524 static void timer_class_init(ObjectClass *klass, void *data)
525 {
526     DeviceClass *dc = DEVICE_CLASS(klass);
527 
528     dc->realize = aspeed_timer_realize;
529     dc->reset = aspeed_timer_reset;
530     dc->desc = "ASPEED Timer";
531     dc->vmsd = &vmstate_aspeed_timer_state;
532 }
533 
534 static const TypeInfo aspeed_timer_info = {
535     .name = TYPE_ASPEED_TIMER,
536     .parent = TYPE_SYS_BUS_DEVICE,
537     .instance_size = sizeof(AspeedTimerCtrlState),
538     .class_init = timer_class_init,
539 };
540 
541 static void aspeed_timer_register_types(void)
542 {
543     type_register_static(&aspeed_timer_info);
544 }
545 
546 type_init(aspeed_timer_register_types)
547