xref: /openbmc/qemu/hw/intc/armv7m_nvic.c (revision 2fb50a33401a2415b71ddc291e8a77bcd2f9e547)
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 "hw/intc/armv7m_nvic.h"
21 #include "target/arm/cpu.h"
22 #include "exec/exec-all.h"
23 #include "qemu/log.h"
24 #include "trace.h"
25 
26 /* IRQ number counting:
27  *
28  * the num-irq property counts the number of external IRQ lines
29  *
30  * NVICState::num_irq counts the total number of exceptions
31  * (external IRQs, the 15 internal exceptions including reset,
32  * and one for the unused exception number 0).
33  *
34  * NVIC_MAX_IRQ is the highest permitted number of external IRQ lines.
35  *
36  * NVIC_MAX_VECTORS is the highest permitted number of exceptions.
37  *
38  * Iterating through all exceptions should typically be done with
39  * for (i = 1; i < s->num_irq; i++) to avoid the unused slot 0.
40  *
41  * The external qemu_irq lines are the NVIC's external IRQ lines,
42  * so line 0 is exception 16.
43  *
44  * In the terminology of the architecture manual, "interrupts" are
45  * a subcategory of exception referring to the external interrupts
46  * (which are exception numbers NVIC_FIRST_IRQ and upward).
47  * For historical reasons QEMU tends to use "interrupt" and
48  * "exception" more or less interchangeably.
49  */
50 #define NVIC_FIRST_IRQ NVIC_INTERNAL_VECTORS
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 /* Maximum priority of non-secure exceptions when AIRCR.PRIS is set */
58 #define NVIC_NS_PRIO_LIMIT 0x80
59 
60 static const uint8_t nvic_id[] = {
61     0x00, 0xb0, 0x1b, 0x00, 0x0d, 0xe0, 0x05, 0xb1
62 };
63 
64 static int nvic_pending_prio(NVICState *s)
65 {
66     /* return the group priority of the current pending interrupt,
67      * or NVIC_NOEXC_PRIO if no interrupt is pending
68      */
69     return s->vectpending_prio;
70 }
71 
72 /* Return the value of the ISCR RETTOBASE bit:
73  * 1 if there is exactly one active exception
74  * 0 if there is more than one active exception
75  * UNKNOWN if there are no active exceptions (we choose 1,
76  * which matches the choice Cortex-M3 is documented as making).
77  *
78  * NB: some versions of the documentation talk about this
79  * counting "active exceptions other than the one shown by IPSR";
80  * this is only different in the obscure corner case where guest
81  * code has manually deactivated an exception and is about
82  * to fail an exception-return integrity check. The definition
83  * above is the one from the v8M ARM ARM and is also in line
84  * with the behaviour documented for the Cortex-M3.
85  */
86 static bool nvic_rettobase(NVICState *s)
87 {
88     int irq, nhand = 0;
89     bool check_sec = arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY);
90 
91     for (irq = ARMV7M_EXCP_RESET; irq < s->num_irq; irq++) {
92         if (s->vectors[irq].active ||
93             (check_sec && irq < NVIC_INTERNAL_VECTORS &&
94              s->sec_vectors[irq].active)) {
95             nhand++;
96             if (nhand == 2) {
97                 return 0;
98             }
99         }
100     }
101 
102     return 1;
103 }
104 
105 /* Return the value of the ISCR ISRPENDING bit:
106  * 1 if an external interrupt is pending
107  * 0 if no external interrupt is pending
108  */
109 static bool nvic_isrpending(NVICState *s)
110 {
111     int irq;
112 
113     /* We can shortcut if the highest priority pending interrupt
114      * happens to be external or if there is nothing pending.
115      */
116     if (s->vectpending > NVIC_FIRST_IRQ) {
117         return true;
118     }
119     if (s->vectpending == 0) {
120         return false;
121     }
122 
123     for (irq = NVIC_FIRST_IRQ; irq < s->num_irq; irq++) {
124         if (s->vectors[irq].pending) {
125             return true;
126         }
127     }
128     return false;
129 }
130 
131 static bool exc_is_banked(int exc)
132 {
133     /* Return true if this is one of the limited set of exceptions which
134      * are banked (and thus have state in sec_vectors[])
135      */
136     return exc == ARMV7M_EXCP_HARD ||
137         exc == ARMV7M_EXCP_MEM ||
138         exc == ARMV7M_EXCP_USAGE ||
139         exc == ARMV7M_EXCP_SVC ||
140         exc == ARMV7M_EXCP_PENDSV ||
141         exc == ARMV7M_EXCP_SYSTICK;
142 }
143 
144 /* Return a mask word which clears the subpriority bits from
145  * a priority value for an M-profile exception, leaving only
146  * the group priority.
147  */
148 static inline uint32_t nvic_gprio_mask(NVICState *s, bool secure)
149 {
150     return ~0U << (s->prigroup[secure] + 1);
151 }
152 
153 static bool exc_targets_secure(NVICState *s, int exc)
154 {
155     /* Return true if this non-banked exception targets Secure state. */
156     if (!arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
157         return false;
158     }
159 
160     if (exc >= NVIC_FIRST_IRQ) {
161         return !s->itns[exc];
162     }
163 
164     /* Function shouldn't be called for banked exceptions. */
165     assert(!exc_is_banked(exc));
166 
167     switch (exc) {
168     case ARMV7M_EXCP_NMI:
169     case ARMV7M_EXCP_BUS:
170         return !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
171     case ARMV7M_EXCP_SECURE:
172         return true;
173     case ARMV7M_EXCP_DEBUG:
174         /* TODO: controlled by DEMCR.SDME, which we don't yet implement */
175         return false;
176     default:
177         /* reset, and reserved (unused) low exception numbers.
178          * We'll get called by code that loops through all the exception
179          * numbers, but it doesn't matter what we return here as these
180          * non-existent exceptions will never be pended or active.
181          */
182         return true;
183     }
184 }
185 
186 static int exc_group_prio(NVICState *s, int rawprio, bool targets_secure)
187 {
188     /* Return the group priority for this exception, given its raw
189      * (group-and-subgroup) priority value and whether it is targeting
190      * secure state or not.
191      */
192     if (rawprio < 0) {
193         return rawprio;
194     }
195     rawprio &= nvic_gprio_mask(s, targets_secure);
196     /* AIRCR.PRIS causes us to squash all NS priorities into the
197      * lower half of the total range
198      */
199     if (!targets_secure &&
200         (s->cpu->env.v7m.aircr & R_V7M_AIRCR_PRIS_MASK)) {
201         rawprio = (rawprio >> 1) + NVIC_NS_PRIO_LIMIT;
202     }
203     return rawprio;
204 }
205 
206 /* Recompute vectpending and exception_prio for a CPU which implements
207  * the Security extension
208  */
209 static void nvic_recompute_state_secure(NVICState *s)
210 {
211     int i, bank;
212     int pend_prio = NVIC_NOEXC_PRIO;
213     int active_prio = NVIC_NOEXC_PRIO;
214     int pend_irq = 0;
215     bool pending_is_s_banked = false;
216 
217     /* R_CQRV: precedence is by:
218      *  - lowest group priority; if both the same then
219      *  - lowest subpriority; if both the same then
220      *  - lowest exception number; if both the same (ie banked) then
221      *  - secure exception takes precedence
222      * Compare pseudocode RawExecutionPriority.
223      * Annoyingly, now we have two prigroup values (for S and NS)
224      * we can't do the loop comparison on raw priority values.
225      */
226     for (i = 1; i < s->num_irq; i++) {
227         for (bank = M_REG_S; bank >= M_REG_NS; bank--) {
228             VecInfo *vec;
229             int prio;
230             bool targets_secure;
231 
232             if (bank == M_REG_S) {
233                 if (!exc_is_banked(i)) {
234                     continue;
235                 }
236                 vec = &s->sec_vectors[i];
237                 targets_secure = true;
238             } else {
239                 vec = &s->vectors[i];
240                 targets_secure = !exc_is_banked(i) && exc_targets_secure(s, i);
241             }
242 
243             prio = exc_group_prio(s, vec->prio, targets_secure);
244             if (vec->enabled && vec->pending && prio < pend_prio) {
245                 pend_prio = prio;
246                 pend_irq = i;
247                 pending_is_s_banked = (bank == M_REG_S);
248             }
249             if (vec->active && prio < active_prio) {
250                 active_prio = prio;
251             }
252         }
253     }
254 
255     s->vectpending_is_s_banked = pending_is_s_banked;
256     s->vectpending = pend_irq;
257     s->vectpending_prio = pend_prio;
258     s->exception_prio = active_prio;
259 
260     trace_nvic_recompute_state_secure(s->vectpending,
261                                       s->vectpending_is_s_banked,
262                                       s->vectpending_prio,
263                                       s->exception_prio);
264 }
265 
266 /* Recompute vectpending and exception_prio */
267 static void nvic_recompute_state(NVICState *s)
268 {
269     int i;
270     int pend_prio = NVIC_NOEXC_PRIO;
271     int active_prio = NVIC_NOEXC_PRIO;
272     int pend_irq = 0;
273 
274     /* In theory we could write one function that handled both
275      * the "security extension present" and "not present"; however
276      * the security related changes significantly complicate the
277      * recomputation just by themselves and mixing both cases together
278      * would be even worse, so we retain a separate non-secure-only
279      * version for CPUs which don't implement the security extension.
280      */
281     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
282         nvic_recompute_state_secure(s);
283         return;
284     }
285 
286     for (i = 1; i < s->num_irq; i++) {
287         VecInfo *vec = &s->vectors[i];
288 
289         if (vec->enabled && vec->pending && vec->prio < pend_prio) {
290             pend_prio = vec->prio;
291             pend_irq = i;
292         }
293         if (vec->active && vec->prio < active_prio) {
294             active_prio = vec->prio;
295         }
296     }
297 
298     if (active_prio > 0) {
299         active_prio &= nvic_gprio_mask(s, false);
300     }
301 
302     if (pend_prio > 0) {
303         pend_prio &= nvic_gprio_mask(s, false);
304     }
305 
306     s->vectpending = pend_irq;
307     s->vectpending_prio = pend_prio;
308     s->exception_prio = active_prio;
309 
310     trace_nvic_recompute_state(s->vectpending,
311                                s->vectpending_prio,
312                                s->exception_prio);
313 }
314 
315 /* Return the current execution priority of the CPU
316  * (equivalent to the pseudocode ExecutionPriority function).
317  * This is a value between -2 (NMI priority) and NVIC_NOEXC_PRIO.
318  */
319 static inline int nvic_exec_prio(NVICState *s)
320 {
321     CPUARMState *env = &s->cpu->env;
322     int running;
323 
324     if (env->v7m.faultmask[env->v7m.secure]) {
325         running = -1;
326     } else if (env->v7m.primask[env->v7m.secure]) {
327         running = 0;
328     } else if (env->v7m.basepri[env->v7m.secure] > 0) {
329         running = env->v7m.basepri[env->v7m.secure] &
330             nvic_gprio_mask(s, env->v7m.secure);
331     } else {
332         running = NVIC_NOEXC_PRIO; /* lower than any possible priority */
333     }
334     /* consider priority of active handler */
335     return MIN(running, s->exception_prio);
336 }
337 
338 bool armv7m_nvic_can_take_pending_exception(void *opaque)
339 {
340     NVICState *s = opaque;
341 
342     return nvic_exec_prio(s) > nvic_pending_prio(s);
343 }
344 
345 int armv7m_nvic_raw_execution_priority(void *opaque)
346 {
347     NVICState *s = opaque;
348 
349     return s->exception_prio;
350 }
351 
352 /* caller must call nvic_irq_update() after this */
353 static void set_prio(NVICState *s, unsigned irq, uint8_t prio)
354 {
355     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
356     assert(irq < s->num_irq);
357 
358     s->vectors[irq].prio = prio;
359 
360     trace_nvic_set_prio(irq, prio);
361 }
362 
363 /* Recompute state and assert irq line accordingly.
364  * Must be called after changes to:
365  *  vec->active, vec->enabled, vec->pending or vec->prio for any vector
366  *  prigroup
367  */
368 static void nvic_irq_update(NVICState *s)
369 {
370     int lvl;
371     int pend_prio;
372 
373     nvic_recompute_state(s);
374     pend_prio = nvic_pending_prio(s);
375 
376     /* Raise NVIC output if this IRQ would be taken, except that we
377      * ignore the effects of the BASEPRI, FAULTMASK and PRIMASK (which
378      * will be checked for in arm_v7m_cpu_exec_interrupt()); changes
379      * to those CPU registers don't cause us to recalculate the NVIC
380      * pending info.
381      */
382     lvl = (pend_prio < s->exception_prio);
383     trace_nvic_irq_update(s->vectpending, pend_prio, s->exception_prio, lvl);
384     qemu_set_irq(s->excpout, lvl);
385 }
386 
387 /**
388  * armv7m_nvic_clear_pending: mark the specified exception as not pending
389  * @opaque: the NVIC
390  * @irq: the exception number to mark as not pending
391  * @secure: false for non-banked exceptions or for the nonsecure
392  * version of a banked exception, true for the secure version of a banked
393  * exception.
394  *
395  * Marks the specified exception as not pending. Note that we will assert()
396  * if @secure is true and @irq does not specify one of the fixed set
397  * of architecturally banked exceptions.
398  */
399 static void armv7m_nvic_clear_pending(void *opaque, int irq, bool secure)
400 {
401     NVICState *s = (NVICState *)opaque;
402     VecInfo *vec;
403 
404     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
405 
406     if (secure) {
407         assert(exc_is_banked(irq));
408         vec = &s->sec_vectors[irq];
409     } else {
410         vec = &s->vectors[irq];
411     }
412     trace_nvic_clear_pending(irq, secure, vec->enabled, vec->prio);
413     if (vec->pending) {
414         vec->pending = 0;
415         nvic_irq_update(s);
416     }
417 }
418 
419 void armv7m_nvic_set_pending(void *opaque, int irq, bool secure)
420 {
421     NVICState *s = (NVICState *)opaque;
422     bool banked = exc_is_banked(irq);
423     VecInfo *vec;
424 
425     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
426     assert(!secure || banked);
427 
428     vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];
429 
430     trace_nvic_set_pending(irq, secure, vec->enabled, vec->prio);
431 
432     if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {
433         /* If a synchronous exception is pending then it may be
434          * escalated to HardFault if:
435          *  * it is equal or lower priority to current execution
436          *  * it is disabled
437          * (ie we need to take it immediately but we can't do so).
438          * Asynchronous exceptions (and interrupts) simply remain pending.
439          *
440          * For QEMU, we don't have any imprecise (asynchronous) faults,
441          * so we can assume that PREFETCH_ABORT and DATA_ABORT are always
442          * synchronous.
443          * Debug exceptions are awkward because only Debug exceptions
444          * resulting from the BKPT instruction should be escalated,
445          * but we don't currently implement any Debug exceptions other
446          * than those that result from BKPT, so we treat all debug exceptions
447          * as needing escalation.
448          *
449          * This all means we can identify whether to escalate based only on
450          * the exception number and don't (yet) need the caller to explicitly
451          * tell us whether this exception is synchronous or not.
452          */
453         int running = nvic_exec_prio(s);
454         bool escalate = false;
455 
456         if (vec->prio >= running) {
457             trace_nvic_escalate_prio(irq, vec->prio, running);
458             escalate = true;
459         } else if (!vec->enabled) {
460             trace_nvic_escalate_disabled(irq);
461             escalate = true;
462         }
463 
464         if (escalate) {
465             if (running < 0) {
466                 /* We want to escalate to HardFault but we can't take a
467                  * synchronous HardFault at this point either. This is a
468                  * Lockup condition due to a guest bug. We don't model
469                  * Lockup, so report via cpu_abort() instead.
470                  */
471                 cpu_abort(&s->cpu->parent_obj,
472                           "Lockup: can't escalate %d to HardFault "
473                           "(current priority %d)\n", irq, running);
474             }
475 
476             /* We can do the escalation, so we take HardFault instead.
477              * If BFHFNMINS is set then we escalate to the banked HF for
478              * the target security state of the original exception; otherwise
479              * we take a Secure HardFault.
480              */
481             irq = ARMV7M_EXCP_HARD;
482             if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY) &&
483                 (secure ||
484                  !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))) {
485                 vec = &s->sec_vectors[irq];
486             } else {
487                 vec = &s->vectors[irq];
488             }
489             /* HF may be banked but there is only one shared HFSR */
490             s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;
491         }
492     }
493 
494     if (!vec->pending) {
495         vec->pending = 1;
496         nvic_irq_update(s);
497     }
498 }
499 
500 /* Make pending IRQ active.  */
501 void armv7m_nvic_acknowledge_irq(void *opaque)
502 {
503     NVICState *s = (NVICState *)opaque;
504     CPUARMState *env = &s->cpu->env;
505     const int pending = s->vectpending;
506     const int running = nvic_exec_prio(s);
507     VecInfo *vec;
508 
509     assert(pending > ARMV7M_EXCP_RESET && pending < s->num_irq);
510 
511     vec = &s->vectors[pending];
512 
513     assert(vec->enabled);
514     assert(vec->pending);
515 
516     assert(s->vectpending_prio < running);
517 
518     trace_nvic_acknowledge_irq(pending, s->vectpending_prio);
519 
520     vec->active = 1;
521     vec->pending = 0;
522 
523     env->v7m.exception = s->vectpending;
524 
525     nvic_irq_update(s);
526 }
527 
528 int armv7m_nvic_complete_irq(void *opaque, int irq)
529 {
530     NVICState *s = (NVICState *)opaque;
531     VecInfo *vec;
532     int ret;
533 
534     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
535 
536     vec = &s->vectors[irq];
537 
538     trace_nvic_complete_irq(irq);
539 
540     if (!vec->active) {
541         /* Tell the caller this was an illegal exception return */
542         return -1;
543     }
544 
545     ret = nvic_rettobase(s);
546 
547     vec->active = 0;
548     if (vec->level) {
549         /* Re-pend the exception if it's still held high; only
550          * happens for extenal IRQs
551          */
552         assert(irq >= NVIC_FIRST_IRQ);
553         vec->pending = 1;
554     }
555 
556     nvic_irq_update(s);
557 
558     return ret;
559 }
560 
561 /* callback when external interrupt line is changed */
562 static void set_irq_level(void *opaque, int n, int level)
563 {
564     NVICState *s = opaque;
565     VecInfo *vec;
566 
567     n += NVIC_FIRST_IRQ;
568 
569     assert(n >= NVIC_FIRST_IRQ && n < s->num_irq);
570 
571     trace_nvic_set_irq_level(n, level);
572 
573     /* The pending status of an external interrupt is
574      * latched on rising edge and exception handler return.
575      *
576      * Pulsing the IRQ will always run the handler
577      * once, and the handler will re-run until the
578      * level is low when the handler completes.
579      */
580     vec = &s->vectors[n];
581     if (level != vec->level) {
582         vec->level = level;
583         if (level) {
584             armv7m_nvic_set_pending(s, n, false);
585         }
586     }
587 }
588 
589 static uint32_t nvic_readl(NVICState *s, uint32_t offset, MemTxAttrs attrs)
590 {
591     ARMCPU *cpu = s->cpu;
592     uint32_t val;
593 
594     switch (offset) {
595     case 4: /* Interrupt Control Type.  */
596         return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;
597     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
598     {
599         int startvec = 32 * (offset - 0x380) + NVIC_FIRST_IRQ;
600         int i;
601 
602         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
603             goto bad_offset;
604         }
605         if (!attrs.secure) {
606             return 0;
607         }
608         val = 0;
609         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
610             if (s->itns[startvec + i]) {
611                 val |= (1 << i);
612             }
613         }
614         return val;
615     }
616     case 0xd00: /* CPUID Base.  */
617         return cpu->midr;
618     case 0xd04: /* Interrupt Control State.  */
619         /* VECTACTIVE */
620         val = cpu->env.v7m.exception;
621         /* VECTPENDING */
622         val |= (s->vectpending & 0xff) << 12;
623         /* ISRPENDING - set if any external IRQ is pending */
624         if (nvic_isrpending(s)) {
625             val |= (1 << 22);
626         }
627         /* RETTOBASE - set if only one handler is active */
628         if (nvic_rettobase(s)) {
629             val |= (1 << 11);
630         }
631         /* PENDSTSET */
632         if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {
633             val |= (1 << 26);
634         }
635         /* PENDSVSET */
636         if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {
637             val |= (1 << 28);
638         }
639         /* NMIPENDSET */
640         if (s->vectors[ARMV7M_EXCP_NMI].pending) {
641             val |= (1 << 31);
642         }
643         /* ISRPREEMPT not implemented */
644         return val;
645     case 0xd08: /* Vector Table Offset.  */
646         return cpu->env.v7m.vecbase[attrs.secure];
647     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
648         val = 0xfa050000 | (s->prigroup[attrs.secure] << 8);
649         if (attrs.secure) {
650             /* s->aircr stores PRIS, BFHFNMINS, SYSRESETREQS */
651             val |= cpu->env.v7m.aircr;
652         } else {
653             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
654                 /* BFHFNMINS is R/O from NS; other bits are RAZ/WI. If
655                  * security isn't supported then BFHFNMINS is RAO (and
656                  * the bit in env.v7m.aircr is always set).
657                  */
658                 val |= cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK;
659             }
660         }
661         return val;
662     case 0xd10: /* System Control.  */
663         /* TODO: Implement SLEEPONEXIT.  */
664         return 0;
665     case 0xd14: /* Configuration Control.  */
666         /* The BFHFNMIGN bit is the only non-banked bit; we
667          * keep it in the non-secure copy of the register.
668          */
669         val = cpu->env.v7m.ccr[attrs.secure];
670         val |= cpu->env.v7m.ccr[M_REG_NS] & R_V7M_CCR_BFHFNMIGN_MASK;
671         return val;
672     case 0xd24: /* System Handler Status.  */
673         val = 0;
674         if (s->vectors[ARMV7M_EXCP_MEM].active) {
675             val |= (1 << 0);
676         }
677         if (s->vectors[ARMV7M_EXCP_BUS].active) {
678             val |= (1 << 1);
679         }
680         if (s->vectors[ARMV7M_EXCP_USAGE].active) {
681             val |= (1 << 3);
682         }
683         if (s->vectors[ARMV7M_EXCP_SVC].active) {
684             val |= (1 << 7);
685         }
686         if (s->vectors[ARMV7M_EXCP_DEBUG].active) {
687             val |= (1 << 8);
688         }
689         if (s->vectors[ARMV7M_EXCP_PENDSV].active) {
690             val |= (1 << 10);
691         }
692         if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {
693             val |= (1 << 11);
694         }
695         if (s->vectors[ARMV7M_EXCP_USAGE].pending) {
696             val |= (1 << 12);
697         }
698         if (s->vectors[ARMV7M_EXCP_MEM].pending) {
699             val |= (1 << 13);
700         }
701         if (s->vectors[ARMV7M_EXCP_BUS].pending) {
702             val |= (1 << 14);
703         }
704         if (s->vectors[ARMV7M_EXCP_SVC].pending) {
705             val |= (1 << 15);
706         }
707         if (s->vectors[ARMV7M_EXCP_MEM].enabled) {
708             val |= (1 << 16);
709         }
710         if (s->vectors[ARMV7M_EXCP_BUS].enabled) {
711             val |= (1 << 17);
712         }
713         if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {
714             val |= (1 << 18);
715         }
716         return val;
717     case 0xd28: /* Configurable Fault Status.  */
718         /* The BFSR bits [15:8] are shared between security states
719          * and we store them in the NS copy
720          */
721         val = cpu->env.v7m.cfsr[attrs.secure];
722         val |= cpu->env.v7m.cfsr[M_REG_NS] & R_V7M_CFSR_BFSR_MASK;
723         return val;
724     case 0xd2c: /* Hard Fault Status.  */
725         return cpu->env.v7m.hfsr;
726     case 0xd30: /* Debug Fault Status.  */
727         return cpu->env.v7m.dfsr;
728     case 0xd34: /* MMFAR MemManage Fault Address */
729         return cpu->env.v7m.mmfar[attrs.secure];
730     case 0xd38: /* Bus Fault Address.  */
731         return cpu->env.v7m.bfar;
732     case 0xd3c: /* Aux Fault Status.  */
733         /* TODO: Implement fault status registers.  */
734         qemu_log_mask(LOG_UNIMP,
735                       "Aux Fault status registers unimplemented\n");
736         return 0;
737     case 0xd40: /* PFR0.  */
738         return 0x00000030;
739     case 0xd44: /* PRF1.  */
740         return 0x00000200;
741     case 0xd48: /* DFR0.  */
742         return 0x00100000;
743     case 0xd4c: /* AFR0.  */
744         return 0x00000000;
745     case 0xd50: /* MMFR0.  */
746         return 0x00000030;
747     case 0xd54: /* MMFR1.  */
748         return 0x00000000;
749     case 0xd58: /* MMFR2.  */
750         return 0x00000000;
751     case 0xd5c: /* MMFR3.  */
752         return 0x00000000;
753     case 0xd60: /* ISAR0.  */
754         return 0x01141110;
755     case 0xd64: /* ISAR1.  */
756         return 0x02111000;
757     case 0xd68: /* ISAR2.  */
758         return 0x21112231;
759     case 0xd6c: /* ISAR3.  */
760         return 0x01111110;
761     case 0xd70: /* ISAR4.  */
762         return 0x01310102;
763     /* TODO: Implement debug registers.  */
764     case 0xd90: /* MPU_TYPE */
765         /* Unified MPU; if the MPU is not present this value is zero */
766         return cpu->pmsav7_dregion << 8;
767         break;
768     case 0xd94: /* MPU_CTRL */
769         return cpu->env.v7m.mpu_ctrl[attrs.secure];
770     case 0xd98: /* MPU_RNR */
771         return cpu->env.pmsav7.rnr[attrs.secure];
772     case 0xd9c: /* MPU_RBAR */
773     case 0xda4: /* MPU_RBAR_A1 */
774     case 0xdac: /* MPU_RBAR_A2 */
775     case 0xdb4: /* MPU_RBAR_A3 */
776     {
777         int region = cpu->env.pmsav7.rnr[attrs.secure];
778 
779         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
780             /* PMSAv8M handling of the aliases is different from v7M:
781              * aliases A1, A2, A3 override the low two bits of the region
782              * number in MPU_RNR, and there is no 'region' field in the
783              * RBAR register.
784              */
785             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
786             if (aliasno) {
787                 region = deposit32(region, 0, 2, aliasno);
788             }
789             if (region >= cpu->pmsav7_dregion) {
790                 return 0;
791             }
792             return cpu->env.pmsav8.rbar[attrs.secure][region];
793         }
794 
795         if (region >= cpu->pmsav7_dregion) {
796             return 0;
797         }
798         return (cpu->env.pmsav7.drbar[region] & 0x1f) | (region & 0xf);
799     }
800     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
801     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
802     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
803     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
804     {
805         int region = cpu->env.pmsav7.rnr[attrs.secure];
806 
807         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
808             /* PMSAv8M handling of the aliases is different from v7M:
809              * aliases A1, A2, A3 override the low two bits of the region
810              * number in MPU_RNR.
811              */
812             int aliasno = (offset - 0xda0) / 8; /* 0..3 */
813             if (aliasno) {
814                 region = deposit32(region, 0, 2, aliasno);
815             }
816             if (region >= cpu->pmsav7_dregion) {
817                 return 0;
818             }
819             return cpu->env.pmsav8.rlar[attrs.secure][region];
820         }
821 
822         if (region >= cpu->pmsav7_dregion) {
823             return 0;
824         }
825         return ((cpu->env.pmsav7.dracr[region] & 0xffff) << 16) |
826             (cpu->env.pmsav7.drsr[region] & 0xffff);
827     }
828     case 0xdc0: /* MPU_MAIR0 */
829         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
830             goto bad_offset;
831         }
832         return cpu->env.pmsav8.mair0[attrs.secure];
833     case 0xdc4: /* MPU_MAIR1 */
834         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
835             goto bad_offset;
836         }
837         return cpu->env.pmsav8.mair1[attrs.secure];
838     default:
839     bad_offset:
840         qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);
841         return 0;
842     }
843 }
844 
845 static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value,
846                         MemTxAttrs attrs)
847 {
848     ARMCPU *cpu = s->cpu;
849 
850     switch (offset) {
851     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
852     {
853         int startvec = 32 * (offset - 0x380) + NVIC_FIRST_IRQ;
854         int i;
855 
856         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
857             goto bad_offset;
858         }
859         if (!attrs.secure) {
860             break;
861         }
862         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
863             s->itns[startvec + i] = (value >> i) & 1;
864         }
865         nvic_irq_update(s);
866         break;
867     }
868     case 0xd04: /* Interrupt Control State.  */
869         if (value & (1 << 31)) {
870             armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI, false);
871         }
872         if (value & (1 << 28)) {
873             armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
874         } else if (value & (1 << 27)) {
875             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
876         }
877         if (value & (1 << 26)) {
878             armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
879         } else if (value & (1 << 25)) {
880             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
881         }
882         break;
883     case 0xd08: /* Vector Table Offset.  */
884         cpu->env.v7m.vecbase[attrs.secure] = value & 0xffffff80;
885         break;
886     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
887         if ((value >> R_V7M_AIRCR_VECTKEY_SHIFT) == 0x05fa) {
888             if (value & R_V7M_AIRCR_SYSRESETREQ_MASK) {
889                 if (attrs.secure ||
890                     !(cpu->env.v7m.aircr & R_V7M_AIRCR_SYSRESETREQS_MASK)) {
891                     qemu_irq_pulse(s->sysresetreq);
892                 }
893             }
894             if (value & R_V7M_AIRCR_VECTCLRACTIVE_MASK) {
895                 qemu_log_mask(LOG_GUEST_ERROR,
896                               "Setting VECTCLRACTIVE when not in DEBUG mode "
897                               "is UNPREDICTABLE\n");
898             }
899             if (value & R_V7M_AIRCR_VECTRESET_MASK) {
900                 /* NB: this bit is RES0 in v8M */
901                 qemu_log_mask(LOG_GUEST_ERROR,
902                               "Setting VECTRESET when not in DEBUG mode "
903                               "is UNPREDICTABLE\n");
904             }
905             s->prigroup[attrs.secure] = extract32(value,
906                                                   R_V7M_AIRCR_PRIGROUP_SHIFT,
907                                                   R_V7M_AIRCR_PRIGROUP_LENGTH);
908             if (attrs.secure) {
909                 /* These bits are only writable by secure */
910                 cpu->env.v7m.aircr = value &
911                     (R_V7M_AIRCR_SYSRESETREQS_MASK |
912                      R_V7M_AIRCR_BFHFNMINS_MASK |
913                      R_V7M_AIRCR_PRIS_MASK);
914             }
915             nvic_irq_update(s);
916         }
917         break;
918     case 0xd10: /* System Control.  */
919         /* TODO: Implement control registers.  */
920         qemu_log_mask(LOG_UNIMP, "NVIC: SCR unimplemented\n");
921         break;
922     case 0xd14: /* Configuration Control.  */
923         /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */
924         value &= (R_V7M_CCR_STKALIGN_MASK |
925                   R_V7M_CCR_BFHFNMIGN_MASK |
926                   R_V7M_CCR_DIV_0_TRP_MASK |
927                   R_V7M_CCR_UNALIGN_TRP_MASK |
928                   R_V7M_CCR_USERSETMPEND_MASK |
929                   R_V7M_CCR_NONBASETHRDENA_MASK);
930 
931         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
932             /* v8M makes NONBASETHRDENA and STKALIGN be RES1 */
933             value |= R_V7M_CCR_NONBASETHRDENA_MASK
934                 | R_V7M_CCR_STKALIGN_MASK;
935         }
936         if (attrs.secure) {
937             /* the BFHFNMIGN bit is not banked; keep that in the NS copy */
938             cpu->env.v7m.ccr[M_REG_NS] =
939                 (cpu->env.v7m.ccr[M_REG_NS] & ~R_V7M_CCR_BFHFNMIGN_MASK)
940                 | (value & R_V7M_CCR_BFHFNMIGN_MASK);
941             value &= ~R_V7M_CCR_BFHFNMIGN_MASK;
942         }
943 
944         cpu->env.v7m.ccr[attrs.secure] = value;
945         break;
946     case 0xd24: /* System Handler Control.  */
947         s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
948         s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;
949         s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
950         s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
951         s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;
952         s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;
953         s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;
954         s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;
955         s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
956         s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;
957         s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
958         s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
959         s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
960         s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;
961         nvic_irq_update(s);
962         break;
963     case 0xd28: /* Configurable Fault Status.  */
964         cpu->env.v7m.cfsr[attrs.secure] &= ~value; /* W1C */
965         if (attrs.secure) {
966             /* The BFSR bits [15:8] are shared between security states
967              * and we store them in the NS copy.
968              */
969             cpu->env.v7m.cfsr[M_REG_NS] &= ~(value & R_V7M_CFSR_BFSR_MASK);
970         }
971         break;
972     case 0xd2c: /* Hard Fault Status.  */
973         cpu->env.v7m.hfsr &= ~value; /* W1C */
974         break;
975     case 0xd30: /* Debug Fault Status.  */
976         cpu->env.v7m.dfsr &= ~value; /* W1C */
977         break;
978     case 0xd34: /* Mem Manage Address.  */
979         cpu->env.v7m.mmfar[attrs.secure] = value;
980         return;
981     case 0xd38: /* Bus Fault Address.  */
982         cpu->env.v7m.bfar = value;
983         return;
984     case 0xd3c: /* Aux Fault Status.  */
985         qemu_log_mask(LOG_UNIMP,
986                       "NVIC: Aux fault status registers unimplemented\n");
987         break;
988     case 0xd90: /* MPU_TYPE */
989         return; /* RO */
990     case 0xd94: /* MPU_CTRL */
991         if ((value &
992              (R_V7M_MPU_CTRL_HFNMIENA_MASK | R_V7M_MPU_CTRL_ENABLE_MASK))
993             == R_V7M_MPU_CTRL_HFNMIENA_MASK) {
994             qemu_log_mask(LOG_GUEST_ERROR, "MPU_CTRL: HFNMIENA and !ENABLE is "
995                           "UNPREDICTABLE\n");
996         }
997         cpu->env.v7m.mpu_ctrl[attrs.secure]
998             = value & (R_V7M_MPU_CTRL_ENABLE_MASK |
999                        R_V7M_MPU_CTRL_HFNMIENA_MASK |
1000                        R_V7M_MPU_CTRL_PRIVDEFENA_MASK);
1001         tlb_flush(CPU(cpu));
1002         break;
1003     case 0xd98: /* MPU_RNR */
1004         if (value >= cpu->pmsav7_dregion) {
1005             qemu_log_mask(LOG_GUEST_ERROR, "MPU region out of range %"
1006                           PRIu32 "/%" PRIu32 "\n",
1007                           value, cpu->pmsav7_dregion);
1008         } else {
1009             cpu->env.pmsav7.rnr[attrs.secure] = value;
1010         }
1011         break;
1012     case 0xd9c: /* MPU_RBAR */
1013     case 0xda4: /* MPU_RBAR_A1 */
1014     case 0xdac: /* MPU_RBAR_A2 */
1015     case 0xdb4: /* MPU_RBAR_A3 */
1016     {
1017         int region;
1018 
1019         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1020             /* PMSAv8M handling of the aliases is different from v7M:
1021              * aliases A1, A2, A3 override the low two bits of the region
1022              * number in MPU_RNR, and there is no 'region' field in the
1023              * RBAR register.
1024              */
1025             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1026 
1027             region = cpu->env.pmsav7.rnr[attrs.secure];
1028             if (aliasno) {
1029                 region = deposit32(region, 0, 2, aliasno);
1030             }
1031             if (region >= cpu->pmsav7_dregion) {
1032                 return;
1033             }
1034             cpu->env.pmsav8.rbar[attrs.secure][region] = value;
1035             tlb_flush(CPU(cpu));
1036             return;
1037         }
1038 
1039         if (value & (1 << 4)) {
1040             /* VALID bit means use the region number specified in this
1041              * value and also update MPU_RNR.REGION with that value.
1042              */
1043             region = extract32(value, 0, 4);
1044             if (region >= cpu->pmsav7_dregion) {
1045                 qemu_log_mask(LOG_GUEST_ERROR,
1046                               "MPU region out of range %u/%" PRIu32 "\n",
1047                               region, cpu->pmsav7_dregion);
1048                 return;
1049             }
1050             cpu->env.pmsav7.rnr[attrs.secure] = region;
1051         } else {
1052             region = cpu->env.pmsav7.rnr[attrs.secure];
1053         }
1054 
1055         if (region >= cpu->pmsav7_dregion) {
1056             return;
1057         }
1058 
1059         cpu->env.pmsav7.drbar[region] = value & ~0x1f;
1060         tlb_flush(CPU(cpu));
1061         break;
1062     }
1063     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
1064     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
1065     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
1066     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
1067     {
1068         int region = cpu->env.pmsav7.rnr[attrs.secure];
1069 
1070         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1071             /* PMSAv8M handling of the aliases is different from v7M:
1072              * aliases A1, A2, A3 override the low two bits of the region
1073              * number in MPU_RNR.
1074              */
1075             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1076 
1077             region = cpu->env.pmsav7.rnr[attrs.secure];
1078             if (aliasno) {
1079                 region = deposit32(region, 0, 2, aliasno);
1080             }
1081             if (region >= cpu->pmsav7_dregion) {
1082                 return;
1083             }
1084             cpu->env.pmsav8.rlar[attrs.secure][region] = value;
1085             tlb_flush(CPU(cpu));
1086             return;
1087         }
1088 
1089         if (region >= cpu->pmsav7_dregion) {
1090             return;
1091         }
1092 
1093         cpu->env.pmsav7.drsr[region] = value & 0xff3f;
1094         cpu->env.pmsav7.dracr[region] = (value >> 16) & 0x173f;
1095         tlb_flush(CPU(cpu));
1096         break;
1097     }
1098     case 0xdc0: /* MPU_MAIR0 */
1099         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1100             goto bad_offset;
1101         }
1102         if (cpu->pmsav7_dregion) {
1103             /* Register is RES0 if no MPU regions are implemented */
1104             cpu->env.pmsav8.mair0[attrs.secure] = value;
1105         }
1106         /* We don't need to do anything else because memory attributes
1107          * only affect cacheability, and we don't implement caching.
1108          */
1109         break;
1110     case 0xdc4: /* MPU_MAIR1 */
1111         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1112             goto bad_offset;
1113         }
1114         if (cpu->pmsav7_dregion) {
1115             /* Register is RES0 if no MPU regions are implemented */
1116             cpu->env.pmsav8.mair1[attrs.secure] = value;
1117         }
1118         /* We don't need to do anything else because memory attributes
1119          * only affect cacheability, and we don't implement caching.
1120          */
1121         break;
1122     case 0xf00: /* Software Triggered Interrupt Register */
1123     {
1124         int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;
1125         if (excnum < s->num_irq) {
1126             armv7m_nvic_set_pending(s, excnum, false);
1127         }
1128         break;
1129     }
1130     default:
1131     bad_offset:
1132         qemu_log_mask(LOG_GUEST_ERROR,
1133                       "NVIC: Bad write offset 0x%x\n", offset);
1134     }
1135 }
1136 
1137 static bool nvic_user_access_ok(NVICState *s, hwaddr offset, MemTxAttrs attrs)
1138 {
1139     /* Return true if unprivileged access to this register is permitted. */
1140     switch (offset) {
1141     case 0xf00: /* STIR: accessible only if CCR.USERSETMPEND permits */
1142         /* For access via STIR_NS it is the NS CCR.USERSETMPEND that
1143          * controls access even though the CPU is in Secure state (I_QDKX).
1144          */
1145         return s->cpu->env.v7m.ccr[attrs.secure] & R_V7M_CCR_USERSETMPEND_MASK;
1146     default:
1147         /* All other user accesses cause a BusFault unconditionally */
1148         return false;
1149     }
1150 }
1151 
1152 static MemTxResult nvic_sysreg_read(void *opaque, hwaddr addr,
1153                                     uint64_t *data, unsigned size,
1154                                     MemTxAttrs attrs)
1155 {
1156     NVICState *s = (NVICState *)opaque;
1157     uint32_t offset = addr;
1158     unsigned i, startvec, end;
1159     uint32_t val;
1160 
1161     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
1162         /* Generate BusFault for unprivileged accesses */
1163         return MEMTX_ERROR;
1164     }
1165 
1166     switch (offset) {
1167     /* reads of set and clear both return the status */
1168     case 0x100 ... 0x13f: /* NVIC Set enable */
1169         offset += 0x80;
1170         /* fall through */
1171     case 0x180 ... 0x1bf: /* NVIC Clear enable */
1172         val = 0;
1173         startvec = offset - 0x180 + NVIC_FIRST_IRQ; /* vector # */
1174 
1175         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1176             if (s->vectors[startvec + i].enabled &&
1177                 (attrs.secure || s->itns[startvec + i])) {
1178                 val |= (1 << i);
1179             }
1180         }
1181         break;
1182     case 0x200 ... 0x23f: /* NVIC Set pend */
1183         offset += 0x80;
1184         /* fall through */
1185     case 0x280 ... 0x2bf: /* NVIC Clear pend */
1186         val = 0;
1187         startvec = offset - 0x280 + NVIC_FIRST_IRQ; /* vector # */
1188         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1189             if (s->vectors[startvec + i].pending &&
1190                 (attrs.secure || s->itns[startvec + i])) {
1191                 val |= (1 << i);
1192             }
1193         }
1194         break;
1195     case 0x300 ... 0x33f: /* NVIC Active */
1196         val = 0;
1197         startvec = offset - 0x300 + NVIC_FIRST_IRQ; /* vector # */
1198 
1199         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1200             if (s->vectors[startvec + i].active &&
1201                 (attrs.secure || s->itns[startvec + i])) {
1202                 val |= (1 << i);
1203             }
1204         }
1205         break;
1206     case 0x400 ... 0x5ef: /* NVIC Priority */
1207         val = 0;
1208         startvec = offset - 0x400 + NVIC_FIRST_IRQ; /* vector # */
1209 
1210         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
1211             if (attrs.secure || s->itns[startvec + i]) {
1212                 val |= s->vectors[startvec + i].prio << (8 * i);
1213             }
1214         }
1215         break;
1216     case 0xd18 ... 0xd23: /* System Handler Priority.  */
1217         val = 0;
1218         for (i = 0; i < size; i++) {
1219             val |= s->vectors[(offset - 0xd14) + i].prio << (i * 8);
1220         }
1221         break;
1222     case 0xfe0 ... 0xfff: /* ID.  */
1223         if (offset & 3) {
1224             val = 0;
1225         } else {
1226             val = nvic_id[(offset - 0xfe0) >> 2];
1227         }
1228         break;
1229     default:
1230         if (size == 4) {
1231             val = nvic_readl(s, offset, attrs);
1232         } else {
1233             qemu_log_mask(LOG_GUEST_ERROR,
1234                           "NVIC: Bad read of size %d at offset 0x%x\n",
1235                           size, offset);
1236             val = 0;
1237         }
1238     }
1239 
1240     trace_nvic_sysreg_read(addr, val, size);
1241     *data = val;
1242     return MEMTX_OK;
1243 }
1244 
1245 static MemTxResult nvic_sysreg_write(void *opaque, hwaddr addr,
1246                                      uint64_t value, unsigned size,
1247                                      MemTxAttrs attrs)
1248 {
1249     NVICState *s = (NVICState *)opaque;
1250     uint32_t offset = addr;
1251     unsigned i, startvec, end;
1252     unsigned setval = 0;
1253 
1254     trace_nvic_sysreg_write(addr, value, size);
1255 
1256     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
1257         /* Generate BusFault for unprivileged accesses */
1258         return MEMTX_ERROR;
1259     }
1260 
1261     switch (offset) {
1262     case 0x100 ... 0x13f: /* NVIC Set enable */
1263         offset += 0x80;
1264         setval = 1;
1265         /* fall through */
1266     case 0x180 ... 0x1bf: /* NVIC Clear enable */
1267         startvec = 8 * (offset - 0x180) + NVIC_FIRST_IRQ;
1268 
1269         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1270             if (value & (1 << i) &&
1271                 (attrs.secure || s->itns[startvec + i])) {
1272                 s->vectors[startvec + i].enabled = setval;
1273             }
1274         }
1275         nvic_irq_update(s);
1276         return MEMTX_OK;
1277     case 0x200 ... 0x23f: /* NVIC Set pend */
1278         /* the special logic in armv7m_nvic_set_pending()
1279          * is not needed since IRQs are never escalated
1280          */
1281         offset += 0x80;
1282         setval = 1;
1283         /* fall through */
1284     case 0x280 ... 0x2bf: /* NVIC Clear pend */
1285         startvec = 8 * (offset - 0x280) + NVIC_FIRST_IRQ; /* vector # */
1286 
1287         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1288             if (value & (1 << i) &&
1289                 (attrs.secure || s->itns[startvec + i])) {
1290                 s->vectors[startvec + i].pending = setval;
1291             }
1292         }
1293         nvic_irq_update(s);
1294         return MEMTX_OK;
1295     case 0x300 ... 0x33f: /* NVIC Active */
1296         return MEMTX_OK; /* R/O */
1297     case 0x400 ... 0x5ef: /* NVIC Priority */
1298         startvec = 8 * (offset - 0x400) + NVIC_FIRST_IRQ; /* vector # */
1299 
1300         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
1301             if (attrs.secure || s->itns[startvec + i]) {
1302                 set_prio(s, startvec + i, (value >> (i * 8)) & 0xff);
1303             }
1304         }
1305         nvic_irq_update(s);
1306         return MEMTX_OK;
1307     case 0xd18 ... 0xd23: /* System Handler Priority.  */
1308         for (i = 0; i < size; i++) {
1309             unsigned hdlidx = (offset - 0xd14) + i;
1310             set_prio(s, hdlidx, (value >> (i * 8)) & 0xff);
1311         }
1312         nvic_irq_update(s);
1313         return MEMTX_OK;
1314     }
1315     if (size == 4) {
1316         nvic_writel(s, offset, value, attrs);
1317         return MEMTX_OK;
1318     }
1319     qemu_log_mask(LOG_GUEST_ERROR,
1320                   "NVIC: Bad write of size %d at offset 0x%x\n", size, offset);
1321     /* This is UNPREDICTABLE; treat as RAZ/WI */
1322     return MEMTX_OK;
1323 }
1324 
1325 static const MemoryRegionOps nvic_sysreg_ops = {
1326     .read_with_attrs = nvic_sysreg_read,
1327     .write_with_attrs = nvic_sysreg_write,
1328     .endianness = DEVICE_NATIVE_ENDIAN,
1329 };
1330 
1331 static MemTxResult nvic_sysreg_ns_write(void *opaque, hwaddr addr,
1332                                         uint64_t value, unsigned size,
1333                                         MemTxAttrs attrs)
1334 {
1335     if (attrs.secure) {
1336         /* S accesses to the alias act like NS accesses to the real region */
1337         attrs.secure = 0;
1338         return nvic_sysreg_write(opaque, addr, value, size, attrs);
1339     } else {
1340         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
1341         if (attrs.user) {
1342             return MEMTX_ERROR;
1343         }
1344         return MEMTX_OK;
1345     }
1346 }
1347 
1348 static MemTxResult nvic_sysreg_ns_read(void *opaque, hwaddr addr,
1349                                        uint64_t *data, unsigned size,
1350                                        MemTxAttrs attrs)
1351 {
1352     if (attrs.secure) {
1353         /* S accesses to the alias act like NS accesses to the real region */
1354         attrs.secure = 0;
1355         return nvic_sysreg_read(opaque, addr, data, size, attrs);
1356     } else {
1357         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
1358         if (attrs.user) {
1359             return MEMTX_ERROR;
1360         }
1361         *data = 0;
1362         return MEMTX_OK;
1363     }
1364 }
1365 
1366 static const MemoryRegionOps nvic_sysreg_ns_ops = {
1367     .read_with_attrs = nvic_sysreg_ns_read,
1368     .write_with_attrs = nvic_sysreg_ns_write,
1369     .endianness = DEVICE_NATIVE_ENDIAN,
1370 };
1371 
1372 static int nvic_post_load(void *opaque, int version_id)
1373 {
1374     NVICState *s = opaque;
1375     unsigned i;
1376 
1377     /* Check for out of range priority settings */
1378     if (s->vectors[ARMV7M_EXCP_RESET].prio != -3 ||
1379         s->vectors[ARMV7M_EXCP_NMI].prio != -2 ||
1380         s->vectors[ARMV7M_EXCP_HARD].prio != -1) {
1381         return 1;
1382     }
1383     for (i = ARMV7M_EXCP_MEM; i < s->num_irq; i++) {
1384         if (s->vectors[i].prio & ~0xff) {
1385             return 1;
1386         }
1387     }
1388 
1389     nvic_recompute_state(s);
1390 
1391     return 0;
1392 }
1393 
1394 static const VMStateDescription vmstate_VecInfo = {
1395     .name = "armv7m_nvic_info",
1396     .version_id = 1,
1397     .minimum_version_id = 1,
1398     .fields = (VMStateField[]) {
1399         VMSTATE_INT16(prio, VecInfo),
1400         VMSTATE_UINT8(enabled, VecInfo),
1401         VMSTATE_UINT8(pending, VecInfo),
1402         VMSTATE_UINT8(active, VecInfo),
1403         VMSTATE_UINT8(level, VecInfo),
1404         VMSTATE_END_OF_LIST()
1405     }
1406 };
1407 
1408 static bool nvic_security_needed(void *opaque)
1409 {
1410     NVICState *s = opaque;
1411 
1412     return arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY);
1413 }
1414 
1415 static int nvic_security_post_load(void *opaque, int version_id)
1416 {
1417     NVICState *s = opaque;
1418     int i;
1419 
1420     /* Check for out of range priority settings */
1421     if (s->sec_vectors[ARMV7M_EXCP_HARD].prio != -1) {
1422         return 1;
1423     }
1424     for (i = ARMV7M_EXCP_MEM; i < ARRAY_SIZE(s->sec_vectors); i++) {
1425         if (s->sec_vectors[i].prio & ~0xff) {
1426             return 1;
1427         }
1428     }
1429     return 0;
1430 }
1431 
1432 static const VMStateDescription vmstate_nvic_security = {
1433     .name = "nvic/m-security",
1434     .version_id = 1,
1435     .minimum_version_id = 1,
1436     .needed = nvic_security_needed,
1437     .post_load = &nvic_security_post_load,
1438     .fields = (VMStateField[]) {
1439         VMSTATE_STRUCT_ARRAY(sec_vectors, NVICState, NVIC_INTERNAL_VECTORS, 1,
1440                              vmstate_VecInfo, VecInfo),
1441         VMSTATE_UINT32(prigroup[M_REG_S], NVICState),
1442         VMSTATE_BOOL_ARRAY(itns, NVICState, NVIC_MAX_VECTORS),
1443         VMSTATE_END_OF_LIST()
1444     }
1445 };
1446 
1447 static const VMStateDescription vmstate_nvic = {
1448     .name = "armv7m_nvic",
1449     .version_id = 4,
1450     .minimum_version_id = 4,
1451     .post_load = &nvic_post_load,
1452     .fields = (VMStateField[]) {
1453         VMSTATE_STRUCT_ARRAY(vectors, NVICState, NVIC_MAX_VECTORS, 1,
1454                              vmstate_VecInfo, VecInfo),
1455         VMSTATE_UINT32(prigroup[M_REG_NS], NVICState),
1456         VMSTATE_END_OF_LIST()
1457     },
1458     .subsections = (const VMStateDescription*[]) {
1459         &vmstate_nvic_security,
1460         NULL
1461     }
1462 };
1463 
1464 static Property props_nvic[] = {
1465     /* Number of external IRQ lines (so excluding the 16 internal exceptions) */
1466     DEFINE_PROP_UINT32("num-irq", NVICState, num_irq, 64),
1467     DEFINE_PROP_END_OF_LIST()
1468 };
1469 
1470 static void armv7m_nvic_reset(DeviceState *dev)
1471 {
1472     NVICState *s = NVIC(dev);
1473 
1474     s->vectors[ARMV7M_EXCP_NMI].enabled = 1;
1475     s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
1476     /* MEM, BUS, and USAGE are enabled through
1477      * the System Handler Control register
1478      */
1479     s->vectors[ARMV7M_EXCP_SVC].enabled = 1;
1480     s->vectors[ARMV7M_EXCP_DEBUG].enabled = 1;
1481     s->vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
1482     s->vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
1483 
1484     s->vectors[ARMV7M_EXCP_RESET].prio = -3;
1485     s->vectors[ARMV7M_EXCP_NMI].prio = -2;
1486     s->vectors[ARMV7M_EXCP_HARD].prio = -1;
1487 
1488     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
1489         s->sec_vectors[ARMV7M_EXCP_HARD].enabled = 1;
1490         s->sec_vectors[ARMV7M_EXCP_SVC].enabled = 1;
1491         s->sec_vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
1492         s->sec_vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
1493 
1494         /* AIRCR.BFHFNMINS resets to 0 so Secure HF is priority -1 (R_CMTC) */
1495         s->sec_vectors[ARMV7M_EXCP_HARD].prio = -1;
1496     }
1497 
1498     /* Strictly speaking the reset handler should be enabled.
1499      * However, we don't simulate soft resets through the NVIC,
1500      * and the reset vector should never be pended.
1501      * So we leave it disabled to catch logic errors.
1502      */
1503 
1504     s->exception_prio = NVIC_NOEXC_PRIO;
1505     s->vectpending = 0;
1506     s->vectpending_is_s_banked = false;
1507     s->vectpending_prio = NVIC_NOEXC_PRIO;
1508 
1509     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
1510         memset(s->itns, 0, sizeof(s->itns));
1511     } else {
1512         /* This state is constant and not guest accessible in a non-security
1513          * NVIC; we set the bits to true to avoid having to do a feature
1514          * bit check in the NVIC enable/pend/etc register accessors.
1515          */
1516         int i;
1517 
1518         for (i = NVIC_FIRST_IRQ; i < ARRAY_SIZE(s->itns); i++) {
1519             s->itns[i] = true;
1520         }
1521     }
1522 }
1523 
1524 static void nvic_systick_trigger(void *opaque, int n, int level)
1525 {
1526     NVICState *s = opaque;
1527 
1528     if (level) {
1529         /* SysTick just asked us to pend its exception.
1530          * (This is different from an external interrupt line's
1531          * behaviour.)
1532          * TODO: when we implement the banked systicks we must make
1533          * this pend the correct banked exception.
1534          */
1535         armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, false);
1536     }
1537 }
1538 
1539 static void armv7m_nvic_realize(DeviceState *dev, Error **errp)
1540 {
1541     NVICState *s = NVIC(dev);
1542     SysBusDevice *systick_sbd;
1543     Error *err = NULL;
1544     int regionlen;
1545 
1546     s->cpu = ARM_CPU(qemu_get_cpu(0));
1547     assert(s->cpu);
1548 
1549     if (s->num_irq > NVIC_MAX_IRQ) {
1550         error_setg(errp, "num-irq %d exceeds NVIC maximum", s->num_irq);
1551         return;
1552     }
1553 
1554     qdev_init_gpio_in(dev, set_irq_level, s->num_irq);
1555 
1556     /* include space for internal exception vectors */
1557     s->num_irq += NVIC_FIRST_IRQ;
1558 
1559     object_property_set_bool(OBJECT(&s->systick), true, "realized", &err);
1560     if (err != NULL) {
1561         error_propagate(errp, err);
1562         return;
1563     }
1564     systick_sbd = SYS_BUS_DEVICE(&s->systick);
1565     sysbus_connect_irq(systick_sbd, 0,
1566                        qdev_get_gpio_in_named(dev, "systick-trigger", 0));
1567 
1568     /* The NVIC and System Control Space (SCS) starts at 0xe000e000
1569      * and looks like this:
1570      *  0x004 - ICTR
1571      *  0x010 - 0xff - systick
1572      *  0x100..0x7ec - NVIC
1573      *  0x7f0..0xcff - Reserved
1574      *  0xd00..0xd3c - SCS registers
1575      *  0xd40..0xeff - Reserved or Not implemented
1576      *  0xf00 - STIR
1577      *
1578      * Some registers within this space are banked between security states.
1579      * In v8M there is a second range 0xe002e000..0xe002efff which is the
1580      * NonSecure alias SCS; secure accesses to this behave like NS accesses
1581      * to the main SCS range, and non-secure accesses (including when
1582      * the security extension is not implemented) are RAZ/WI.
1583      * Note that both the main SCS range and the alias range are defined
1584      * to be exempt from memory attribution (R_BLJT) and so the memory
1585      * transaction attribute always matches the current CPU security
1586      * state (attrs.secure == env->v7m.secure). In the nvic_sysreg_ns_ops
1587      * wrappers we change attrs.secure to indicate the NS access; so
1588      * generally code determining which banked register to use should
1589      * use attrs.secure; code determining actual behaviour of the system
1590      * should use env->v7m.secure.
1591      */
1592     regionlen = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? 0x21000 : 0x1000;
1593     memory_region_init(&s->container, OBJECT(s), "nvic", regionlen);
1594     /* The system register region goes at the bottom of the priority
1595      * stack as it covers the whole page.
1596      */
1597     memory_region_init_io(&s->sysregmem, OBJECT(s), &nvic_sysreg_ops, s,
1598                           "nvic_sysregs", 0x1000);
1599     memory_region_add_subregion(&s->container, 0, &s->sysregmem);
1600     memory_region_add_subregion_overlap(&s->container, 0x10,
1601                                         sysbus_mmio_get_region(systick_sbd, 0),
1602                                         1);
1603 
1604     if (arm_feature(&s->cpu->env, ARM_FEATURE_V8)) {
1605         memory_region_init_io(&s->sysreg_ns_mem, OBJECT(s),
1606                               &nvic_sysreg_ns_ops, s,
1607                               "nvic_sysregs_ns", 0x1000);
1608         memory_region_add_subregion(&s->container, 0x20000, &s->sysreg_ns_mem);
1609     }
1610 
1611     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->container);
1612 }
1613 
1614 static void armv7m_nvic_instance_init(Object *obj)
1615 {
1616     /* We have a different default value for the num-irq property
1617      * than our superclass. This function runs after qdev init
1618      * has set the defaults from the Property array and before
1619      * any user-specified property setting, so just modify the
1620      * value in the GICState struct.
1621      */
1622     DeviceState *dev = DEVICE(obj);
1623     NVICState *nvic = NVIC(obj);
1624     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
1625 
1626     object_initialize(&nvic->systick, sizeof(nvic->systick), TYPE_SYSTICK);
1627     qdev_set_parent_bus(DEVICE(&nvic->systick), sysbus_get_default());
1628 
1629     sysbus_init_irq(sbd, &nvic->excpout);
1630     qdev_init_gpio_out_named(dev, &nvic->sysresetreq, "SYSRESETREQ", 1);
1631     qdev_init_gpio_in_named(dev, nvic_systick_trigger, "systick-trigger", 1);
1632 }
1633 
1634 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
1635 {
1636     DeviceClass *dc = DEVICE_CLASS(klass);
1637 
1638     dc->vmsd  = &vmstate_nvic;
1639     dc->props = props_nvic;
1640     dc->reset = armv7m_nvic_reset;
1641     dc->realize = armv7m_nvic_realize;
1642 }
1643 
1644 static const TypeInfo armv7m_nvic_info = {
1645     .name          = TYPE_NVIC,
1646     .parent        = TYPE_SYS_BUS_DEVICE,
1647     .instance_init = armv7m_nvic_instance_init,
1648     .instance_size = sizeof(NVICState),
1649     .class_init    = armv7m_nvic_class_init,
1650     .class_size    = sizeof(SysBusDeviceClass),
1651 };
1652 
1653 static void armv7m_nvic_register_types(void)
1654 {
1655     type_register_static(&armv7m_nvic_info);
1656 }
1657 
1658 type_init(armv7m_nvic_register_types)
1659