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