xref: /openbmc/qemu/hw/intc/armv7m_nvic.c (revision e6a0d3500d3a0032680a3eca038c60c5cbab60f8)
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  * secure indicates the bank to use for banked exceptions (we assert if
354  * we are passed secure=true for a non-banked exception).
355  */
356 static void set_prio(NVICState *s, unsigned irq, bool secure, uint8_t prio)
357 {
358     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
359     assert(irq < s->num_irq);
360 
361     if (secure) {
362         assert(exc_is_banked(irq));
363         s->sec_vectors[irq].prio = prio;
364     } else {
365         s->vectors[irq].prio = prio;
366     }
367 
368     trace_nvic_set_prio(irq, secure, prio);
369 }
370 
371 /* Return the current raw priority register value.
372  * secure indicates the bank to use for banked exceptions (we assert if
373  * we are passed secure=true for a non-banked exception).
374  */
375 static int get_prio(NVICState *s, unsigned irq, bool secure)
376 {
377     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
378     assert(irq < s->num_irq);
379 
380     if (secure) {
381         assert(exc_is_banked(irq));
382         return s->sec_vectors[irq].prio;
383     } else {
384         return s->vectors[irq].prio;
385     }
386 }
387 
388 /* Recompute state and assert irq line accordingly.
389  * Must be called after changes to:
390  *  vec->active, vec->enabled, vec->pending or vec->prio for any vector
391  *  prigroup
392  */
393 static void nvic_irq_update(NVICState *s)
394 {
395     int lvl;
396     int pend_prio;
397 
398     nvic_recompute_state(s);
399     pend_prio = nvic_pending_prio(s);
400 
401     /* Raise NVIC output if this IRQ would be taken, except that we
402      * ignore the effects of the BASEPRI, FAULTMASK and PRIMASK (which
403      * will be checked for in arm_v7m_cpu_exec_interrupt()); changes
404      * to those CPU registers don't cause us to recalculate the NVIC
405      * pending info.
406      */
407     lvl = (pend_prio < s->exception_prio);
408     trace_nvic_irq_update(s->vectpending, pend_prio, s->exception_prio, lvl);
409     qemu_set_irq(s->excpout, lvl);
410 }
411 
412 /**
413  * armv7m_nvic_clear_pending: mark the specified exception as not pending
414  * @opaque: the NVIC
415  * @irq: the exception number to mark as not pending
416  * @secure: false for non-banked exceptions or for the nonsecure
417  * version of a banked exception, true for the secure version of a banked
418  * exception.
419  *
420  * Marks the specified exception as not pending. Note that we will assert()
421  * if @secure is true and @irq does not specify one of the fixed set
422  * of architecturally banked exceptions.
423  */
424 static void armv7m_nvic_clear_pending(void *opaque, int irq, bool secure)
425 {
426     NVICState *s = (NVICState *)opaque;
427     VecInfo *vec;
428 
429     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
430 
431     if (secure) {
432         assert(exc_is_banked(irq));
433         vec = &s->sec_vectors[irq];
434     } else {
435         vec = &s->vectors[irq];
436     }
437     trace_nvic_clear_pending(irq, secure, vec->enabled, vec->prio);
438     if (vec->pending) {
439         vec->pending = 0;
440         nvic_irq_update(s);
441     }
442 }
443 
444 void armv7m_nvic_set_pending(void *opaque, int irq, bool secure)
445 {
446     NVICState *s = (NVICState *)opaque;
447     bool banked = exc_is_banked(irq);
448     VecInfo *vec;
449 
450     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
451     assert(!secure || banked);
452 
453     vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];
454 
455     trace_nvic_set_pending(irq, secure, vec->enabled, vec->prio);
456 
457     if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {
458         /* If a synchronous exception is pending then it may be
459          * escalated to HardFault if:
460          *  * it is equal or lower priority to current execution
461          *  * it is disabled
462          * (ie we need to take it immediately but we can't do so).
463          * Asynchronous exceptions (and interrupts) simply remain pending.
464          *
465          * For QEMU, we don't have any imprecise (asynchronous) faults,
466          * so we can assume that PREFETCH_ABORT and DATA_ABORT are always
467          * synchronous.
468          * Debug exceptions are awkward because only Debug exceptions
469          * resulting from the BKPT instruction should be escalated,
470          * but we don't currently implement any Debug exceptions other
471          * than those that result from BKPT, so we treat all debug exceptions
472          * as needing escalation.
473          *
474          * This all means we can identify whether to escalate based only on
475          * the exception number and don't (yet) need the caller to explicitly
476          * tell us whether this exception is synchronous or not.
477          */
478         int running = nvic_exec_prio(s);
479         bool escalate = false;
480 
481         if (vec->prio >= running) {
482             trace_nvic_escalate_prio(irq, vec->prio, running);
483             escalate = true;
484         } else if (!vec->enabled) {
485             trace_nvic_escalate_disabled(irq);
486             escalate = true;
487         }
488 
489         if (escalate) {
490             if (running < 0) {
491                 /* We want to escalate to HardFault but we can't take a
492                  * synchronous HardFault at this point either. This is a
493                  * Lockup condition due to a guest bug. We don't model
494                  * Lockup, so report via cpu_abort() instead.
495                  */
496                 cpu_abort(&s->cpu->parent_obj,
497                           "Lockup: can't escalate %d to HardFault "
498                           "(current priority %d)\n", irq, running);
499             }
500 
501             /* We can do the escalation, so we take HardFault instead.
502              * If BFHFNMINS is set then we escalate to the banked HF for
503              * the target security state of the original exception; otherwise
504              * we take a Secure HardFault.
505              */
506             irq = ARMV7M_EXCP_HARD;
507             if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY) &&
508                 (secure ||
509                  !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))) {
510                 vec = &s->sec_vectors[irq];
511             } else {
512                 vec = &s->vectors[irq];
513             }
514             /* HF may be banked but there is only one shared HFSR */
515             s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;
516         }
517     }
518 
519     if (!vec->pending) {
520         vec->pending = 1;
521         nvic_irq_update(s);
522     }
523 }
524 
525 /* Make pending IRQ active.  */
526 void armv7m_nvic_acknowledge_irq(void *opaque)
527 {
528     NVICState *s = (NVICState *)opaque;
529     CPUARMState *env = &s->cpu->env;
530     const int pending = s->vectpending;
531     const int running = nvic_exec_prio(s);
532     VecInfo *vec;
533 
534     assert(pending > ARMV7M_EXCP_RESET && pending < s->num_irq);
535 
536     vec = &s->vectors[pending];
537 
538     assert(vec->enabled);
539     assert(vec->pending);
540 
541     assert(s->vectpending_prio < running);
542 
543     trace_nvic_acknowledge_irq(pending, s->vectpending_prio);
544 
545     vec->active = 1;
546     vec->pending = 0;
547 
548     env->v7m.exception = s->vectpending;
549 
550     nvic_irq_update(s);
551 }
552 
553 int armv7m_nvic_complete_irq(void *opaque, int irq)
554 {
555     NVICState *s = (NVICState *)opaque;
556     VecInfo *vec;
557     int ret;
558 
559     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
560 
561     vec = &s->vectors[irq];
562 
563     trace_nvic_complete_irq(irq);
564 
565     if (!vec->active) {
566         /* Tell the caller this was an illegal exception return */
567         return -1;
568     }
569 
570     ret = nvic_rettobase(s);
571 
572     vec->active = 0;
573     if (vec->level) {
574         /* Re-pend the exception if it's still held high; only
575          * happens for extenal IRQs
576          */
577         assert(irq >= NVIC_FIRST_IRQ);
578         vec->pending = 1;
579     }
580 
581     nvic_irq_update(s);
582 
583     return ret;
584 }
585 
586 /* callback when external interrupt line is changed */
587 static void set_irq_level(void *opaque, int n, int level)
588 {
589     NVICState *s = opaque;
590     VecInfo *vec;
591 
592     n += NVIC_FIRST_IRQ;
593 
594     assert(n >= NVIC_FIRST_IRQ && n < s->num_irq);
595 
596     trace_nvic_set_irq_level(n, level);
597 
598     /* The pending status of an external interrupt is
599      * latched on rising edge and exception handler return.
600      *
601      * Pulsing the IRQ will always run the handler
602      * once, and the handler will re-run until the
603      * level is low when the handler completes.
604      */
605     vec = &s->vectors[n];
606     if (level != vec->level) {
607         vec->level = level;
608         if (level) {
609             armv7m_nvic_set_pending(s, n, false);
610         }
611     }
612 }
613 
614 static uint32_t nvic_readl(NVICState *s, uint32_t offset, MemTxAttrs attrs)
615 {
616     ARMCPU *cpu = s->cpu;
617     uint32_t val;
618 
619     switch (offset) {
620     case 4: /* Interrupt Control Type.  */
621         return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;
622     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
623     {
624         int startvec = 32 * (offset - 0x380) + NVIC_FIRST_IRQ;
625         int i;
626 
627         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
628             goto bad_offset;
629         }
630         if (!attrs.secure) {
631             return 0;
632         }
633         val = 0;
634         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
635             if (s->itns[startvec + i]) {
636                 val |= (1 << i);
637             }
638         }
639         return val;
640     }
641     case 0xd00: /* CPUID Base.  */
642         return cpu->midr;
643     case 0xd04: /* Interrupt Control State.  */
644         /* VECTACTIVE */
645         val = cpu->env.v7m.exception;
646         /* VECTPENDING */
647         val |= (s->vectpending & 0xff) << 12;
648         /* ISRPENDING - set if any external IRQ is pending */
649         if (nvic_isrpending(s)) {
650             val |= (1 << 22);
651         }
652         /* RETTOBASE - set if only one handler is active */
653         if (nvic_rettobase(s)) {
654             val |= (1 << 11);
655         }
656         /* PENDSTSET */
657         if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {
658             val |= (1 << 26);
659         }
660         /* PENDSVSET */
661         if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {
662             val |= (1 << 28);
663         }
664         /* NMIPENDSET */
665         if (s->vectors[ARMV7M_EXCP_NMI].pending) {
666             val |= (1 << 31);
667         }
668         /* ISRPREEMPT not implemented */
669         return val;
670     case 0xd08: /* Vector Table Offset.  */
671         return cpu->env.v7m.vecbase[attrs.secure];
672     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
673         val = 0xfa050000 | (s->prigroup[attrs.secure] << 8);
674         if (attrs.secure) {
675             /* s->aircr stores PRIS, BFHFNMINS, SYSRESETREQS */
676             val |= cpu->env.v7m.aircr;
677         } else {
678             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
679                 /* BFHFNMINS is R/O from NS; other bits are RAZ/WI. If
680                  * security isn't supported then BFHFNMINS is RAO (and
681                  * the bit in env.v7m.aircr is always set).
682                  */
683                 val |= cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK;
684             }
685         }
686         return val;
687     case 0xd10: /* System Control.  */
688         /* TODO: Implement SLEEPONEXIT.  */
689         return 0;
690     case 0xd14: /* Configuration Control.  */
691         /* The BFHFNMIGN bit is the only non-banked bit; we
692          * keep it in the non-secure copy of the register.
693          */
694         val = cpu->env.v7m.ccr[attrs.secure];
695         val |= cpu->env.v7m.ccr[M_REG_NS] & R_V7M_CCR_BFHFNMIGN_MASK;
696         return val;
697     case 0xd24: /* System Handler Status.  */
698         val = 0;
699         if (s->vectors[ARMV7M_EXCP_MEM].active) {
700             val |= (1 << 0);
701         }
702         if (s->vectors[ARMV7M_EXCP_BUS].active) {
703             val |= (1 << 1);
704         }
705         if (s->vectors[ARMV7M_EXCP_USAGE].active) {
706             val |= (1 << 3);
707         }
708         if (s->vectors[ARMV7M_EXCP_SVC].active) {
709             val |= (1 << 7);
710         }
711         if (s->vectors[ARMV7M_EXCP_DEBUG].active) {
712             val |= (1 << 8);
713         }
714         if (s->vectors[ARMV7M_EXCP_PENDSV].active) {
715             val |= (1 << 10);
716         }
717         if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {
718             val |= (1 << 11);
719         }
720         if (s->vectors[ARMV7M_EXCP_USAGE].pending) {
721             val |= (1 << 12);
722         }
723         if (s->vectors[ARMV7M_EXCP_MEM].pending) {
724             val |= (1 << 13);
725         }
726         if (s->vectors[ARMV7M_EXCP_BUS].pending) {
727             val |= (1 << 14);
728         }
729         if (s->vectors[ARMV7M_EXCP_SVC].pending) {
730             val |= (1 << 15);
731         }
732         if (s->vectors[ARMV7M_EXCP_MEM].enabled) {
733             val |= (1 << 16);
734         }
735         if (s->vectors[ARMV7M_EXCP_BUS].enabled) {
736             val |= (1 << 17);
737         }
738         if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {
739             val |= (1 << 18);
740         }
741         return val;
742     case 0xd28: /* Configurable Fault Status.  */
743         /* The BFSR bits [15:8] are shared between security states
744          * and we store them in the NS copy
745          */
746         val = cpu->env.v7m.cfsr[attrs.secure];
747         val |= cpu->env.v7m.cfsr[M_REG_NS] & R_V7M_CFSR_BFSR_MASK;
748         return val;
749     case 0xd2c: /* Hard Fault Status.  */
750         return cpu->env.v7m.hfsr;
751     case 0xd30: /* Debug Fault Status.  */
752         return cpu->env.v7m.dfsr;
753     case 0xd34: /* MMFAR MemManage Fault Address */
754         return cpu->env.v7m.mmfar[attrs.secure];
755     case 0xd38: /* Bus Fault Address.  */
756         return cpu->env.v7m.bfar;
757     case 0xd3c: /* Aux Fault Status.  */
758         /* TODO: Implement fault status registers.  */
759         qemu_log_mask(LOG_UNIMP,
760                       "Aux Fault status registers unimplemented\n");
761         return 0;
762     case 0xd40: /* PFR0.  */
763         return 0x00000030;
764     case 0xd44: /* PRF1.  */
765         return 0x00000200;
766     case 0xd48: /* DFR0.  */
767         return 0x00100000;
768     case 0xd4c: /* AFR0.  */
769         return 0x00000000;
770     case 0xd50: /* MMFR0.  */
771         return 0x00000030;
772     case 0xd54: /* MMFR1.  */
773         return 0x00000000;
774     case 0xd58: /* MMFR2.  */
775         return 0x00000000;
776     case 0xd5c: /* MMFR3.  */
777         return 0x00000000;
778     case 0xd60: /* ISAR0.  */
779         return 0x01141110;
780     case 0xd64: /* ISAR1.  */
781         return 0x02111000;
782     case 0xd68: /* ISAR2.  */
783         return 0x21112231;
784     case 0xd6c: /* ISAR3.  */
785         return 0x01111110;
786     case 0xd70: /* ISAR4.  */
787         return 0x01310102;
788     /* TODO: Implement debug registers.  */
789     case 0xd90: /* MPU_TYPE */
790         /* Unified MPU; if the MPU is not present this value is zero */
791         return cpu->pmsav7_dregion << 8;
792         break;
793     case 0xd94: /* MPU_CTRL */
794         return cpu->env.v7m.mpu_ctrl[attrs.secure];
795     case 0xd98: /* MPU_RNR */
796         return cpu->env.pmsav7.rnr[attrs.secure];
797     case 0xd9c: /* MPU_RBAR */
798     case 0xda4: /* MPU_RBAR_A1 */
799     case 0xdac: /* MPU_RBAR_A2 */
800     case 0xdb4: /* MPU_RBAR_A3 */
801     {
802         int region = cpu->env.pmsav7.rnr[attrs.secure];
803 
804         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
805             /* PMSAv8M handling of the aliases is different from v7M:
806              * aliases A1, A2, A3 override the low two bits of the region
807              * number in MPU_RNR, and there is no 'region' field in the
808              * RBAR register.
809              */
810             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
811             if (aliasno) {
812                 region = deposit32(region, 0, 2, aliasno);
813             }
814             if (region >= cpu->pmsav7_dregion) {
815                 return 0;
816             }
817             return cpu->env.pmsav8.rbar[attrs.secure][region];
818         }
819 
820         if (region >= cpu->pmsav7_dregion) {
821             return 0;
822         }
823         return (cpu->env.pmsav7.drbar[region] & 0x1f) | (region & 0xf);
824     }
825     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
826     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
827     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
828     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
829     {
830         int region = cpu->env.pmsav7.rnr[attrs.secure];
831 
832         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
833             /* PMSAv8M handling of the aliases is different from v7M:
834              * aliases A1, A2, A3 override the low two bits of the region
835              * number in MPU_RNR.
836              */
837             int aliasno = (offset - 0xda0) / 8; /* 0..3 */
838             if (aliasno) {
839                 region = deposit32(region, 0, 2, aliasno);
840             }
841             if (region >= cpu->pmsav7_dregion) {
842                 return 0;
843             }
844             return cpu->env.pmsav8.rlar[attrs.secure][region];
845         }
846 
847         if (region >= cpu->pmsav7_dregion) {
848             return 0;
849         }
850         return ((cpu->env.pmsav7.dracr[region] & 0xffff) << 16) |
851             (cpu->env.pmsav7.drsr[region] & 0xffff);
852     }
853     case 0xdc0: /* MPU_MAIR0 */
854         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
855             goto bad_offset;
856         }
857         return cpu->env.pmsav8.mair0[attrs.secure];
858     case 0xdc4: /* MPU_MAIR1 */
859         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
860             goto bad_offset;
861         }
862         return cpu->env.pmsav8.mair1[attrs.secure];
863     default:
864     bad_offset:
865         qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);
866         return 0;
867     }
868 }
869 
870 static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value,
871                         MemTxAttrs attrs)
872 {
873     ARMCPU *cpu = s->cpu;
874 
875     switch (offset) {
876     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
877     {
878         int startvec = 32 * (offset - 0x380) + NVIC_FIRST_IRQ;
879         int i;
880 
881         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
882             goto bad_offset;
883         }
884         if (!attrs.secure) {
885             break;
886         }
887         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
888             s->itns[startvec + i] = (value >> i) & 1;
889         }
890         nvic_irq_update(s);
891         break;
892     }
893     case 0xd04: /* Interrupt Control State.  */
894         if (value & (1 << 31)) {
895             armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI, false);
896         }
897         if (value & (1 << 28)) {
898             armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
899         } else if (value & (1 << 27)) {
900             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
901         }
902         if (value & (1 << 26)) {
903             armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
904         } else if (value & (1 << 25)) {
905             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
906         }
907         break;
908     case 0xd08: /* Vector Table Offset.  */
909         cpu->env.v7m.vecbase[attrs.secure] = value & 0xffffff80;
910         break;
911     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
912         if ((value >> R_V7M_AIRCR_VECTKEY_SHIFT) == 0x05fa) {
913             if (value & R_V7M_AIRCR_SYSRESETREQ_MASK) {
914                 if (attrs.secure ||
915                     !(cpu->env.v7m.aircr & R_V7M_AIRCR_SYSRESETREQS_MASK)) {
916                     qemu_irq_pulse(s->sysresetreq);
917                 }
918             }
919             if (value & R_V7M_AIRCR_VECTCLRACTIVE_MASK) {
920                 qemu_log_mask(LOG_GUEST_ERROR,
921                               "Setting VECTCLRACTIVE when not in DEBUG mode "
922                               "is UNPREDICTABLE\n");
923             }
924             if (value & R_V7M_AIRCR_VECTRESET_MASK) {
925                 /* NB: this bit is RES0 in v8M */
926                 qemu_log_mask(LOG_GUEST_ERROR,
927                               "Setting VECTRESET when not in DEBUG mode "
928                               "is UNPREDICTABLE\n");
929             }
930             s->prigroup[attrs.secure] = extract32(value,
931                                                   R_V7M_AIRCR_PRIGROUP_SHIFT,
932                                                   R_V7M_AIRCR_PRIGROUP_LENGTH);
933             if (attrs.secure) {
934                 /* These bits are only writable by secure */
935                 cpu->env.v7m.aircr = value &
936                     (R_V7M_AIRCR_SYSRESETREQS_MASK |
937                      R_V7M_AIRCR_BFHFNMINS_MASK |
938                      R_V7M_AIRCR_PRIS_MASK);
939             }
940             nvic_irq_update(s);
941         }
942         break;
943     case 0xd10: /* System Control.  */
944         /* TODO: Implement control registers.  */
945         qemu_log_mask(LOG_UNIMP, "NVIC: SCR unimplemented\n");
946         break;
947     case 0xd14: /* Configuration Control.  */
948         /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */
949         value &= (R_V7M_CCR_STKALIGN_MASK |
950                   R_V7M_CCR_BFHFNMIGN_MASK |
951                   R_V7M_CCR_DIV_0_TRP_MASK |
952                   R_V7M_CCR_UNALIGN_TRP_MASK |
953                   R_V7M_CCR_USERSETMPEND_MASK |
954                   R_V7M_CCR_NONBASETHRDENA_MASK);
955 
956         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
957             /* v8M makes NONBASETHRDENA and STKALIGN be RES1 */
958             value |= R_V7M_CCR_NONBASETHRDENA_MASK
959                 | R_V7M_CCR_STKALIGN_MASK;
960         }
961         if (attrs.secure) {
962             /* the BFHFNMIGN bit is not banked; keep that in the NS copy */
963             cpu->env.v7m.ccr[M_REG_NS] =
964                 (cpu->env.v7m.ccr[M_REG_NS] & ~R_V7M_CCR_BFHFNMIGN_MASK)
965                 | (value & R_V7M_CCR_BFHFNMIGN_MASK);
966             value &= ~R_V7M_CCR_BFHFNMIGN_MASK;
967         }
968 
969         cpu->env.v7m.ccr[attrs.secure] = value;
970         break;
971     case 0xd24: /* System Handler Control.  */
972         s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
973         s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;
974         s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
975         s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
976         s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;
977         s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;
978         s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;
979         s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;
980         s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
981         s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;
982         s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
983         s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
984         s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
985         s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;
986         nvic_irq_update(s);
987         break;
988     case 0xd28: /* Configurable Fault Status.  */
989         cpu->env.v7m.cfsr[attrs.secure] &= ~value; /* W1C */
990         if (attrs.secure) {
991             /* The BFSR bits [15:8] are shared between security states
992              * and we store them in the NS copy.
993              */
994             cpu->env.v7m.cfsr[M_REG_NS] &= ~(value & R_V7M_CFSR_BFSR_MASK);
995         }
996         break;
997     case 0xd2c: /* Hard Fault Status.  */
998         cpu->env.v7m.hfsr &= ~value; /* W1C */
999         break;
1000     case 0xd30: /* Debug Fault Status.  */
1001         cpu->env.v7m.dfsr &= ~value; /* W1C */
1002         break;
1003     case 0xd34: /* Mem Manage Address.  */
1004         cpu->env.v7m.mmfar[attrs.secure] = value;
1005         return;
1006     case 0xd38: /* Bus Fault Address.  */
1007         cpu->env.v7m.bfar = value;
1008         return;
1009     case 0xd3c: /* Aux Fault Status.  */
1010         qemu_log_mask(LOG_UNIMP,
1011                       "NVIC: Aux fault status registers unimplemented\n");
1012         break;
1013     case 0xd90: /* MPU_TYPE */
1014         return; /* RO */
1015     case 0xd94: /* MPU_CTRL */
1016         if ((value &
1017              (R_V7M_MPU_CTRL_HFNMIENA_MASK | R_V7M_MPU_CTRL_ENABLE_MASK))
1018             == R_V7M_MPU_CTRL_HFNMIENA_MASK) {
1019             qemu_log_mask(LOG_GUEST_ERROR, "MPU_CTRL: HFNMIENA and !ENABLE is "
1020                           "UNPREDICTABLE\n");
1021         }
1022         cpu->env.v7m.mpu_ctrl[attrs.secure]
1023             = value & (R_V7M_MPU_CTRL_ENABLE_MASK |
1024                        R_V7M_MPU_CTRL_HFNMIENA_MASK |
1025                        R_V7M_MPU_CTRL_PRIVDEFENA_MASK);
1026         tlb_flush(CPU(cpu));
1027         break;
1028     case 0xd98: /* MPU_RNR */
1029         if (value >= cpu->pmsav7_dregion) {
1030             qemu_log_mask(LOG_GUEST_ERROR, "MPU region out of range %"
1031                           PRIu32 "/%" PRIu32 "\n",
1032                           value, cpu->pmsav7_dregion);
1033         } else {
1034             cpu->env.pmsav7.rnr[attrs.secure] = value;
1035         }
1036         break;
1037     case 0xd9c: /* MPU_RBAR */
1038     case 0xda4: /* MPU_RBAR_A1 */
1039     case 0xdac: /* MPU_RBAR_A2 */
1040     case 0xdb4: /* MPU_RBAR_A3 */
1041     {
1042         int region;
1043 
1044         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1045             /* PMSAv8M handling of the aliases is different from v7M:
1046              * aliases A1, A2, A3 override the low two bits of the region
1047              * number in MPU_RNR, and there is no 'region' field in the
1048              * RBAR register.
1049              */
1050             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1051 
1052             region = cpu->env.pmsav7.rnr[attrs.secure];
1053             if (aliasno) {
1054                 region = deposit32(region, 0, 2, aliasno);
1055             }
1056             if (region >= cpu->pmsav7_dregion) {
1057                 return;
1058             }
1059             cpu->env.pmsav8.rbar[attrs.secure][region] = value;
1060             tlb_flush(CPU(cpu));
1061             return;
1062         }
1063 
1064         if (value & (1 << 4)) {
1065             /* VALID bit means use the region number specified in this
1066              * value and also update MPU_RNR.REGION with that value.
1067              */
1068             region = extract32(value, 0, 4);
1069             if (region >= cpu->pmsav7_dregion) {
1070                 qemu_log_mask(LOG_GUEST_ERROR,
1071                               "MPU region out of range %u/%" PRIu32 "\n",
1072                               region, cpu->pmsav7_dregion);
1073                 return;
1074             }
1075             cpu->env.pmsav7.rnr[attrs.secure] = region;
1076         } else {
1077             region = cpu->env.pmsav7.rnr[attrs.secure];
1078         }
1079 
1080         if (region >= cpu->pmsav7_dregion) {
1081             return;
1082         }
1083 
1084         cpu->env.pmsav7.drbar[region] = value & ~0x1f;
1085         tlb_flush(CPU(cpu));
1086         break;
1087     }
1088     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
1089     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
1090     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
1091     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
1092     {
1093         int region = cpu->env.pmsav7.rnr[attrs.secure];
1094 
1095         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1096             /* PMSAv8M handling of the aliases is different from v7M:
1097              * aliases A1, A2, A3 override the low two bits of the region
1098              * number in MPU_RNR.
1099              */
1100             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1101 
1102             region = cpu->env.pmsav7.rnr[attrs.secure];
1103             if (aliasno) {
1104                 region = deposit32(region, 0, 2, aliasno);
1105             }
1106             if (region >= cpu->pmsav7_dregion) {
1107                 return;
1108             }
1109             cpu->env.pmsav8.rlar[attrs.secure][region] = value;
1110             tlb_flush(CPU(cpu));
1111             return;
1112         }
1113 
1114         if (region >= cpu->pmsav7_dregion) {
1115             return;
1116         }
1117 
1118         cpu->env.pmsav7.drsr[region] = value & 0xff3f;
1119         cpu->env.pmsav7.dracr[region] = (value >> 16) & 0x173f;
1120         tlb_flush(CPU(cpu));
1121         break;
1122     }
1123     case 0xdc0: /* MPU_MAIR0 */
1124         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1125             goto bad_offset;
1126         }
1127         if (cpu->pmsav7_dregion) {
1128             /* Register is RES0 if no MPU regions are implemented */
1129             cpu->env.pmsav8.mair0[attrs.secure] = value;
1130         }
1131         /* We don't need to do anything else because memory attributes
1132          * only affect cacheability, and we don't implement caching.
1133          */
1134         break;
1135     case 0xdc4: /* MPU_MAIR1 */
1136         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1137             goto bad_offset;
1138         }
1139         if (cpu->pmsav7_dregion) {
1140             /* Register is RES0 if no MPU regions are implemented */
1141             cpu->env.pmsav8.mair1[attrs.secure] = value;
1142         }
1143         /* We don't need to do anything else because memory attributes
1144          * only affect cacheability, and we don't implement caching.
1145          */
1146         break;
1147     case 0xf00: /* Software Triggered Interrupt Register */
1148     {
1149         int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;
1150         if (excnum < s->num_irq) {
1151             armv7m_nvic_set_pending(s, excnum, false);
1152         }
1153         break;
1154     }
1155     default:
1156     bad_offset:
1157         qemu_log_mask(LOG_GUEST_ERROR,
1158                       "NVIC: Bad write offset 0x%x\n", offset);
1159     }
1160 }
1161 
1162 static bool nvic_user_access_ok(NVICState *s, hwaddr offset, MemTxAttrs attrs)
1163 {
1164     /* Return true if unprivileged access to this register is permitted. */
1165     switch (offset) {
1166     case 0xf00: /* STIR: accessible only if CCR.USERSETMPEND permits */
1167         /* For access via STIR_NS it is the NS CCR.USERSETMPEND that
1168          * controls access even though the CPU is in Secure state (I_QDKX).
1169          */
1170         return s->cpu->env.v7m.ccr[attrs.secure] & R_V7M_CCR_USERSETMPEND_MASK;
1171     default:
1172         /* All other user accesses cause a BusFault unconditionally */
1173         return false;
1174     }
1175 }
1176 
1177 static int shpr_bank(NVICState *s, int exc, MemTxAttrs attrs)
1178 {
1179     /* Behaviour for the SHPR register field for this exception:
1180      * return M_REG_NS to use the nonsecure vector (including for
1181      * non-banked exceptions), M_REG_S for the secure version of
1182      * a banked exception, and -1 if this field should RAZ/WI.
1183      */
1184     switch (exc) {
1185     case ARMV7M_EXCP_MEM:
1186     case ARMV7M_EXCP_USAGE:
1187     case ARMV7M_EXCP_SVC:
1188     case ARMV7M_EXCP_PENDSV:
1189     case ARMV7M_EXCP_SYSTICK:
1190         /* Banked exceptions */
1191         return attrs.secure;
1192     case ARMV7M_EXCP_BUS:
1193         /* Not banked, RAZ/WI from nonsecure if BFHFNMINS is zero */
1194         if (!attrs.secure &&
1195             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1196             return -1;
1197         }
1198         return M_REG_NS;
1199     case ARMV7M_EXCP_SECURE:
1200         /* Not banked, RAZ/WI from nonsecure */
1201         if (!attrs.secure) {
1202             return -1;
1203         }
1204         return M_REG_NS;
1205     case ARMV7M_EXCP_DEBUG:
1206         /* Not banked. TODO should RAZ/WI if DEMCR.SDME is set */
1207         return M_REG_NS;
1208     case 8 ... 10:
1209     case 13:
1210         /* RES0 */
1211         return -1;
1212     default:
1213         /* Not reachable due to decode of SHPR register addresses */
1214         g_assert_not_reached();
1215     }
1216 }
1217 
1218 static MemTxResult nvic_sysreg_read(void *opaque, hwaddr addr,
1219                                     uint64_t *data, unsigned size,
1220                                     MemTxAttrs attrs)
1221 {
1222     NVICState *s = (NVICState *)opaque;
1223     uint32_t offset = addr;
1224     unsigned i, startvec, end;
1225     uint32_t val;
1226 
1227     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
1228         /* Generate BusFault for unprivileged accesses */
1229         return MEMTX_ERROR;
1230     }
1231 
1232     switch (offset) {
1233     /* reads of set and clear both return the status */
1234     case 0x100 ... 0x13f: /* NVIC Set enable */
1235         offset += 0x80;
1236         /* fall through */
1237     case 0x180 ... 0x1bf: /* NVIC Clear enable */
1238         val = 0;
1239         startvec = offset - 0x180 + NVIC_FIRST_IRQ; /* vector # */
1240 
1241         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1242             if (s->vectors[startvec + i].enabled &&
1243                 (attrs.secure || s->itns[startvec + i])) {
1244                 val |= (1 << i);
1245             }
1246         }
1247         break;
1248     case 0x200 ... 0x23f: /* NVIC Set pend */
1249         offset += 0x80;
1250         /* fall through */
1251     case 0x280 ... 0x2bf: /* NVIC Clear pend */
1252         val = 0;
1253         startvec = offset - 0x280 + NVIC_FIRST_IRQ; /* vector # */
1254         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1255             if (s->vectors[startvec + i].pending &&
1256                 (attrs.secure || s->itns[startvec + i])) {
1257                 val |= (1 << i);
1258             }
1259         }
1260         break;
1261     case 0x300 ... 0x33f: /* NVIC Active */
1262         val = 0;
1263         startvec = offset - 0x300 + NVIC_FIRST_IRQ; /* vector # */
1264 
1265         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1266             if (s->vectors[startvec + i].active &&
1267                 (attrs.secure || s->itns[startvec + i])) {
1268                 val |= (1 << i);
1269             }
1270         }
1271         break;
1272     case 0x400 ... 0x5ef: /* NVIC Priority */
1273         val = 0;
1274         startvec = offset - 0x400 + NVIC_FIRST_IRQ; /* vector # */
1275 
1276         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
1277             if (attrs.secure || s->itns[startvec + i]) {
1278                 val |= s->vectors[startvec + i].prio << (8 * i);
1279             }
1280         }
1281         break;
1282     case 0xd18 ... 0xd23: /* System Handler Priority (SHPR1, SHPR2, SHPR3) */
1283         val = 0;
1284         for (i = 0; i < size; i++) {
1285             unsigned hdlidx = (offset - 0xd14) + i;
1286             int sbank = shpr_bank(s, hdlidx, attrs);
1287 
1288             if (sbank < 0) {
1289                 continue;
1290             }
1291             val = deposit32(val, i * 8, 8, get_prio(s, hdlidx, sbank));
1292         }
1293         break;
1294     case 0xfe0 ... 0xfff: /* ID.  */
1295         if (offset & 3) {
1296             val = 0;
1297         } else {
1298             val = nvic_id[(offset - 0xfe0) >> 2];
1299         }
1300         break;
1301     default:
1302         if (size == 4) {
1303             val = nvic_readl(s, offset, attrs);
1304         } else {
1305             qemu_log_mask(LOG_GUEST_ERROR,
1306                           "NVIC: Bad read of size %d at offset 0x%x\n",
1307                           size, offset);
1308             val = 0;
1309         }
1310     }
1311 
1312     trace_nvic_sysreg_read(addr, val, size);
1313     *data = val;
1314     return MEMTX_OK;
1315 }
1316 
1317 static MemTxResult nvic_sysreg_write(void *opaque, hwaddr addr,
1318                                      uint64_t value, unsigned size,
1319                                      MemTxAttrs attrs)
1320 {
1321     NVICState *s = (NVICState *)opaque;
1322     uint32_t offset = addr;
1323     unsigned i, startvec, end;
1324     unsigned setval = 0;
1325 
1326     trace_nvic_sysreg_write(addr, value, size);
1327 
1328     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
1329         /* Generate BusFault for unprivileged accesses */
1330         return MEMTX_ERROR;
1331     }
1332 
1333     switch (offset) {
1334     case 0x100 ... 0x13f: /* NVIC Set enable */
1335         offset += 0x80;
1336         setval = 1;
1337         /* fall through */
1338     case 0x180 ... 0x1bf: /* NVIC Clear enable */
1339         startvec = 8 * (offset - 0x180) + NVIC_FIRST_IRQ;
1340 
1341         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1342             if (value & (1 << i) &&
1343                 (attrs.secure || s->itns[startvec + i])) {
1344                 s->vectors[startvec + i].enabled = setval;
1345             }
1346         }
1347         nvic_irq_update(s);
1348         return MEMTX_OK;
1349     case 0x200 ... 0x23f: /* NVIC Set pend */
1350         /* the special logic in armv7m_nvic_set_pending()
1351          * is not needed since IRQs are never escalated
1352          */
1353         offset += 0x80;
1354         setval = 1;
1355         /* fall through */
1356     case 0x280 ... 0x2bf: /* NVIC Clear pend */
1357         startvec = 8 * (offset - 0x280) + NVIC_FIRST_IRQ; /* vector # */
1358 
1359         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1360             if (value & (1 << i) &&
1361                 (attrs.secure || s->itns[startvec + i])) {
1362                 s->vectors[startvec + i].pending = setval;
1363             }
1364         }
1365         nvic_irq_update(s);
1366         return MEMTX_OK;
1367     case 0x300 ... 0x33f: /* NVIC Active */
1368         return MEMTX_OK; /* R/O */
1369     case 0x400 ... 0x5ef: /* NVIC Priority */
1370         startvec = 8 * (offset - 0x400) + NVIC_FIRST_IRQ; /* vector # */
1371 
1372         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
1373             if (attrs.secure || s->itns[startvec + i]) {
1374                 set_prio(s, startvec + i, false, (value >> (i * 8)) & 0xff);
1375             }
1376         }
1377         nvic_irq_update(s);
1378         return MEMTX_OK;
1379     case 0xd18 ... 0xd23: /* System Handler Priority (SHPR1, SHPR2, SHPR3) */
1380         for (i = 0; i < size; i++) {
1381             unsigned hdlidx = (offset - 0xd14) + i;
1382             int newprio = extract32(value, i * 8, 8);
1383             int sbank = shpr_bank(s, hdlidx, attrs);
1384 
1385             if (sbank < 0) {
1386                 continue;
1387             }
1388             set_prio(s, hdlidx, sbank, newprio);
1389         }
1390         nvic_irq_update(s);
1391         return MEMTX_OK;
1392     }
1393     if (size == 4) {
1394         nvic_writel(s, offset, value, attrs);
1395         return MEMTX_OK;
1396     }
1397     qemu_log_mask(LOG_GUEST_ERROR,
1398                   "NVIC: Bad write of size %d at offset 0x%x\n", size, offset);
1399     /* This is UNPREDICTABLE; treat as RAZ/WI */
1400     return MEMTX_OK;
1401 }
1402 
1403 static const MemoryRegionOps nvic_sysreg_ops = {
1404     .read_with_attrs = nvic_sysreg_read,
1405     .write_with_attrs = nvic_sysreg_write,
1406     .endianness = DEVICE_NATIVE_ENDIAN,
1407 };
1408 
1409 static MemTxResult nvic_sysreg_ns_write(void *opaque, hwaddr addr,
1410                                         uint64_t value, unsigned size,
1411                                         MemTxAttrs attrs)
1412 {
1413     if (attrs.secure) {
1414         /* S accesses to the alias act like NS accesses to the real region */
1415         attrs.secure = 0;
1416         return nvic_sysreg_write(opaque, addr, value, size, attrs);
1417     } else {
1418         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
1419         if (attrs.user) {
1420             return MEMTX_ERROR;
1421         }
1422         return MEMTX_OK;
1423     }
1424 }
1425 
1426 static MemTxResult nvic_sysreg_ns_read(void *opaque, hwaddr addr,
1427                                        uint64_t *data, unsigned size,
1428                                        MemTxAttrs attrs)
1429 {
1430     if (attrs.secure) {
1431         /* S accesses to the alias act like NS accesses to the real region */
1432         attrs.secure = 0;
1433         return nvic_sysreg_read(opaque, addr, data, size, attrs);
1434     } else {
1435         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
1436         if (attrs.user) {
1437             return MEMTX_ERROR;
1438         }
1439         *data = 0;
1440         return MEMTX_OK;
1441     }
1442 }
1443 
1444 static const MemoryRegionOps nvic_sysreg_ns_ops = {
1445     .read_with_attrs = nvic_sysreg_ns_read,
1446     .write_with_attrs = nvic_sysreg_ns_write,
1447     .endianness = DEVICE_NATIVE_ENDIAN,
1448 };
1449 
1450 static int nvic_post_load(void *opaque, int version_id)
1451 {
1452     NVICState *s = opaque;
1453     unsigned i;
1454 
1455     /* Check for out of range priority settings */
1456     if (s->vectors[ARMV7M_EXCP_RESET].prio != -3 ||
1457         s->vectors[ARMV7M_EXCP_NMI].prio != -2 ||
1458         s->vectors[ARMV7M_EXCP_HARD].prio != -1) {
1459         return 1;
1460     }
1461     for (i = ARMV7M_EXCP_MEM; i < s->num_irq; i++) {
1462         if (s->vectors[i].prio & ~0xff) {
1463             return 1;
1464         }
1465     }
1466 
1467     nvic_recompute_state(s);
1468 
1469     return 0;
1470 }
1471 
1472 static const VMStateDescription vmstate_VecInfo = {
1473     .name = "armv7m_nvic_info",
1474     .version_id = 1,
1475     .minimum_version_id = 1,
1476     .fields = (VMStateField[]) {
1477         VMSTATE_INT16(prio, VecInfo),
1478         VMSTATE_UINT8(enabled, VecInfo),
1479         VMSTATE_UINT8(pending, VecInfo),
1480         VMSTATE_UINT8(active, VecInfo),
1481         VMSTATE_UINT8(level, VecInfo),
1482         VMSTATE_END_OF_LIST()
1483     }
1484 };
1485 
1486 static bool nvic_security_needed(void *opaque)
1487 {
1488     NVICState *s = opaque;
1489 
1490     return arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY);
1491 }
1492 
1493 static int nvic_security_post_load(void *opaque, int version_id)
1494 {
1495     NVICState *s = opaque;
1496     int i;
1497 
1498     /* Check for out of range priority settings */
1499     if (s->sec_vectors[ARMV7M_EXCP_HARD].prio != -1) {
1500         return 1;
1501     }
1502     for (i = ARMV7M_EXCP_MEM; i < ARRAY_SIZE(s->sec_vectors); i++) {
1503         if (s->sec_vectors[i].prio & ~0xff) {
1504             return 1;
1505         }
1506     }
1507     return 0;
1508 }
1509 
1510 static const VMStateDescription vmstate_nvic_security = {
1511     .name = "nvic/m-security",
1512     .version_id = 1,
1513     .minimum_version_id = 1,
1514     .needed = nvic_security_needed,
1515     .post_load = &nvic_security_post_load,
1516     .fields = (VMStateField[]) {
1517         VMSTATE_STRUCT_ARRAY(sec_vectors, NVICState, NVIC_INTERNAL_VECTORS, 1,
1518                              vmstate_VecInfo, VecInfo),
1519         VMSTATE_UINT32(prigroup[M_REG_S], NVICState),
1520         VMSTATE_BOOL_ARRAY(itns, NVICState, NVIC_MAX_VECTORS),
1521         VMSTATE_END_OF_LIST()
1522     }
1523 };
1524 
1525 static const VMStateDescription vmstate_nvic = {
1526     .name = "armv7m_nvic",
1527     .version_id = 4,
1528     .minimum_version_id = 4,
1529     .post_load = &nvic_post_load,
1530     .fields = (VMStateField[]) {
1531         VMSTATE_STRUCT_ARRAY(vectors, NVICState, NVIC_MAX_VECTORS, 1,
1532                              vmstate_VecInfo, VecInfo),
1533         VMSTATE_UINT32(prigroup[M_REG_NS], NVICState),
1534         VMSTATE_END_OF_LIST()
1535     },
1536     .subsections = (const VMStateDescription*[]) {
1537         &vmstate_nvic_security,
1538         NULL
1539     }
1540 };
1541 
1542 static Property props_nvic[] = {
1543     /* Number of external IRQ lines (so excluding the 16 internal exceptions) */
1544     DEFINE_PROP_UINT32("num-irq", NVICState, num_irq, 64),
1545     DEFINE_PROP_END_OF_LIST()
1546 };
1547 
1548 static void armv7m_nvic_reset(DeviceState *dev)
1549 {
1550     NVICState *s = NVIC(dev);
1551 
1552     s->vectors[ARMV7M_EXCP_NMI].enabled = 1;
1553     s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
1554     /* MEM, BUS, and USAGE are enabled through
1555      * the System Handler Control register
1556      */
1557     s->vectors[ARMV7M_EXCP_SVC].enabled = 1;
1558     s->vectors[ARMV7M_EXCP_DEBUG].enabled = 1;
1559     s->vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
1560     s->vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
1561 
1562     s->vectors[ARMV7M_EXCP_RESET].prio = -3;
1563     s->vectors[ARMV7M_EXCP_NMI].prio = -2;
1564     s->vectors[ARMV7M_EXCP_HARD].prio = -1;
1565 
1566     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
1567         s->sec_vectors[ARMV7M_EXCP_HARD].enabled = 1;
1568         s->sec_vectors[ARMV7M_EXCP_SVC].enabled = 1;
1569         s->sec_vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
1570         s->sec_vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
1571 
1572         /* AIRCR.BFHFNMINS resets to 0 so Secure HF is priority -1 (R_CMTC) */
1573         s->sec_vectors[ARMV7M_EXCP_HARD].prio = -1;
1574     }
1575 
1576     /* Strictly speaking the reset handler should be enabled.
1577      * However, we don't simulate soft resets through the NVIC,
1578      * and the reset vector should never be pended.
1579      * So we leave it disabled to catch logic errors.
1580      */
1581 
1582     s->exception_prio = NVIC_NOEXC_PRIO;
1583     s->vectpending = 0;
1584     s->vectpending_is_s_banked = false;
1585     s->vectpending_prio = NVIC_NOEXC_PRIO;
1586 
1587     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
1588         memset(s->itns, 0, sizeof(s->itns));
1589     } else {
1590         /* This state is constant and not guest accessible in a non-security
1591          * NVIC; we set the bits to true to avoid having to do a feature
1592          * bit check in the NVIC enable/pend/etc register accessors.
1593          */
1594         int i;
1595 
1596         for (i = NVIC_FIRST_IRQ; i < ARRAY_SIZE(s->itns); i++) {
1597             s->itns[i] = true;
1598         }
1599     }
1600 }
1601 
1602 static void nvic_systick_trigger(void *opaque, int n, int level)
1603 {
1604     NVICState *s = opaque;
1605 
1606     if (level) {
1607         /* SysTick just asked us to pend its exception.
1608          * (This is different from an external interrupt line's
1609          * behaviour.)
1610          * TODO: when we implement the banked systicks we must make
1611          * this pend the correct banked exception.
1612          */
1613         armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, false);
1614     }
1615 }
1616 
1617 static void armv7m_nvic_realize(DeviceState *dev, Error **errp)
1618 {
1619     NVICState *s = NVIC(dev);
1620     SysBusDevice *systick_sbd;
1621     Error *err = NULL;
1622     int regionlen;
1623 
1624     s->cpu = ARM_CPU(qemu_get_cpu(0));
1625     assert(s->cpu);
1626 
1627     if (s->num_irq > NVIC_MAX_IRQ) {
1628         error_setg(errp, "num-irq %d exceeds NVIC maximum", s->num_irq);
1629         return;
1630     }
1631 
1632     qdev_init_gpio_in(dev, set_irq_level, s->num_irq);
1633 
1634     /* include space for internal exception vectors */
1635     s->num_irq += NVIC_FIRST_IRQ;
1636 
1637     object_property_set_bool(OBJECT(&s->systick), true, "realized", &err);
1638     if (err != NULL) {
1639         error_propagate(errp, err);
1640         return;
1641     }
1642     systick_sbd = SYS_BUS_DEVICE(&s->systick);
1643     sysbus_connect_irq(systick_sbd, 0,
1644                        qdev_get_gpio_in_named(dev, "systick-trigger", 0));
1645 
1646     /* The NVIC and System Control Space (SCS) starts at 0xe000e000
1647      * and looks like this:
1648      *  0x004 - ICTR
1649      *  0x010 - 0xff - systick
1650      *  0x100..0x7ec - NVIC
1651      *  0x7f0..0xcff - Reserved
1652      *  0xd00..0xd3c - SCS registers
1653      *  0xd40..0xeff - Reserved or Not implemented
1654      *  0xf00 - STIR
1655      *
1656      * Some registers within this space are banked between security states.
1657      * In v8M there is a second range 0xe002e000..0xe002efff which is the
1658      * NonSecure alias SCS; secure accesses to this behave like NS accesses
1659      * to the main SCS range, and non-secure accesses (including when
1660      * the security extension is not implemented) are RAZ/WI.
1661      * Note that both the main SCS range and the alias range are defined
1662      * to be exempt from memory attribution (R_BLJT) and so the memory
1663      * transaction attribute always matches the current CPU security
1664      * state (attrs.secure == env->v7m.secure). In the nvic_sysreg_ns_ops
1665      * wrappers we change attrs.secure to indicate the NS access; so
1666      * generally code determining which banked register to use should
1667      * use attrs.secure; code determining actual behaviour of the system
1668      * should use env->v7m.secure.
1669      */
1670     regionlen = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? 0x21000 : 0x1000;
1671     memory_region_init(&s->container, OBJECT(s), "nvic", regionlen);
1672     /* The system register region goes at the bottom of the priority
1673      * stack as it covers the whole page.
1674      */
1675     memory_region_init_io(&s->sysregmem, OBJECT(s), &nvic_sysreg_ops, s,
1676                           "nvic_sysregs", 0x1000);
1677     memory_region_add_subregion(&s->container, 0, &s->sysregmem);
1678     memory_region_add_subregion_overlap(&s->container, 0x10,
1679                                         sysbus_mmio_get_region(systick_sbd, 0),
1680                                         1);
1681 
1682     if (arm_feature(&s->cpu->env, ARM_FEATURE_V8)) {
1683         memory_region_init_io(&s->sysreg_ns_mem, OBJECT(s),
1684                               &nvic_sysreg_ns_ops, s,
1685                               "nvic_sysregs_ns", 0x1000);
1686         memory_region_add_subregion(&s->container, 0x20000, &s->sysreg_ns_mem);
1687     }
1688 
1689     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->container);
1690 }
1691 
1692 static void armv7m_nvic_instance_init(Object *obj)
1693 {
1694     /* We have a different default value for the num-irq property
1695      * than our superclass. This function runs after qdev init
1696      * has set the defaults from the Property array and before
1697      * any user-specified property setting, so just modify the
1698      * value in the GICState struct.
1699      */
1700     DeviceState *dev = DEVICE(obj);
1701     NVICState *nvic = NVIC(obj);
1702     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
1703 
1704     object_initialize(&nvic->systick, sizeof(nvic->systick), TYPE_SYSTICK);
1705     qdev_set_parent_bus(DEVICE(&nvic->systick), sysbus_get_default());
1706 
1707     sysbus_init_irq(sbd, &nvic->excpout);
1708     qdev_init_gpio_out_named(dev, &nvic->sysresetreq, "SYSRESETREQ", 1);
1709     qdev_init_gpio_in_named(dev, nvic_systick_trigger, "systick-trigger", 1);
1710 }
1711 
1712 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
1713 {
1714     DeviceClass *dc = DEVICE_CLASS(klass);
1715 
1716     dc->vmsd  = &vmstate_nvic;
1717     dc->props = props_nvic;
1718     dc->reset = armv7m_nvic_reset;
1719     dc->realize = armv7m_nvic_realize;
1720 }
1721 
1722 static const TypeInfo armv7m_nvic_info = {
1723     .name          = TYPE_NVIC,
1724     .parent        = TYPE_SYS_BUS_DEVICE,
1725     .instance_init = armv7m_nvic_instance_init,
1726     .instance_size = sizeof(NVICState),
1727     .class_init    = armv7m_nvic_class_init,
1728     .class_size    = sizeof(SysBusDeviceClass),
1729 };
1730 
1731 static void armv7m_nvic_register_types(void)
1732 {
1733     type_register_static(&armv7m_nvic_info);
1734 }
1735 
1736 type_init(armv7m_nvic_register_types)
1737