xref: /openbmc/qemu/hw/intc/armv7m_nvic.c (revision f7759e4331ed04b2128af36efd395e55e3076406)
1 /*
2  * ARM Nested Vectored Interrupt Controller
3  *
4  * Copyright (c) 2006-2007 CodeSourcery.
5  * Written by Paul Brook
6  *
7  * This code is licensed under the GPL.
8  *
9  * The ARMv7M System controller is fairly tightly tied in with the
10  * NVIC.  Much of that is also implemented here.
11  */
12 
13 #include "qemu/osdep.h"
14 #include "qapi/error.h"
15 #include "qemu-common.h"
16 #include "cpu.h"
17 #include "hw/sysbus.h"
18 #include "qemu/timer.h"
19 #include "hw/arm/arm.h"
20 #include "target/arm/cpu.h"
21 #include "exec/address-spaces.h"
22 #include "qemu/log.h"
23 #include "trace.h"
24 
25 /* IRQ number counting:
26  *
27  * the num-irq property counts the number of external IRQ lines
28  *
29  * NVICState::num_irq counts the total number of exceptions
30  * (external IRQs, the 15 internal exceptions including reset,
31  * and one for the unused exception number 0).
32  *
33  * NVIC_MAX_IRQ is the highest permitted number of external IRQ lines.
34  *
35  * NVIC_MAX_VECTORS is the highest permitted number of exceptions.
36  *
37  * Iterating through all exceptions should typically be done with
38  * for (i = 1; i < s->num_irq; i++) to avoid the unused slot 0.
39  *
40  * The external qemu_irq lines are the NVIC's external IRQ lines,
41  * so line 0 is exception 16.
42  *
43  * In the terminology of the architecture manual, "interrupts" are
44  * a subcategory of exception referring to the external interrupts
45  * (which are exception numbers NVIC_FIRST_IRQ and upward).
46  * For historical reasons QEMU tends to use "interrupt" and
47  * "exception" more or less interchangeably.
48  */
49 #define NVIC_FIRST_IRQ 16
50 #define NVIC_MAX_VECTORS 512
51 #define NVIC_MAX_IRQ (NVIC_MAX_VECTORS - NVIC_FIRST_IRQ)
52 
53 /* Effective running priority of the CPU when no exception is active
54  * (higher than the highest possible priority value)
55  */
56 #define NVIC_NOEXC_PRIO 0x100
57 
58 typedef struct VecInfo {
59     /* Exception priorities can range from -3 to 255; only the unmodifiable
60      * priority values for RESET, NMI and HardFault can be negative.
61      */
62     int16_t prio;
63     uint8_t enabled;
64     uint8_t pending;
65     uint8_t active;
66     uint8_t level; /* exceptions <=15 never set level */
67 } VecInfo;
68 
69 typedef struct NVICState {
70     /*< private >*/
71     SysBusDevice parent_obj;
72     /*< public >*/
73 
74     ARMCPU *cpu;
75 
76     VecInfo vectors[NVIC_MAX_VECTORS];
77     uint32_t prigroup;
78 
79     /* vectpending and exception_prio are both cached state that can
80      * be recalculated from the vectors[] array and the prigroup field.
81      */
82     unsigned int vectpending; /* highest prio pending enabled exception */
83     int exception_prio; /* group prio of the highest prio active exception */
84 
85     struct {
86         uint32_t control;
87         uint32_t reload;
88         int64_t tick;
89         QEMUTimer *timer;
90     } systick;
91 
92     MemoryRegion sysregmem;
93     MemoryRegion container;
94 
95     uint32_t num_irq;
96     qemu_irq excpout;
97     qemu_irq sysresetreq;
98 } NVICState;
99 
100 #define TYPE_NVIC "armv7m_nvic"
101 
102 #define NVIC(obj) \
103     OBJECT_CHECK(NVICState, (obj), TYPE_NVIC)
104 
105 static const uint8_t nvic_id[] = {
106     0x00, 0xb0, 0x1b, 0x00, 0x0d, 0xe0, 0x05, 0xb1
107 };
108 
109 /* qemu timers run at 1GHz.   We want something closer to 1MHz.  */
110 #define SYSTICK_SCALE 1000ULL
111 
112 #define SYSTICK_ENABLE    (1 << 0)
113 #define SYSTICK_TICKINT   (1 << 1)
114 #define SYSTICK_CLKSOURCE (1 << 2)
115 #define SYSTICK_COUNTFLAG (1 << 16)
116 
117 int system_clock_scale;
118 
119 /* Conversion factor from qemu timer to SysTick frequencies.  */
120 static inline int64_t systick_scale(NVICState *s)
121 {
122     if (s->systick.control & SYSTICK_CLKSOURCE)
123         return system_clock_scale;
124     else
125         return 1000;
126 }
127 
128 static void systick_reload(NVICState *s, int reset)
129 {
130     /* The Cortex-M3 Devices Generic User Guide says that "When the
131      * ENABLE bit is set to 1, the counter loads the RELOAD value from the
132      * SYST RVR register and then counts down". So, we need to check the
133      * ENABLE bit before reloading the value.
134      */
135     if ((s->systick.control & SYSTICK_ENABLE) == 0) {
136         return;
137     }
138 
139     if (reset)
140         s->systick.tick = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
141     s->systick.tick += (s->systick.reload + 1) * systick_scale(s);
142     timer_mod(s->systick.timer, s->systick.tick);
143 }
144 
145 static void systick_timer_tick(void * opaque)
146 {
147     NVICState *s = (NVICState *)opaque;
148     s->systick.control |= SYSTICK_COUNTFLAG;
149     if (s->systick.control & SYSTICK_TICKINT) {
150         /* Trigger the interrupt.  */
151         armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK);
152     }
153     if (s->systick.reload == 0) {
154         s->systick.control &= ~SYSTICK_ENABLE;
155     } else {
156         systick_reload(s, 0);
157     }
158 }
159 
160 static void systick_reset(NVICState *s)
161 {
162     s->systick.control = 0;
163     s->systick.reload = 0;
164     s->systick.tick = 0;
165     timer_del(s->systick.timer);
166 }
167 
168 static int nvic_pending_prio(NVICState *s)
169 {
170     /* return the priority of the current pending interrupt,
171      * or NVIC_NOEXC_PRIO if no interrupt is pending
172      */
173     return s->vectpending ? s->vectors[s->vectpending].prio : NVIC_NOEXC_PRIO;
174 }
175 
176 /* Return the value of the ISCR RETTOBASE bit:
177  * 1 if there is exactly one active exception
178  * 0 if there is more than one active exception
179  * UNKNOWN if there are no active exceptions (we choose 1,
180  * which matches the choice Cortex-M3 is documented as making).
181  *
182  * NB: some versions of the documentation talk about this
183  * counting "active exceptions other than the one shown by IPSR";
184  * this is only different in the obscure corner case where guest
185  * code has manually deactivated an exception and is about
186  * to fail an exception-return integrity check. The definition
187  * above is the one from the v8M ARM ARM and is also in line
188  * with the behaviour documented for the Cortex-M3.
189  */
190 static bool nvic_rettobase(NVICState *s)
191 {
192     int irq, nhand = 0;
193 
194     for (irq = ARMV7M_EXCP_RESET; irq < s->num_irq; irq++) {
195         if (s->vectors[irq].active) {
196             nhand++;
197             if (nhand == 2) {
198                 return 0;
199             }
200         }
201     }
202 
203     return 1;
204 }
205 
206 /* Return the value of the ISCR ISRPENDING bit:
207  * 1 if an external interrupt is pending
208  * 0 if no external interrupt is pending
209  */
210 static bool nvic_isrpending(NVICState *s)
211 {
212     int irq;
213 
214     /* We can shortcut if the highest priority pending interrupt
215      * happens to be external or if there is nothing pending.
216      */
217     if (s->vectpending > NVIC_FIRST_IRQ) {
218         return true;
219     }
220     if (s->vectpending == 0) {
221         return false;
222     }
223 
224     for (irq = NVIC_FIRST_IRQ; irq < s->num_irq; irq++) {
225         if (s->vectors[irq].pending) {
226             return true;
227         }
228     }
229     return false;
230 }
231 
232 /* Return a mask word which clears the subpriority bits from
233  * a priority value for an M-profile exception, leaving only
234  * the group priority.
235  */
236 static inline uint32_t nvic_gprio_mask(NVICState *s)
237 {
238     return ~0U << (s->prigroup + 1);
239 }
240 
241 /* Recompute vectpending and exception_prio */
242 static void nvic_recompute_state(NVICState *s)
243 {
244     int i;
245     int pend_prio = NVIC_NOEXC_PRIO;
246     int active_prio = NVIC_NOEXC_PRIO;
247     int pend_irq = 0;
248 
249     for (i = 1; i < s->num_irq; i++) {
250         VecInfo *vec = &s->vectors[i];
251 
252         if (vec->enabled && vec->pending && vec->prio < pend_prio) {
253             pend_prio = vec->prio;
254             pend_irq = i;
255         }
256         if (vec->active && vec->prio < active_prio) {
257             active_prio = vec->prio;
258         }
259     }
260 
261     s->vectpending = pend_irq;
262     s->exception_prio = active_prio & nvic_gprio_mask(s);
263 
264     trace_nvic_recompute_state(s->vectpending, s->exception_prio);
265 }
266 
267 /* Return the current execution priority of the CPU
268  * (equivalent to the pseudocode ExecutionPriority function).
269  * This is a value between -2 (NMI priority) and NVIC_NOEXC_PRIO.
270  */
271 static inline int nvic_exec_prio(NVICState *s)
272 {
273     CPUARMState *env = &s->cpu->env;
274     int running;
275 
276     if (env->daif & PSTATE_F) { /* FAULTMASK */
277         running = -1;
278     } else if (env->daif & PSTATE_I) { /* PRIMASK */
279         running = 0;
280     } else if (env->v7m.basepri > 0) {
281         running = env->v7m.basepri & nvic_gprio_mask(s);
282     } else {
283         running = NVIC_NOEXC_PRIO; /* lower than any possible priority */
284     }
285     /* consider priority of active handler */
286     return MIN(running, s->exception_prio);
287 }
288 
289 bool armv7m_nvic_can_take_pending_exception(void *opaque)
290 {
291     NVICState *s = opaque;
292 
293     return nvic_exec_prio(s) > nvic_pending_prio(s);
294 }
295 
296 /* caller must call nvic_irq_update() after this */
297 static void set_prio(NVICState *s, unsigned irq, uint8_t prio)
298 {
299     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
300     assert(irq < s->num_irq);
301 
302     s->vectors[irq].prio = prio;
303 
304     trace_nvic_set_prio(irq, prio);
305 }
306 
307 /* Recompute state and assert irq line accordingly.
308  * Must be called after changes to:
309  *  vec->active, vec->enabled, vec->pending or vec->prio for any vector
310  *  prigroup
311  */
312 static void nvic_irq_update(NVICState *s)
313 {
314     int lvl;
315     int pend_prio;
316 
317     nvic_recompute_state(s);
318     pend_prio = nvic_pending_prio(s);
319 
320     /* Raise NVIC output if this IRQ would be taken, except that we
321      * ignore the effects of the BASEPRI, FAULTMASK and PRIMASK (which
322      * will be checked for in arm_v7m_cpu_exec_interrupt()); changes
323      * to those CPU registers don't cause us to recalculate the NVIC
324      * pending info.
325      */
326     lvl = (pend_prio < s->exception_prio);
327     trace_nvic_irq_update(s->vectpending, pend_prio, s->exception_prio, lvl);
328     qemu_set_irq(s->excpout, lvl);
329 }
330 
331 static void armv7m_nvic_clear_pending(void *opaque, int irq)
332 {
333     NVICState *s = (NVICState *)opaque;
334     VecInfo *vec;
335 
336     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
337 
338     vec = &s->vectors[irq];
339     trace_nvic_clear_pending(irq, vec->enabled, vec->prio);
340     if (vec->pending) {
341         vec->pending = 0;
342         nvic_irq_update(s);
343     }
344 }
345 
346 void armv7m_nvic_set_pending(void *opaque, int irq)
347 {
348     NVICState *s = (NVICState *)opaque;
349     VecInfo *vec;
350 
351     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
352 
353     vec = &s->vectors[irq];
354     trace_nvic_set_pending(irq, vec->enabled, vec->prio);
355 
356 
357     if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {
358         /* If a synchronous exception is pending then it may be
359          * escalated to HardFault if:
360          *  * it is equal or lower priority to current execution
361          *  * it is disabled
362          * (ie we need to take it immediately but we can't do so).
363          * Asynchronous exceptions (and interrupts) simply remain pending.
364          *
365          * For QEMU, we don't have any imprecise (asynchronous) faults,
366          * so we can assume that PREFETCH_ABORT and DATA_ABORT are always
367          * synchronous.
368          * Debug exceptions are awkward because only Debug exceptions
369          * resulting from the BKPT instruction should be escalated,
370          * but we don't currently implement any Debug exceptions other
371          * than those that result from BKPT, so we treat all debug exceptions
372          * as needing escalation.
373          *
374          * This all means we can identify whether to escalate based only on
375          * the exception number and don't (yet) need the caller to explicitly
376          * tell us whether this exception is synchronous or not.
377          */
378         int running = nvic_exec_prio(s);
379         bool escalate = false;
380 
381         if (vec->prio >= running) {
382             trace_nvic_escalate_prio(irq, vec->prio, running);
383             escalate = true;
384         } else if (!vec->enabled) {
385             trace_nvic_escalate_disabled(irq);
386             escalate = true;
387         }
388 
389         if (escalate) {
390             if (running < 0) {
391                 /* We want to escalate to HardFault but we can't take a
392                  * synchronous HardFault at this point either. This is a
393                  * Lockup condition due to a guest bug. We don't model
394                  * Lockup, so report via cpu_abort() instead.
395                  */
396                 cpu_abort(&s->cpu->parent_obj,
397                           "Lockup: can't escalate %d to HardFault "
398                           "(current priority %d)\n", irq, running);
399             }
400 
401             /* We can do the escalation, so we take HardFault instead */
402             irq = ARMV7M_EXCP_HARD;
403             vec = &s->vectors[irq];
404             s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;
405         }
406     }
407 
408     if (!vec->pending) {
409         vec->pending = 1;
410         nvic_irq_update(s);
411     }
412 }
413 
414 /* Make pending IRQ active.  */
415 void armv7m_nvic_acknowledge_irq(void *opaque)
416 {
417     NVICState *s = (NVICState *)opaque;
418     CPUARMState *env = &s->cpu->env;
419     const int pending = s->vectpending;
420     const int running = nvic_exec_prio(s);
421     int pendgroupprio;
422     VecInfo *vec;
423 
424     assert(pending > ARMV7M_EXCP_RESET && pending < s->num_irq);
425 
426     vec = &s->vectors[pending];
427 
428     assert(vec->enabled);
429     assert(vec->pending);
430 
431     pendgroupprio = vec->prio & nvic_gprio_mask(s);
432     assert(pendgroupprio < running);
433 
434     trace_nvic_acknowledge_irq(pending, vec->prio);
435 
436     vec->active = 1;
437     vec->pending = 0;
438 
439     env->v7m.exception = s->vectpending;
440 
441     nvic_irq_update(s);
442 }
443 
444 int armv7m_nvic_complete_irq(void *opaque, int irq)
445 {
446     NVICState *s = (NVICState *)opaque;
447     VecInfo *vec;
448     int ret;
449 
450     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
451 
452     vec = &s->vectors[irq];
453 
454     trace_nvic_complete_irq(irq);
455 
456     if (!vec->active) {
457         /* Tell the caller this was an illegal exception return */
458         return -1;
459     }
460 
461     ret = nvic_rettobase(s);
462 
463     vec->active = 0;
464     if (vec->level) {
465         /* Re-pend the exception if it's still held high; only
466          * happens for extenal IRQs
467          */
468         assert(irq >= NVIC_FIRST_IRQ);
469         vec->pending = 1;
470     }
471 
472     nvic_irq_update(s);
473 
474     return ret;
475 }
476 
477 /* callback when external interrupt line is changed */
478 static void set_irq_level(void *opaque, int n, int level)
479 {
480     NVICState *s = opaque;
481     VecInfo *vec;
482 
483     n += NVIC_FIRST_IRQ;
484 
485     assert(n >= NVIC_FIRST_IRQ && n < s->num_irq);
486 
487     trace_nvic_set_irq_level(n, level);
488 
489     /* The pending status of an external interrupt is
490      * latched on rising edge and exception handler return.
491      *
492      * Pulsing the IRQ will always run the handler
493      * once, and the handler will re-run until the
494      * level is low when the handler completes.
495      */
496     vec = &s->vectors[n];
497     if (level != vec->level) {
498         vec->level = level;
499         if (level) {
500             armv7m_nvic_set_pending(s, n);
501         }
502     }
503 }
504 
505 static uint32_t nvic_readl(NVICState *s, uint32_t offset)
506 {
507     ARMCPU *cpu = s->cpu;
508     uint32_t val;
509 
510     switch (offset) {
511     case 4: /* Interrupt Control Type.  */
512         return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;
513     case 0x10: /* SysTick Control and Status.  */
514         val = s->systick.control;
515         s->systick.control &= ~SYSTICK_COUNTFLAG;
516         return val;
517     case 0x14: /* SysTick Reload Value.  */
518         return s->systick.reload;
519     case 0x18: /* SysTick Current Value.  */
520         {
521             int64_t t;
522             if ((s->systick.control & SYSTICK_ENABLE) == 0)
523                 return 0;
524             t = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
525             if (t >= s->systick.tick)
526                 return 0;
527             val = ((s->systick.tick - (t + 1)) / systick_scale(s)) + 1;
528             /* The interrupt in triggered when the timer reaches zero.
529                However the counter is not reloaded until the next clock
530                tick.  This is a hack to return zero during the first tick.  */
531             if (val > s->systick.reload)
532                 val = 0;
533             return val;
534         }
535     case 0x1c: /* SysTick Calibration Value.  */
536         return 10000;
537     case 0xd00: /* CPUID Base.  */
538         return cpu->midr;
539     case 0xd04: /* Interrupt Control State.  */
540         /* VECTACTIVE */
541         val = cpu->env.v7m.exception;
542         /* VECTPENDING */
543         val |= (s->vectpending & 0xff) << 12;
544         /* ISRPENDING - set if any external IRQ is pending */
545         if (nvic_isrpending(s)) {
546             val |= (1 << 22);
547         }
548         /* RETTOBASE - set if only one handler is active */
549         if (nvic_rettobase(s)) {
550             val |= (1 << 11);
551         }
552         /* PENDSTSET */
553         if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {
554             val |= (1 << 26);
555         }
556         /* PENDSVSET */
557         if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {
558             val |= (1 << 28);
559         }
560         /* NMIPENDSET */
561         if (s->vectors[ARMV7M_EXCP_NMI].pending) {
562             val |= (1 << 31);
563         }
564         /* ISRPREEMPT not implemented */
565         return val;
566     case 0xd08: /* Vector Table Offset.  */
567         return cpu->env.v7m.vecbase;
568     case 0xd0c: /* Application Interrupt/Reset Control.  */
569         return 0xfa050000 | (s->prigroup << 8);
570     case 0xd10: /* System Control.  */
571         /* TODO: Implement SLEEPONEXIT.  */
572         return 0;
573     case 0xd14: /* Configuration Control.  */
574         return cpu->env.v7m.ccr;
575     case 0xd24: /* System Handler Status.  */
576         val = 0;
577         if (s->vectors[ARMV7M_EXCP_MEM].active) {
578             val |= (1 << 0);
579         }
580         if (s->vectors[ARMV7M_EXCP_BUS].active) {
581             val |= (1 << 1);
582         }
583         if (s->vectors[ARMV7M_EXCP_USAGE].active) {
584             val |= (1 << 3);
585         }
586         if (s->vectors[ARMV7M_EXCP_SVC].active) {
587             val |= (1 << 7);
588         }
589         if (s->vectors[ARMV7M_EXCP_DEBUG].active) {
590             val |= (1 << 8);
591         }
592         if (s->vectors[ARMV7M_EXCP_PENDSV].active) {
593             val |= (1 << 10);
594         }
595         if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {
596             val |= (1 << 11);
597         }
598         if (s->vectors[ARMV7M_EXCP_USAGE].pending) {
599             val |= (1 << 12);
600         }
601         if (s->vectors[ARMV7M_EXCP_MEM].pending) {
602             val |= (1 << 13);
603         }
604         if (s->vectors[ARMV7M_EXCP_BUS].pending) {
605             val |= (1 << 14);
606         }
607         if (s->vectors[ARMV7M_EXCP_SVC].pending) {
608             val |= (1 << 15);
609         }
610         if (s->vectors[ARMV7M_EXCP_MEM].enabled) {
611             val |= (1 << 16);
612         }
613         if (s->vectors[ARMV7M_EXCP_BUS].enabled) {
614             val |= (1 << 17);
615         }
616         if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {
617             val |= (1 << 18);
618         }
619         return val;
620     case 0xd28: /* Configurable Fault Status.  */
621         return cpu->env.v7m.cfsr;
622     case 0xd2c: /* Hard Fault Status.  */
623         return cpu->env.v7m.hfsr;
624     case 0xd30: /* Debug Fault Status.  */
625         return cpu->env.v7m.dfsr;
626     case 0xd34: /* MMFAR MemManage Fault Address */
627         return cpu->env.v7m.mmfar;
628     case 0xd38: /* Bus Fault Address.  */
629         return cpu->env.v7m.bfar;
630     case 0xd3c: /* Aux Fault Status.  */
631         /* TODO: Implement fault status registers.  */
632         qemu_log_mask(LOG_UNIMP,
633                       "Aux Fault status registers unimplemented\n");
634         return 0;
635     case 0xd40: /* PFR0.  */
636         return 0x00000030;
637     case 0xd44: /* PRF1.  */
638         return 0x00000200;
639     case 0xd48: /* DFR0.  */
640         return 0x00100000;
641     case 0xd4c: /* AFR0.  */
642         return 0x00000000;
643     case 0xd50: /* MMFR0.  */
644         return 0x00000030;
645     case 0xd54: /* MMFR1.  */
646         return 0x00000000;
647     case 0xd58: /* MMFR2.  */
648         return 0x00000000;
649     case 0xd5c: /* MMFR3.  */
650         return 0x00000000;
651     case 0xd60: /* ISAR0.  */
652         return 0x01141110;
653     case 0xd64: /* ISAR1.  */
654         return 0x02111000;
655     case 0xd68: /* ISAR2.  */
656         return 0x21112231;
657     case 0xd6c: /* ISAR3.  */
658         return 0x01111110;
659     case 0xd70: /* ISAR4.  */
660         return 0x01310102;
661     /* TODO: Implement debug registers.  */
662     default:
663         qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);
664         return 0;
665     }
666 }
667 
668 static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value)
669 {
670     ARMCPU *cpu = s->cpu;
671     uint32_t oldval;
672     switch (offset) {
673     case 0x10: /* SysTick Control and Status.  */
674         oldval = s->systick.control;
675         s->systick.control &= 0xfffffff8;
676         s->systick.control |= value & 7;
677         if ((oldval ^ value) & SYSTICK_ENABLE) {
678             int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
679             if (value & SYSTICK_ENABLE) {
680                 if (s->systick.tick) {
681                     s->systick.tick += now;
682                     timer_mod(s->systick.timer, s->systick.tick);
683                 } else {
684                     systick_reload(s, 1);
685                 }
686             } else {
687                 timer_del(s->systick.timer);
688                 s->systick.tick -= now;
689                 if (s->systick.tick < 0)
690                   s->systick.tick = 0;
691             }
692         } else if ((oldval ^ value) & SYSTICK_CLKSOURCE) {
693             /* This is a hack. Force the timer to be reloaded
694                when the reference clock is changed.  */
695             systick_reload(s, 1);
696         }
697         break;
698     case 0x14: /* SysTick Reload Value.  */
699         s->systick.reload = value;
700         break;
701     case 0x18: /* SysTick Current Value.  Writes reload the timer.  */
702         systick_reload(s, 1);
703         s->systick.control &= ~SYSTICK_COUNTFLAG;
704         break;
705     case 0xd04: /* Interrupt Control State.  */
706         if (value & (1 << 31)) {
707             armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI);
708         }
709         if (value & (1 << 28)) {
710             armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV);
711         } else if (value & (1 << 27)) {
712             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV);
713         }
714         if (value & (1 << 26)) {
715             armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK);
716         } else if (value & (1 << 25)) {
717             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK);
718         }
719         break;
720     case 0xd08: /* Vector Table Offset.  */
721         cpu->env.v7m.vecbase = value & 0xffffff80;
722         break;
723     case 0xd0c: /* Application Interrupt/Reset Control.  */
724         if ((value >> 16) == 0x05fa) {
725             if (value & 4) {
726                 qemu_irq_pulse(s->sysresetreq);
727             }
728             if (value & 2) {
729                 qemu_log_mask(LOG_GUEST_ERROR,
730                               "Setting VECTCLRACTIVE when not in DEBUG mode "
731                               "is UNPREDICTABLE\n");
732             }
733             if (value & 1) {
734                 qemu_log_mask(LOG_GUEST_ERROR,
735                               "Setting VECTRESET when not in DEBUG mode "
736                               "is UNPREDICTABLE\n");
737             }
738             s->prigroup = extract32(value, 8, 3);
739             nvic_irq_update(s);
740         }
741         break;
742     case 0xd10: /* System Control.  */
743         /* TODO: Implement control registers.  */
744         qemu_log_mask(LOG_UNIMP, "NVIC: SCR unimplemented\n");
745         break;
746     case 0xd14: /* Configuration Control.  */
747         /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */
748         value &= (R_V7M_CCR_STKALIGN_MASK |
749                   R_V7M_CCR_BFHFNMIGN_MASK |
750                   R_V7M_CCR_DIV_0_TRP_MASK |
751                   R_V7M_CCR_UNALIGN_TRP_MASK |
752                   R_V7M_CCR_USERSETMPEND_MASK |
753                   R_V7M_CCR_NONBASETHRDENA_MASK);
754 
755         cpu->env.v7m.ccr = value;
756         break;
757     case 0xd24: /* System Handler Control.  */
758         s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
759         s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;
760         s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
761         s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
762         s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;
763         s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;
764         s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;
765         s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;
766         s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
767         s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;
768         s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
769         s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
770         s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
771         s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;
772         nvic_irq_update(s);
773         break;
774     case 0xd28: /* Configurable Fault Status.  */
775         cpu->env.v7m.cfsr &= ~value; /* W1C */
776         break;
777     case 0xd2c: /* Hard Fault Status.  */
778         cpu->env.v7m.hfsr &= ~value; /* W1C */
779         break;
780     case 0xd30: /* Debug Fault Status.  */
781         cpu->env.v7m.dfsr &= ~value; /* W1C */
782         break;
783     case 0xd34: /* Mem Manage Address.  */
784         cpu->env.v7m.mmfar = value;
785         return;
786     case 0xd38: /* Bus Fault Address.  */
787         cpu->env.v7m.bfar = value;
788         return;
789     case 0xd3c: /* Aux Fault Status.  */
790         qemu_log_mask(LOG_UNIMP,
791                       "NVIC: Aux fault status registers unimplemented\n");
792         break;
793     case 0xf00: /* Software Triggered Interrupt Register */
794     {
795         /* user mode can only write to STIR if CCR.USERSETMPEND permits it */
796         int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;
797         if (excnum < s->num_irq &&
798             (arm_current_el(&cpu->env) ||
799              (cpu->env.v7m.ccr & R_V7M_CCR_USERSETMPEND_MASK))) {
800             armv7m_nvic_set_pending(s, excnum);
801         }
802         break;
803     }
804     default:
805         qemu_log_mask(LOG_GUEST_ERROR,
806                       "NVIC: Bad write offset 0x%x\n", offset);
807     }
808 }
809 
810 static uint64_t nvic_sysreg_read(void *opaque, hwaddr addr,
811                                  unsigned size)
812 {
813     NVICState *s = (NVICState *)opaque;
814     uint32_t offset = addr;
815     unsigned i, startvec, end;
816     uint32_t val;
817 
818     switch (offset) {
819     /* reads of set and clear both return the status */
820     case 0x100 ... 0x13f: /* NVIC Set enable */
821         offset += 0x80;
822         /* fall through */
823     case 0x180 ... 0x1bf: /* NVIC Clear enable */
824         val = 0;
825         startvec = offset - 0x180 + NVIC_FIRST_IRQ; /* vector # */
826 
827         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
828             if (s->vectors[startvec + i].enabled) {
829                 val |= (1 << i);
830             }
831         }
832         break;
833     case 0x200 ... 0x23f: /* NVIC Set pend */
834         offset += 0x80;
835         /* fall through */
836     case 0x280 ... 0x2bf: /* NVIC Clear pend */
837         val = 0;
838         startvec = offset - 0x280 + NVIC_FIRST_IRQ; /* vector # */
839         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
840             if (s->vectors[startvec + i].pending) {
841                 val |= (1 << i);
842             }
843         }
844         break;
845     case 0x300 ... 0x33f: /* NVIC Active */
846         val = 0;
847         startvec = offset - 0x300 + NVIC_FIRST_IRQ; /* vector # */
848 
849         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
850             if (s->vectors[startvec + i].active) {
851                 val |= (1 << i);
852             }
853         }
854         break;
855     case 0x400 ... 0x5ef: /* NVIC Priority */
856         val = 0;
857         startvec = offset - 0x400 + NVIC_FIRST_IRQ; /* vector # */
858 
859         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
860             val |= s->vectors[startvec + i].prio << (8 * i);
861         }
862         break;
863     case 0xd18 ... 0xd23: /* System Handler Priority.  */
864         val = 0;
865         for (i = 0; i < size; i++) {
866             val |= s->vectors[(offset - 0xd14) + i].prio << (i * 8);
867         }
868         break;
869     case 0xfe0 ... 0xfff: /* ID.  */
870         if (offset & 3) {
871             val = 0;
872         } else {
873             val = nvic_id[(offset - 0xfe0) >> 2];
874         }
875         break;
876     default:
877         if (size == 4) {
878             val = nvic_readl(s, offset);
879         } else {
880             qemu_log_mask(LOG_GUEST_ERROR,
881                           "NVIC: Bad read of size %d at offset 0x%x\n",
882                           size, offset);
883             val = 0;
884         }
885     }
886 
887     trace_nvic_sysreg_read(addr, val, size);
888     return val;
889 }
890 
891 static void nvic_sysreg_write(void *opaque, hwaddr addr,
892                               uint64_t value, unsigned size)
893 {
894     NVICState *s = (NVICState *)opaque;
895     uint32_t offset = addr;
896     unsigned i, startvec, end;
897     unsigned setval = 0;
898 
899     trace_nvic_sysreg_write(addr, value, size);
900 
901     switch (offset) {
902     case 0x100 ... 0x13f: /* NVIC Set enable */
903         offset += 0x80;
904         setval = 1;
905         /* fall through */
906     case 0x180 ... 0x1bf: /* NVIC Clear enable */
907         startvec = 8 * (offset - 0x180) + NVIC_FIRST_IRQ;
908 
909         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
910             if (value & (1 << i)) {
911                 s->vectors[startvec + i].enabled = setval;
912             }
913         }
914         nvic_irq_update(s);
915         return;
916     case 0x200 ... 0x23f: /* NVIC Set pend */
917         /* the special logic in armv7m_nvic_set_pending()
918          * is not needed since IRQs are never escalated
919          */
920         offset += 0x80;
921         setval = 1;
922         /* fall through */
923     case 0x280 ... 0x2bf: /* NVIC Clear pend */
924         startvec = 8 * (offset - 0x280) + NVIC_FIRST_IRQ; /* vector # */
925 
926         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
927             if (value & (1 << i)) {
928                 s->vectors[startvec + i].pending = setval;
929             }
930         }
931         nvic_irq_update(s);
932         return;
933     case 0x300 ... 0x33f: /* NVIC Active */
934         return; /* R/O */
935     case 0x400 ... 0x5ef: /* NVIC Priority */
936         startvec = 8 * (offset - 0x400) + NVIC_FIRST_IRQ; /* vector # */
937 
938         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
939             set_prio(s, startvec + i, (value >> (i * 8)) & 0xff);
940         }
941         nvic_irq_update(s);
942         return;
943     case 0xd18 ... 0xd23: /* System Handler Priority.  */
944         for (i = 0; i < size; i++) {
945             unsigned hdlidx = (offset - 0xd14) + i;
946             set_prio(s, hdlidx, (value >> (i * 8)) & 0xff);
947         }
948         nvic_irq_update(s);
949         return;
950     }
951     if (size == 4) {
952         nvic_writel(s, offset, value);
953         return;
954     }
955     qemu_log_mask(LOG_GUEST_ERROR,
956                   "NVIC: Bad write of size %d at offset 0x%x\n", size, offset);
957 }
958 
959 static const MemoryRegionOps nvic_sysreg_ops = {
960     .read = nvic_sysreg_read,
961     .write = nvic_sysreg_write,
962     .endianness = DEVICE_NATIVE_ENDIAN,
963 };
964 
965 static int nvic_post_load(void *opaque, int version_id)
966 {
967     NVICState *s = opaque;
968     unsigned i;
969 
970     /* Check for out of range priority settings */
971     if (s->vectors[ARMV7M_EXCP_RESET].prio != -3 ||
972         s->vectors[ARMV7M_EXCP_NMI].prio != -2 ||
973         s->vectors[ARMV7M_EXCP_HARD].prio != -1) {
974         return 1;
975     }
976     for (i = ARMV7M_EXCP_MEM; i < s->num_irq; i++) {
977         if (s->vectors[i].prio & ~0xff) {
978             return 1;
979         }
980     }
981 
982     nvic_recompute_state(s);
983 
984     return 0;
985 }
986 
987 static const VMStateDescription vmstate_VecInfo = {
988     .name = "armv7m_nvic_info",
989     .version_id = 1,
990     .minimum_version_id = 1,
991     .fields = (VMStateField[]) {
992         VMSTATE_INT16(prio, VecInfo),
993         VMSTATE_UINT8(enabled, VecInfo),
994         VMSTATE_UINT8(pending, VecInfo),
995         VMSTATE_UINT8(active, VecInfo),
996         VMSTATE_UINT8(level, VecInfo),
997         VMSTATE_END_OF_LIST()
998     }
999 };
1000 
1001 static const VMStateDescription vmstate_nvic = {
1002     .name = "armv7m_nvic",
1003     .version_id = 3,
1004     .minimum_version_id = 3,
1005     .post_load = &nvic_post_load,
1006     .fields = (VMStateField[]) {
1007         VMSTATE_STRUCT_ARRAY(vectors, NVICState, NVIC_MAX_VECTORS, 1,
1008                              vmstate_VecInfo, VecInfo),
1009         VMSTATE_UINT32(systick.control, NVICState),
1010         VMSTATE_UINT32(systick.reload, NVICState),
1011         VMSTATE_INT64(systick.tick, NVICState),
1012         VMSTATE_TIMER_PTR(systick.timer, NVICState),
1013         VMSTATE_UINT32(prigroup, NVICState),
1014         VMSTATE_END_OF_LIST()
1015     }
1016 };
1017 
1018 static Property props_nvic[] = {
1019     /* Number of external IRQ lines (so excluding the 16 internal exceptions) */
1020     DEFINE_PROP_UINT32("num-irq", NVICState, num_irq, 64),
1021     DEFINE_PROP_END_OF_LIST()
1022 };
1023 
1024 static void armv7m_nvic_reset(DeviceState *dev)
1025 {
1026     NVICState *s = NVIC(dev);
1027 
1028     s->vectors[ARMV7M_EXCP_NMI].enabled = 1;
1029     s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
1030     /* MEM, BUS, and USAGE are enabled through
1031      * the System Handler Control register
1032      */
1033     s->vectors[ARMV7M_EXCP_SVC].enabled = 1;
1034     s->vectors[ARMV7M_EXCP_DEBUG].enabled = 1;
1035     s->vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
1036     s->vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
1037 
1038     s->vectors[ARMV7M_EXCP_RESET].prio = -3;
1039     s->vectors[ARMV7M_EXCP_NMI].prio = -2;
1040     s->vectors[ARMV7M_EXCP_HARD].prio = -1;
1041 
1042     /* Strictly speaking the reset handler should be enabled.
1043      * However, we don't simulate soft resets through the NVIC,
1044      * and the reset vector should never be pended.
1045      * So we leave it disabled to catch logic errors.
1046      */
1047 
1048     s->exception_prio = NVIC_NOEXC_PRIO;
1049     s->vectpending = 0;
1050 
1051     systick_reset(s);
1052 }
1053 
1054 static void armv7m_nvic_realize(DeviceState *dev, Error **errp)
1055 {
1056     NVICState *s = NVIC(dev);
1057 
1058     s->cpu = ARM_CPU(qemu_get_cpu(0));
1059     assert(s->cpu);
1060 
1061     if (s->num_irq > NVIC_MAX_IRQ) {
1062         error_setg(errp, "num-irq %d exceeds NVIC maximum", s->num_irq);
1063         return;
1064     }
1065 
1066     qdev_init_gpio_in(dev, set_irq_level, s->num_irq);
1067 
1068     /* include space for internal exception vectors */
1069     s->num_irq += NVIC_FIRST_IRQ;
1070 
1071     /* The NVIC and System Control Space (SCS) starts at 0xe000e000
1072      * and looks like this:
1073      *  0x004 - ICTR
1074      *  0x010 - 0x1c - systick
1075      *  0x100..0x7ec - NVIC
1076      *  0x7f0..0xcff - Reserved
1077      *  0xd00..0xd3c - SCS registers
1078      *  0xd40..0xeff - Reserved or Not implemented
1079      *  0xf00 - STIR
1080      *
1081      * At the moment there is only one thing in the container region,
1082      * but we leave it in place to allow us to pull systick out into
1083      * its own device object later.
1084      */
1085     memory_region_init(&s->container, OBJECT(s), "nvic", 0x1000);
1086     /* The system register region goes at the bottom of the priority
1087      * stack as it covers the whole page.
1088      */
1089     memory_region_init_io(&s->sysregmem, OBJECT(s), &nvic_sysreg_ops, s,
1090                           "nvic_sysregs", 0x1000);
1091     memory_region_add_subregion(&s->container, 0, &s->sysregmem);
1092 
1093     /* Map the whole thing into system memory at the location required
1094      * by the v7M architecture.
1095      */
1096     memory_region_add_subregion(get_system_memory(), 0xe000e000, &s->container);
1097     s->systick.timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, systick_timer_tick, s);
1098 }
1099 
1100 static void armv7m_nvic_instance_init(Object *obj)
1101 {
1102     /* We have a different default value for the num-irq property
1103      * than our superclass. This function runs after qdev init
1104      * has set the defaults from the Property array and before
1105      * any user-specified property setting, so just modify the
1106      * value in the GICState struct.
1107      */
1108     DeviceState *dev = DEVICE(obj);
1109     NVICState *nvic = NVIC(obj);
1110     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
1111 
1112     sysbus_init_irq(sbd, &nvic->excpout);
1113     qdev_init_gpio_out_named(dev, &nvic->sysresetreq, "SYSRESETREQ", 1);
1114 }
1115 
1116 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
1117 {
1118     DeviceClass *dc = DEVICE_CLASS(klass);
1119 
1120     dc->vmsd  = &vmstate_nvic;
1121     dc->props = props_nvic;
1122     dc->reset = armv7m_nvic_reset;
1123     dc->realize = armv7m_nvic_realize;
1124 }
1125 
1126 static const TypeInfo armv7m_nvic_info = {
1127     .name          = TYPE_NVIC,
1128     .parent        = TYPE_SYS_BUS_DEVICE,
1129     .instance_init = armv7m_nvic_instance_init,
1130     .instance_size = sizeof(NVICState),
1131     .class_init    = armv7m_nvic_class_init,
1132     .class_size    = sizeof(SysBusDeviceClass),
1133 };
1134 
1135 static void armv7m_nvic_register_types(void)
1136 {
1137     type_register_static(&armv7m_nvic_info);
1138 }
1139 
1140 type_init(armv7m_nvic_register_types)
1141