xref: /openbmc/qemu/hw/intc/armv7m_nvic.c (revision 5ede82b8ccb652382c106d53f656ed67997d76e8)
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 = NVIC_NOEXC_PRIO;
323 
324     if (env->v7m.basepri[M_REG_NS] > 0) {
325         running = exc_group_prio(s, env->v7m.basepri[M_REG_NS], M_REG_NS);
326     }
327 
328     if (env->v7m.basepri[M_REG_S] > 0) {
329         int basepri = exc_group_prio(s, env->v7m.basepri[M_REG_S], M_REG_S);
330         if (running > basepri) {
331             running = basepri;
332         }
333     }
334 
335     if (env->v7m.primask[M_REG_NS]) {
336         if (env->v7m.aircr & R_V7M_AIRCR_PRIS_MASK) {
337             if (running > NVIC_NS_PRIO_LIMIT) {
338                 running = NVIC_NS_PRIO_LIMIT;
339             }
340         } else {
341             running = 0;
342         }
343     }
344 
345     if (env->v7m.primask[M_REG_S]) {
346         running = 0;
347     }
348 
349     if (env->v7m.faultmask[M_REG_NS]) {
350         if (env->v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
351             running = -1;
352         } else {
353             if (env->v7m.aircr & R_V7M_AIRCR_PRIS_MASK) {
354                 if (running > NVIC_NS_PRIO_LIMIT) {
355                     running = NVIC_NS_PRIO_LIMIT;
356                 }
357             } else {
358                 running = 0;
359             }
360         }
361     }
362 
363     if (env->v7m.faultmask[M_REG_S]) {
364         running = (env->v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) ? -3 : -1;
365     }
366 
367     /* consider priority of active handler */
368     return MIN(running, s->exception_prio);
369 }
370 
371 bool armv7m_nvic_neg_prio_requested(void *opaque, bool secure)
372 {
373     /* Return true if the requested execution priority is negative
374      * for the specified security state, ie that security state
375      * has an active NMI or HardFault or has set its FAULTMASK.
376      * Note that this is not the same as whether the execution
377      * priority is actually negative (for instance AIRCR.PRIS may
378      * mean we don't allow FAULTMASK_NS to actually make the execution
379      * priority negative). Compare pseudocode IsReqExcPriNeg().
380      */
381     NVICState *s = opaque;
382 
383     if (s->cpu->env.v7m.faultmask[secure]) {
384         return true;
385     }
386 
387     if (secure ? s->sec_vectors[ARMV7M_EXCP_HARD].active :
388         s->vectors[ARMV7M_EXCP_HARD].active) {
389         return true;
390     }
391 
392     if (s->vectors[ARMV7M_EXCP_NMI].active &&
393         exc_targets_secure(s, ARMV7M_EXCP_NMI) == secure) {
394         return true;
395     }
396 
397     return false;
398 }
399 
400 bool armv7m_nvic_can_take_pending_exception(void *opaque)
401 {
402     NVICState *s = opaque;
403 
404     return nvic_exec_prio(s) > nvic_pending_prio(s);
405 }
406 
407 int armv7m_nvic_raw_execution_priority(void *opaque)
408 {
409     NVICState *s = opaque;
410 
411     return s->exception_prio;
412 }
413 
414 /* caller must call nvic_irq_update() after this.
415  * secure indicates the bank to use for banked exceptions (we assert if
416  * we are passed secure=true for a non-banked exception).
417  */
418 static void set_prio(NVICState *s, unsigned irq, bool secure, uint8_t prio)
419 {
420     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
421     assert(irq < s->num_irq);
422 
423     if (secure) {
424         assert(exc_is_banked(irq));
425         s->sec_vectors[irq].prio = prio;
426     } else {
427         s->vectors[irq].prio = prio;
428     }
429 
430     trace_nvic_set_prio(irq, secure, prio);
431 }
432 
433 /* Return the current raw priority register value.
434  * secure indicates the bank to use for banked exceptions (we assert if
435  * we are passed secure=true for a non-banked exception).
436  */
437 static int get_prio(NVICState *s, unsigned irq, bool secure)
438 {
439     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
440     assert(irq < s->num_irq);
441 
442     if (secure) {
443         assert(exc_is_banked(irq));
444         return s->sec_vectors[irq].prio;
445     } else {
446         return s->vectors[irq].prio;
447     }
448 }
449 
450 /* Recompute state and assert irq line accordingly.
451  * Must be called after changes to:
452  *  vec->active, vec->enabled, vec->pending or vec->prio for any vector
453  *  prigroup
454  */
455 static void nvic_irq_update(NVICState *s)
456 {
457     int lvl;
458     int pend_prio;
459 
460     nvic_recompute_state(s);
461     pend_prio = nvic_pending_prio(s);
462 
463     /* Raise NVIC output if this IRQ would be taken, except that we
464      * ignore the effects of the BASEPRI, FAULTMASK and PRIMASK (which
465      * will be checked for in arm_v7m_cpu_exec_interrupt()); changes
466      * to those CPU registers don't cause us to recalculate the NVIC
467      * pending info.
468      */
469     lvl = (pend_prio < s->exception_prio);
470     trace_nvic_irq_update(s->vectpending, pend_prio, s->exception_prio, lvl);
471     qemu_set_irq(s->excpout, lvl);
472 }
473 
474 /**
475  * armv7m_nvic_clear_pending: mark the specified exception as not pending
476  * @opaque: the NVIC
477  * @irq: the exception number to mark as not pending
478  * @secure: false for non-banked exceptions or for the nonsecure
479  * version of a banked exception, true for the secure version of a banked
480  * exception.
481  *
482  * Marks the specified exception as not pending. Note that we will assert()
483  * if @secure is true and @irq does not specify one of the fixed set
484  * of architecturally banked exceptions.
485  */
486 static void armv7m_nvic_clear_pending(void *opaque, int irq, bool secure)
487 {
488     NVICState *s = (NVICState *)opaque;
489     VecInfo *vec;
490 
491     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
492 
493     if (secure) {
494         assert(exc_is_banked(irq));
495         vec = &s->sec_vectors[irq];
496     } else {
497         vec = &s->vectors[irq];
498     }
499     trace_nvic_clear_pending(irq, secure, vec->enabled, vec->prio);
500     if (vec->pending) {
501         vec->pending = 0;
502         nvic_irq_update(s);
503     }
504 }
505 
506 static void do_armv7m_nvic_set_pending(void *opaque, int irq, bool secure,
507                                        bool derived)
508 {
509     /* Pend an exception, including possibly escalating it to HardFault.
510      *
511      * This function handles both "normal" pending of interrupts and
512      * exceptions, and also derived exceptions (ones which occur as
513      * a result of trying to take some other exception).
514      *
515      * If derived == true, the caller guarantees that we are part way through
516      * trying to take an exception (but have not yet called
517      * armv7m_nvic_acknowledge_irq() to make it active), and so:
518      *  - s->vectpending is the "original exception" we were trying to take
519      *  - irq is the "derived exception"
520      *  - nvic_exec_prio(s) gives the priority before exception entry
521      * Here we handle the prioritization logic which the pseudocode puts
522      * in the DerivedLateArrival() function.
523      */
524 
525     NVICState *s = (NVICState *)opaque;
526     bool banked = exc_is_banked(irq);
527     VecInfo *vec;
528 
529     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
530     assert(!secure || banked);
531 
532     vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];
533 
534     trace_nvic_set_pending(irq, secure, derived, vec->enabled, vec->prio);
535 
536     if (derived) {
537         /* Derived exceptions are always synchronous. */
538         assert(irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV);
539 
540         if (irq == ARMV7M_EXCP_DEBUG &&
541             exc_group_prio(s, vec->prio, secure) >= nvic_exec_prio(s)) {
542             /* DebugMonitorFault, but its priority is lower than the
543              * preempted exception priority: just ignore it.
544              */
545             return;
546         }
547 
548         if (irq == ARMV7M_EXCP_HARD && vec->prio >= s->vectpending_prio) {
549             /* If this is a terminal exception (one which means we cannot
550              * take the original exception, like a failure to read its
551              * vector table entry), then we must take the derived exception.
552              * If the derived exception can't take priority over the
553              * original exception, then we go into Lockup.
554              *
555              * For QEMU, we rely on the fact that a derived exception is
556              * terminal if and only if it's reported to us as HardFault,
557              * which saves having to have an extra argument is_terminal
558              * that we'd only use in one place.
559              */
560             cpu_abort(&s->cpu->parent_obj,
561                       "Lockup: can't take terminal derived exception "
562                       "(original exception priority %d)\n",
563                       s->vectpending_prio);
564         }
565         /* We now continue with the same code as for a normal pending
566          * exception, which will cause us to pend the derived exception.
567          * We'll then take either the original or the derived exception
568          * based on which is higher priority by the usual mechanism
569          * for selecting the highest priority pending interrupt.
570          */
571     }
572 
573     if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {
574         /* If a synchronous exception is pending then it may be
575          * escalated to HardFault if:
576          *  * it is equal or lower priority to current execution
577          *  * it is disabled
578          * (ie we need to take it immediately but we can't do so).
579          * Asynchronous exceptions (and interrupts) simply remain pending.
580          *
581          * For QEMU, we don't have any imprecise (asynchronous) faults,
582          * so we can assume that PREFETCH_ABORT and DATA_ABORT are always
583          * synchronous.
584          * Debug exceptions are awkward because only Debug exceptions
585          * resulting from the BKPT instruction should be escalated,
586          * but we don't currently implement any Debug exceptions other
587          * than those that result from BKPT, so we treat all debug exceptions
588          * as needing escalation.
589          *
590          * This all means we can identify whether to escalate based only on
591          * the exception number and don't (yet) need the caller to explicitly
592          * tell us whether this exception is synchronous or not.
593          */
594         int running = nvic_exec_prio(s);
595         bool escalate = false;
596 
597         if (exc_group_prio(s, vec->prio, secure) >= running) {
598             trace_nvic_escalate_prio(irq, vec->prio, running);
599             escalate = true;
600         } else if (!vec->enabled) {
601             trace_nvic_escalate_disabled(irq);
602             escalate = true;
603         }
604 
605         if (escalate) {
606 
607             /* We need to escalate this exception to a synchronous HardFault.
608              * If BFHFNMINS is set then we escalate to the banked HF for
609              * the target security state of the original exception; otherwise
610              * we take a Secure HardFault.
611              */
612             irq = ARMV7M_EXCP_HARD;
613             if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY) &&
614                 (secure ||
615                  !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))) {
616                 vec = &s->sec_vectors[irq];
617             } else {
618                 vec = &s->vectors[irq];
619             }
620             if (running <= vec->prio) {
621                 /* We want to escalate to HardFault but we can't take the
622                  * synchronous HardFault at this point either. This is a
623                  * Lockup condition due to a guest bug. We don't model
624                  * Lockup, so report via cpu_abort() instead.
625                  */
626                 cpu_abort(&s->cpu->parent_obj,
627                           "Lockup: can't escalate %d to HardFault "
628                           "(current priority %d)\n", irq, running);
629             }
630 
631             /* HF may be banked but there is only one shared HFSR */
632             s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;
633         }
634     }
635 
636     if (!vec->pending) {
637         vec->pending = 1;
638         nvic_irq_update(s);
639     }
640 }
641 
642 void armv7m_nvic_set_pending(void *opaque, int irq, bool secure)
643 {
644     do_armv7m_nvic_set_pending(opaque, irq, secure, false);
645 }
646 
647 void armv7m_nvic_set_pending_derived(void *opaque, int irq, bool secure)
648 {
649     do_armv7m_nvic_set_pending(opaque, irq, secure, true);
650 }
651 
652 /* Make pending IRQ active.  */
653 bool armv7m_nvic_acknowledge_irq(void *opaque)
654 {
655     NVICState *s = (NVICState *)opaque;
656     CPUARMState *env = &s->cpu->env;
657     const int pending = s->vectpending;
658     const int running = nvic_exec_prio(s);
659     VecInfo *vec;
660     bool targets_secure;
661 
662     assert(pending > ARMV7M_EXCP_RESET && pending < s->num_irq);
663 
664     if (s->vectpending_is_s_banked) {
665         vec = &s->sec_vectors[pending];
666         targets_secure = true;
667     } else {
668         vec = &s->vectors[pending];
669         targets_secure = !exc_is_banked(s->vectpending) &&
670             exc_targets_secure(s, s->vectpending);
671     }
672 
673     assert(vec->enabled);
674     assert(vec->pending);
675 
676     assert(s->vectpending_prio < running);
677 
678     trace_nvic_acknowledge_irq(pending, s->vectpending_prio, targets_secure);
679 
680     vec->active = 1;
681     vec->pending = 0;
682 
683     write_v7m_exception(env, s->vectpending);
684 
685     nvic_irq_update(s);
686 
687     return targets_secure;
688 }
689 
690 int armv7m_nvic_complete_irq(void *opaque, int irq, bool secure)
691 {
692     NVICState *s = (NVICState *)opaque;
693     VecInfo *vec;
694     int ret;
695 
696     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
697 
698     if (secure && exc_is_banked(irq)) {
699         vec = &s->sec_vectors[irq];
700     } else {
701         vec = &s->vectors[irq];
702     }
703 
704     trace_nvic_complete_irq(irq, secure);
705 
706     if (!vec->active) {
707         /* Tell the caller this was an illegal exception return */
708         return -1;
709     }
710 
711     ret = nvic_rettobase(s);
712 
713     vec->active = 0;
714     if (vec->level) {
715         /* Re-pend the exception if it's still held high; only
716          * happens for extenal IRQs
717          */
718         assert(irq >= NVIC_FIRST_IRQ);
719         vec->pending = 1;
720     }
721 
722     nvic_irq_update(s);
723 
724     return ret;
725 }
726 
727 /* callback when external interrupt line is changed */
728 static void set_irq_level(void *opaque, int n, int level)
729 {
730     NVICState *s = opaque;
731     VecInfo *vec;
732 
733     n += NVIC_FIRST_IRQ;
734 
735     assert(n >= NVIC_FIRST_IRQ && n < s->num_irq);
736 
737     trace_nvic_set_irq_level(n, level);
738 
739     /* The pending status of an external interrupt is
740      * latched on rising edge and exception handler return.
741      *
742      * Pulsing the IRQ will always run the handler
743      * once, and the handler will re-run until the
744      * level is low when the handler completes.
745      */
746     vec = &s->vectors[n];
747     if (level != vec->level) {
748         vec->level = level;
749         if (level) {
750             armv7m_nvic_set_pending(s, n, false);
751         }
752     }
753 }
754 
755 static uint32_t nvic_readl(NVICState *s, uint32_t offset, MemTxAttrs attrs)
756 {
757     ARMCPU *cpu = s->cpu;
758     uint32_t val;
759 
760     switch (offset) {
761     case 4: /* Interrupt Control Type.  */
762         return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;
763     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
764     {
765         int startvec = 8 * (offset - 0x380) + NVIC_FIRST_IRQ;
766         int i;
767 
768         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
769             goto bad_offset;
770         }
771         if (!attrs.secure) {
772             return 0;
773         }
774         val = 0;
775         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
776             if (s->itns[startvec + i]) {
777                 val |= (1 << i);
778             }
779         }
780         return val;
781     }
782     case 0xd00: /* CPUID Base.  */
783         return cpu->midr;
784     case 0xd04: /* Interrupt Control State (ICSR) */
785         /* VECTACTIVE */
786         val = cpu->env.v7m.exception;
787         /* VECTPENDING */
788         val |= (s->vectpending & 0xff) << 12;
789         /* ISRPENDING - set if any external IRQ is pending */
790         if (nvic_isrpending(s)) {
791             val |= (1 << 22);
792         }
793         /* RETTOBASE - set if only one handler is active */
794         if (nvic_rettobase(s)) {
795             val |= (1 << 11);
796         }
797         if (attrs.secure) {
798             /* PENDSTSET */
799             if (s->sec_vectors[ARMV7M_EXCP_SYSTICK].pending) {
800                 val |= (1 << 26);
801             }
802             /* PENDSVSET */
803             if (s->sec_vectors[ARMV7M_EXCP_PENDSV].pending) {
804                 val |= (1 << 28);
805             }
806         } else {
807             /* PENDSTSET */
808             if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {
809                 val |= (1 << 26);
810             }
811             /* PENDSVSET */
812             if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {
813                 val |= (1 << 28);
814             }
815         }
816         /* NMIPENDSET */
817         if ((cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) &&
818             s->vectors[ARMV7M_EXCP_NMI].pending) {
819             val |= (1 << 31);
820         }
821         /* ISRPREEMPT: RES0 when halting debug not implemented */
822         /* STTNS: RES0 for the Main Extension */
823         return val;
824     case 0xd08: /* Vector Table Offset.  */
825         return cpu->env.v7m.vecbase[attrs.secure];
826     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
827         val = 0xfa050000 | (s->prigroup[attrs.secure] << 8);
828         if (attrs.secure) {
829             /* s->aircr stores PRIS, BFHFNMINS, SYSRESETREQS */
830             val |= cpu->env.v7m.aircr;
831         } else {
832             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
833                 /* BFHFNMINS is R/O from NS; other bits are RAZ/WI. If
834                  * security isn't supported then BFHFNMINS is RAO (and
835                  * the bit in env.v7m.aircr is always set).
836                  */
837                 val |= cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK;
838             }
839         }
840         return val;
841     case 0xd10: /* System Control.  */
842         /* TODO: Implement SLEEPONEXIT.  */
843         return 0;
844     case 0xd14: /* Configuration Control.  */
845         /* The BFHFNMIGN bit is the only non-banked bit; we
846          * keep it in the non-secure copy of the register.
847          */
848         val = cpu->env.v7m.ccr[attrs.secure];
849         val |= cpu->env.v7m.ccr[M_REG_NS] & R_V7M_CCR_BFHFNMIGN_MASK;
850         return val;
851     case 0xd24: /* System Handler Control and State (SHCSR) */
852         val = 0;
853         if (attrs.secure) {
854             if (s->sec_vectors[ARMV7M_EXCP_MEM].active) {
855                 val |= (1 << 0);
856             }
857             if (s->sec_vectors[ARMV7M_EXCP_HARD].active) {
858                 val |= (1 << 2);
859             }
860             if (s->sec_vectors[ARMV7M_EXCP_USAGE].active) {
861                 val |= (1 << 3);
862             }
863             if (s->sec_vectors[ARMV7M_EXCP_SVC].active) {
864                 val |= (1 << 7);
865             }
866             if (s->sec_vectors[ARMV7M_EXCP_PENDSV].active) {
867                 val |= (1 << 10);
868             }
869             if (s->sec_vectors[ARMV7M_EXCP_SYSTICK].active) {
870                 val |= (1 << 11);
871             }
872             if (s->sec_vectors[ARMV7M_EXCP_USAGE].pending) {
873                 val |= (1 << 12);
874             }
875             if (s->sec_vectors[ARMV7M_EXCP_MEM].pending) {
876                 val |= (1 << 13);
877             }
878             if (s->sec_vectors[ARMV7M_EXCP_SVC].pending) {
879                 val |= (1 << 15);
880             }
881             if (s->sec_vectors[ARMV7M_EXCP_MEM].enabled) {
882                 val |= (1 << 16);
883             }
884             if (s->sec_vectors[ARMV7M_EXCP_USAGE].enabled) {
885                 val |= (1 << 18);
886             }
887             if (s->sec_vectors[ARMV7M_EXCP_HARD].pending) {
888                 val |= (1 << 21);
889             }
890             /* SecureFault is not banked but is always RAZ/WI to NS */
891             if (s->vectors[ARMV7M_EXCP_SECURE].active) {
892                 val |= (1 << 4);
893             }
894             if (s->vectors[ARMV7M_EXCP_SECURE].enabled) {
895                 val |= (1 << 19);
896             }
897             if (s->vectors[ARMV7M_EXCP_SECURE].pending) {
898                 val |= (1 << 20);
899             }
900         } else {
901             if (s->vectors[ARMV7M_EXCP_MEM].active) {
902                 val |= (1 << 0);
903             }
904             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
905                 /* HARDFAULTACT, HARDFAULTPENDED not present in v7M */
906                 if (s->vectors[ARMV7M_EXCP_HARD].active) {
907                     val |= (1 << 2);
908                 }
909                 if (s->vectors[ARMV7M_EXCP_HARD].pending) {
910                     val |= (1 << 21);
911                 }
912             }
913             if (s->vectors[ARMV7M_EXCP_USAGE].active) {
914                 val |= (1 << 3);
915             }
916             if (s->vectors[ARMV7M_EXCP_SVC].active) {
917                 val |= (1 << 7);
918             }
919             if (s->vectors[ARMV7M_EXCP_PENDSV].active) {
920                 val |= (1 << 10);
921             }
922             if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {
923                 val |= (1 << 11);
924             }
925             if (s->vectors[ARMV7M_EXCP_USAGE].pending) {
926                 val |= (1 << 12);
927             }
928             if (s->vectors[ARMV7M_EXCP_MEM].pending) {
929                 val |= (1 << 13);
930             }
931             if (s->vectors[ARMV7M_EXCP_SVC].pending) {
932                 val |= (1 << 15);
933             }
934             if (s->vectors[ARMV7M_EXCP_MEM].enabled) {
935                 val |= (1 << 16);
936             }
937             if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {
938                 val |= (1 << 18);
939             }
940         }
941         if (attrs.secure || (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
942             if (s->vectors[ARMV7M_EXCP_BUS].active) {
943                 val |= (1 << 1);
944             }
945             if (s->vectors[ARMV7M_EXCP_BUS].pending) {
946                 val |= (1 << 14);
947             }
948             if (s->vectors[ARMV7M_EXCP_BUS].enabled) {
949                 val |= (1 << 17);
950             }
951             if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
952                 s->vectors[ARMV7M_EXCP_NMI].active) {
953                 /* NMIACT is not present in v7M */
954                 val |= (1 << 5);
955             }
956         }
957 
958         /* TODO: this is RAZ/WI from NS if DEMCR.SDME is set */
959         if (s->vectors[ARMV7M_EXCP_DEBUG].active) {
960             val |= (1 << 8);
961         }
962         return val;
963     case 0xd2c: /* Hard Fault Status.  */
964         return cpu->env.v7m.hfsr;
965     case 0xd30: /* Debug Fault Status.  */
966         return cpu->env.v7m.dfsr;
967     case 0xd34: /* MMFAR MemManage Fault Address */
968         return cpu->env.v7m.mmfar[attrs.secure];
969     case 0xd38: /* Bus Fault Address.  */
970         return cpu->env.v7m.bfar;
971     case 0xd3c: /* Aux Fault Status.  */
972         /* TODO: Implement fault status registers.  */
973         qemu_log_mask(LOG_UNIMP,
974                       "Aux Fault status registers unimplemented\n");
975         return 0;
976     case 0xd40: /* PFR0.  */
977         return 0x00000030;
978     case 0xd44: /* PRF1.  */
979         return 0x00000200;
980     case 0xd48: /* DFR0.  */
981         return 0x00100000;
982     case 0xd4c: /* AFR0.  */
983         return 0x00000000;
984     case 0xd50: /* MMFR0.  */
985         return 0x00000030;
986     case 0xd54: /* MMFR1.  */
987         return 0x00000000;
988     case 0xd58: /* MMFR2.  */
989         return 0x00000000;
990     case 0xd5c: /* MMFR3.  */
991         return 0x00000000;
992     case 0xd60: /* ISAR0.  */
993         return 0x01141110;
994     case 0xd64: /* ISAR1.  */
995         return 0x02111000;
996     case 0xd68: /* ISAR2.  */
997         return 0x21112231;
998     case 0xd6c: /* ISAR3.  */
999         return 0x01111110;
1000     case 0xd70: /* ISAR4.  */
1001         return 0x01310102;
1002     /* TODO: Implement debug registers.  */
1003     case 0xd90: /* MPU_TYPE */
1004         /* Unified MPU; if the MPU is not present this value is zero */
1005         return cpu->pmsav7_dregion << 8;
1006         break;
1007     case 0xd94: /* MPU_CTRL */
1008         return cpu->env.v7m.mpu_ctrl[attrs.secure];
1009     case 0xd98: /* MPU_RNR */
1010         return cpu->env.pmsav7.rnr[attrs.secure];
1011     case 0xd9c: /* MPU_RBAR */
1012     case 0xda4: /* MPU_RBAR_A1 */
1013     case 0xdac: /* MPU_RBAR_A2 */
1014     case 0xdb4: /* MPU_RBAR_A3 */
1015     {
1016         int region = cpu->env.pmsav7.rnr[attrs.secure];
1017 
1018         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1019             /* PMSAv8M handling of the aliases is different from v7M:
1020              * aliases A1, A2, A3 override the low two bits of the region
1021              * number in MPU_RNR, and there is no 'region' field in the
1022              * RBAR register.
1023              */
1024             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1025             if (aliasno) {
1026                 region = deposit32(region, 0, 2, aliasno);
1027             }
1028             if (region >= cpu->pmsav7_dregion) {
1029                 return 0;
1030             }
1031             return cpu->env.pmsav8.rbar[attrs.secure][region];
1032         }
1033 
1034         if (region >= cpu->pmsav7_dregion) {
1035             return 0;
1036         }
1037         return (cpu->env.pmsav7.drbar[region] & ~0x1f) | (region & 0xf);
1038     }
1039     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
1040     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
1041     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
1042     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
1043     {
1044         int region = cpu->env.pmsav7.rnr[attrs.secure];
1045 
1046         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1047             /* PMSAv8M handling of the aliases is different from v7M:
1048              * aliases A1, A2, A3 override the low two bits of the region
1049              * number in MPU_RNR.
1050              */
1051             int aliasno = (offset - 0xda0) / 8; /* 0..3 */
1052             if (aliasno) {
1053                 region = deposit32(region, 0, 2, aliasno);
1054             }
1055             if (region >= cpu->pmsav7_dregion) {
1056                 return 0;
1057             }
1058             return cpu->env.pmsav8.rlar[attrs.secure][region];
1059         }
1060 
1061         if (region >= cpu->pmsav7_dregion) {
1062             return 0;
1063         }
1064         return ((cpu->env.pmsav7.dracr[region] & 0xffff) << 16) |
1065             (cpu->env.pmsav7.drsr[region] & 0xffff);
1066     }
1067     case 0xdc0: /* MPU_MAIR0 */
1068         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1069             goto bad_offset;
1070         }
1071         return cpu->env.pmsav8.mair0[attrs.secure];
1072     case 0xdc4: /* MPU_MAIR1 */
1073         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1074             goto bad_offset;
1075         }
1076         return cpu->env.pmsav8.mair1[attrs.secure];
1077     case 0xdd0: /* SAU_CTRL */
1078         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1079             goto bad_offset;
1080         }
1081         if (!attrs.secure) {
1082             return 0;
1083         }
1084         return cpu->env.sau.ctrl;
1085     case 0xdd4: /* SAU_TYPE */
1086         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1087             goto bad_offset;
1088         }
1089         if (!attrs.secure) {
1090             return 0;
1091         }
1092         return cpu->sau_sregion;
1093     case 0xdd8: /* SAU_RNR */
1094         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1095             goto bad_offset;
1096         }
1097         if (!attrs.secure) {
1098             return 0;
1099         }
1100         return cpu->env.sau.rnr;
1101     case 0xddc: /* SAU_RBAR */
1102     {
1103         int region = cpu->env.sau.rnr;
1104 
1105         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1106             goto bad_offset;
1107         }
1108         if (!attrs.secure) {
1109             return 0;
1110         }
1111         if (region >= cpu->sau_sregion) {
1112             return 0;
1113         }
1114         return cpu->env.sau.rbar[region];
1115     }
1116     case 0xde0: /* SAU_RLAR */
1117     {
1118         int region = cpu->env.sau.rnr;
1119 
1120         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1121             goto bad_offset;
1122         }
1123         if (!attrs.secure) {
1124             return 0;
1125         }
1126         if (region >= cpu->sau_sregion) {
1127             return 0;
1128         }
1129         return cpu->env.sau.rlar[region];
1130     }
1131     case 0xde4: /* SFSR */
1132         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1133             goto bad_offset;
1134         }
1135         if (!attrs.secure) {
1136             return 0;
1137         }
1138         return cpu->env.v7m.sfsr;
1139     case 0xde8: /* SFAR */
1140         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1141             goto bad_offset;
1142         }
1143         if (!attrs.secure) {
1144             return 0;
1145         }
1146         return cpu->env.v7m.sfar;
1147     default:
1148     bad_offset:
1149         qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);
1150         return 0;
1151     }
1152 }
1153 
1154 static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value,
1155                         MemTxAttrs attrs)
1156 {
1157     ARMCPU *cpu = s->cpu;
1158 
1159     switch (offset) {
1160     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
1161     {
1162         int startvec = 8 * (offset - 0x380) + NVIC_FIRST_IRQ;
1163         int i;
1164 
1165         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1166             goto bad_offset;
1167         }
1168         if (!attrs.secure) {
1169             break;
1170         }
1171         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
1172             s->itns[startvec + i] = (value >> i) & 1;
1173         }
1174         nvic_irq_update(s);
1175         break;
1176     }
1177     case 0xd04: /* Interrupt Control State (ICSR) */
1178         if (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
1179             if (value & (1 << 31)) {
1180                 armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI, false);
1181             } else if (value & (1 << 30) &&
1182                        arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1183                 /* PENDNMICLR didn't exist in v7M */
1184                 armv7m_nvic_clear_pending(s, ARMV7M_EXCP_NMI, false);
1185             }
1186         }
1187         if (value & (1 << 28)) {
1188             armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
1189         } else if (value & (1 << 27)) {
1190             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
1191         }
1192         if (value & (1 << 26)) {
1193             armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
1194         } else if (value & (1 << 25)) {
1195             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
1196         }
1197         break;
1198     case 0xd08: /* Vector Table Offset.  */
1199         cpu->env.v7m.vecbase[attrs.secure] = value & 0xffffff80;
1200         break;
1201     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
1202         if ((value >> R_V7M_AIRCR_VECTKEY_SHIFT) == 0x05fa) {
1203             if (value & R_V7M_AIRCR_SYSRESETREQ_MASK) {
1204                 if (attrs.secure ||
1205                     !(cpu->env.v7m.aircr & R_V7M_AIRCR_SYSRESETREQS_MASK)) {
1206                     qemu_irq_pulse(s->sysresetreq);
1207                 }
1208             }
1209             if (value & R_V7M_AIRCR_VECTCLRACTIVE_MASK) {
1210                 qemu_log_mask(LOG_GUEST_ERROR,
1211                               "Setting VECTCLRACTIVE when not in DEBUG mode "
1212                               "is UNPREDICTABLE\n");
1213             }
1214             if (value & R_V7M_AIRCR_VECTRESET_MASK) {
1215                 /* NB: this bit is RES0 in v8M */
1216                 qemu_log_mask(LOG_GUEST_ERROR,
1217                               "Setting VECTRESET when not in DEBUG mode "
1218                               "is UNPREDICTABLE\n");
1219             }
1220             s->prigroup[attrs.secure] = extract32(value,
1221                                                   R_V7M_AIRCR_PRIGROUP_SHIFT,
1222                                                   R_V7M_AIRCR_PRIGROUP_LENGTH);
1223             if (attrs.secure) {
1224                 /* These bits are only writable by secure */
1225                 cpu->env.v7m.aircr = value &
1226                     (R_V7M_AIRCR_SYSRESETREQS_MASK |
1227                      R_V7M_AIRCR_BFHFNMINS_MASK |
1228                      R_V7M_AIRCR_PRIS_MASK);
1229                 /* BFHFNMINS changes the priority of Secure HardFault, and
1230                  * allows a pending Non-secure HardFault to preempt (which
1231                  * we implement by marking it enabled).
1232                  */
1233                 if (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
1234                     s->sec_vectors[ARMV7M_EXCP_HARD].prio = -3;
1235                     s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
1236                 } else {
1237                     s->sec_vectors[ARMV7M_EXCP_HARD].prio = -1;
1238                     s->vectors[ARMV7M_EXCP_HARD].enabled = 0;
1239                 }
1240             }
1241             nvic_irq_update(s);
1242         }
1243         break;
1244     case 0xd10: /* System Control.  */
1245         /* TODO: Implement control registers.  */
1246         qemu_log_mask(LOG_UNIMP, "NVIC: SCR unimplemented\n");
1247         break;
1248     case 0xd14: /* Configuration Control.  */
1249         /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */
1250         value &= (R_V7M_CCR_STKALIGN_MASK |
1251                   R_V7M_CCR_BFHFNMIGN_MASK |
1252                   R_V7M_CCR_DIV_0_TRP_MASK |
1253                   R_V7M_CCR_UNALIGN_TRP_MASK |
1254                   R_V7M_CCR_USERSETMPEND_MASK |
1255                   R_V7M_CCR_NONBASETHRDENA_MASK);
1256 
1257         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1258             /* v8M makes NONBASETHRDENA and STKALIGN be RES1 */
1259             value |= R_V7M_CCR_NONBASETHRDENA_MASK
1260                 | R_V7M_CCR_STKALIGN_MASK;
1261         }
1262         if (attrs.secure) {
1263             /* the BFHFNMIGN bit is not banked; keep that in the NS copy */
1264             cpu->env.v7m.ccr[M_REG_NS] =
1265                 (cpu->env.v7m.ccr[M_REG_NS] & ~R_V7M_CCR_BFHFNMIGN_MASK)
1266                 | (value & R_V7M_CCR_BFHFNMIGN_MASK);
1267             value &= ~R_V7M_CCR_BFHFNMIGN_MASK;
1268         }
1269 
1270         cpu->env.v7m.ccr[attrs.secure] = value;
1271         break;
1272     case 0xd24: /* System Handler Control and State (SHCSR) */
1273         if (attrs.secure) {
1274             s->sec_vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
1275             /* Secure HardFault active bit cannot be written */
1276             s->sec_vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
1277             s->sec_vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
1278             s->sec_vectors[ARMV7M_EXCP_PENDSV].active =
1279                 (value & (1 << 10)) != 0;
1280             s->sec_vectors[ARMV7M_EXCP_SYSTICK].active =
1281                 (value & (1 << 11)) != 0;
1282             s->sec_vectors[ARMV7M_EXCP_USAGE].pending =
1283                 (value & (1 << 12)) != 0;
1284             s->sec_vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
1285             s->sec_vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
1286             s->sec_vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
1287             s->sec_vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
1288             s->sec_vectors[ARMV7M_EXCP_USAGE].enabled =
1289                 (value & (1 << 18)) != 0;
1290             s->sec_vectors[ARMV7M_EXCP_HARD].pending = (value & (1 << 21)) != 0;
1291             /* SecureFault not banked, but RAZ/WI to NS */
1292             s->vectors[ARMV7M_EXCP_SECURE].active = (value & (1 << 4)) != 0;
1293             s->vectors[ARMV7M_EXCP_SECURE].enabled = (value & (1 << 19)) != 0;
1294             s->vectors[ARMV7M_EXCP_SECURE].pending = (value & (1 << 20)) != 0;
1295         } else {
1296             s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
1297             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1298                 /* HARDFAULTPENDED is not present in v7M */
1299                 s->vectors[ARMV7M_EXCP_HARD].pending = (value & (1 << 21)) != 0;
1300             }
1301             s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
1302             s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
1303             s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;
1304             s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;
1305             s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;
1306             s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
1307             s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
1308             s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
1309             s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;
1310         }
1311         if (attrs.secure || (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1312             s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;
1313             s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;
1314             s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
1315         }
1316         /* NMIACT can only be written if the write is of a zero, with
1317          * BFHFNMINS 1, and by the CPU in secure state via the NS alias.
1318          */
1319         if (!attrs.secure && cpu->env.v7m.secure &&
1320             (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) &&
1321             (value & (1 << 5)) == 0) {
1322             s->vectors[ARMV7M_EXCP_NMI].active = 0;
1323         }
1324         /* HARDFAULTACT can only be written if the write is of a zero
1325          * to the non-secure HardFault state by the CPU in secure state.
1326          * The only case where we can be targeting the non-secure HF state
1327          * when in secure state is if this is a write via the NS alias
1328          * and BFHFNMINS is 1.
1329          */
1330         if (!attrs.secure && cpu->env.v7m.secure &&
1331             (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) &&
1332             (value & (1 << 2)) == 0) {
1333             s->vectors[ARMV7M_EXCP_HARD].active = 0;
1334         }
1335 
1336         /* TODO: this is RAZ/WI from NS if DEMCR.SDME is set */
1337         s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;
1338         nvic_irq_update(s);
1339         break;
1340     case 0xd2c: /* Hard Fault Status.  */
1341         cpu->env.v7m.hfsr &= ~value; /* W1C */
1342         break;
1343     case 0xd30: /* Debug Fault Status.  */
1344         cpu->env.v7m.dfsr &= ~value; /* W1C */
1345         break;
1346     case 0xd34: /* Mem Manage Address.  */
1347         cpu->env.v7m.mmfar[attrs.secure] = value;
1348         return;
1349     case 0xd38: /* Bus Fault Address.  */
1350         cpu->env.v7m.bfar = value;
1351         return;
1352     case 0xd3c: /* Aux Fault Status.  */
1353         qemu_log_mask(LOG_UNIMP,
1354                       "NVIC: Aux fault status registers unimplemented\n");
1355         break;
1356     case 0xd90: /* MPU_TYPE */
1357         return; /* RO */
1358     case 0xd94: /* MPU_CTRL */
1359         if ((value &
1360              (R_V7M_MPU_CTRL_HFNMIENA_MASK | R_V7M_MPU_CTRL_ENABLE_MASK))
1361             == R_V7M_MPU_CTRL_HFNMIENA_MASK) {
1362             qemu_log_mask(LOG_GUEST_ERROR, "MPU_CTRL: HFNMIENA and !ENABLE is "
1363                           "UNPREDICTABLE\n");
1364         }
1365         cpu->env.v7m.mpu_ctrl[attrs.secure]
1366             = value & (R_V7M_MPU_CTRL_ENABLE_MASK |
1367                        R_V7M_MPU_CTRL_HFNMIENA_MASK |
1368                        R_V7M_MPU_CTRL_PRIVDEFENA_MASK);
1369         tlb_flush(CPU(cpu));
1370         break;
1371     case 0xd98: /* MPU_RNR */
1372         if (value >= cpu->pmsav7_dregion) {
1373             qemu_log_mask(LOG_GUEST_ERROR, "MPU region out of range %"
1374                           PRIu32 "/%" PRIu32 "\n",
1375                           value, cpu->pmsav7_dregion);
1376         } else {
1377             cpu->env.pmsav7.rnr[attrs.secure] = value;
1378         }
1379         break;
1380     case 0xd9c: /* MPU_RBAR */
1381     case 0xda4: /* MPU_RBAR_A1 */
1382     case 0xdac: /* MPU_RBAR_A2 */
1383     case 0xdb4: /* MPU_RBAR_A3 */
1384     {
1385         int region;
1386 
1387         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1388             /* PMSAv8M handling of the aliases is different from v7M:
1389              * aliases A1, A2, A3 override the low two bits of the region
1390              * number in MPU_RNR, and there is no 'region' field in the
1391              * RBAR register.
1392              */
1393             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1394 
1395             region = cpu->env.pmsav7.rnr[attrs.secure];
1396             if (aliasno) {
1397                 region = deposit32(region, 0, 2, aliasno);
1398             }
1399             if (region >= cpu->pmsav7_dregion) {
1400                 return;
1401             }
1402             cpu->env.pmsav8.rbar[attrs.secure][region] = value;
1403             tlb_flush(CPU(cpu));
1404             return;
1405         }
1406 
1407         if (value & (1 << 4)) {
1408             /* VALID bit means use the region number specified in this
1409              * value and also update MPU_RNR.REGION with that value.
1410              */
1411             region = extract32(value, 0, 4);
1412             if (region >= cpu->pmsav7_dregion) {
1413                 qemu_log_mask(LOG_GUEST_ERROR,
1414                               "MPU region out of range %u/%" PRIu32 "\n",
1415                               region, cpu->pmsav7_dregion);
1416                 return;
1417             }
1418             cpu->env.pmsav7.rnr[attrs.secure] = region;
1419         } else {
1420             region = cpu->env.pmsav7.rnr[attrs.secure];
1421         }
1422 
1423         if (region >= cpu->pmsav7_dregion) {
1424             return;
1425         }
1426 
1427         cpu->env.pmsav7.drbar[region] = value & ~0x1f;
1428         tlb_flush(CPU(cpu));
1429         break;
1430     }
1431     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
1432     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
1433     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
1434     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
1435     {
1436         int region = cpu->env.pmsav7.rnr[attrs.secure];
1437 
1438         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1439             /* PMSAv8M handling of the aliases is different from v7M:
1440              * aliases A1, A2, A3 override the low two bits of the region
1441              * number in MPU_RNR.
1442              */
1443             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1444 
1445             region = cpu->env.pmsav7.rnr[attrs.secure];
1446             if (aliasno) {
1447                 region = deposit32(region, 0, 2, aliasno);
1448             }
1449             if (region >= cpu->pmsav7_dregion) {
1450                 return;
1451             }
1452             cpu->env.pmsav8.rlar[attrs.secure][region] = value;
1453             tlb_flush(CPU(cpu));
1454             return;
1455         }
1456 
1457         if (region >= cpu->pmsav7_dregion) {
1458             return;
1459         }
1460 
1461         cpu->env.pmsav7.drsr[region] = value & 0xff3f;
1462         cpu->env.pmsav7.dracr[region] = (value >> 16) & 0x173f;
1463         tlb_flush(CPU(cpu));
1464         break;
1465     }
1466     case 0xdc0: /* MPU_MAIR0 */
1467         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1468             goto bad_offset;
1469         }
1470         if (cpu->pmsav7_dregion) {
1471             /* Register is RES0 if no MPU regions are implemented */
1472             cpu->env.pmsav8.mair0[attrs.secure] = value;
1473         }
1474         /* We don't need to do anything else because memory attributes
1475          * only affect cacheability, and we don't implement caching.
1476          */
1477         break;
1478     case 0xdc4: /* MPU_MAIR1 */
1479         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1480             goto bad_offset;
1481         }
1482         if (cpu->pmsav7_dregion) {
1483             /* Register is RES0 if no MPU regions are implemented */
1484             cpu->env.pmsav8.mair1[attrs.secure] = value;
1485         }
1486         /* We don't need to do anything else because memory attributes
1487          * only affect cacheability, and we don't implement caching.
1488          */
1489         break;
1490     case 0xdd0: /* SAU_CTRL */
1491         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1492             goto bad_offset;
1493         }
1494         if (!attrs.secure) {
1495             return;
1496         }
1497         cpu->env.sau.ctrl = value & 3;
1498         break;
1499     case 0xdd4: /* SAU_TYPE */
1500         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1501             goto bad_offset;
1502         }
1503         break;
1504     case 0xdd8: /* SAU_RNR */
1505         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1506             goto bad_offset;
1507         }
1508         if (!attrs.secure) {
1509             return;
1510         }
1511         if (value >= cpu->sau_sregion) {
1512             qemu_log_mask(LOG_GUEST_ERROR, "SAU region out of range %"
1513                           PRIu32 "/%" PRIu32 "\n",
1514                           value, cpu->sau_sregion);
1515         } else {
1516             cpu->env.sau.rnr = value;
1517         }
1518         break;
1519     case 0xddc: /* SAU_RBAR */
1520     {
1521         int region = cpu->env.sau.rnr;
1522 
1523         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1524             goto bad_offset;
1525         }
1526         if (!attrs.secure) {
1527             return;
1528         }
1529         if (region >= cpu->sau_sregion) {
1530             return;
1531         }
1532         cpu->env.sau.rbar[region] = value & ~0x1f;
1533         tlb_flush(CPU(cpu));
1534         break;
1535     }
1536     case 0xde0: /* SAU_RLAR */
1537     {
1538         int region = cpu->env.sau.rnr;
1539 
1540         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1541             goto bad_offset;
1542         }
1543         if (!attrs.secure) {
1544             return;
1545         }
1546         if (region >= cpu->sau_sregion) {
1547             return;
1548         }
1549         cpu->env.sau.rlar[region] = value & ~0x1c;
1550         tlb_flush(CPU(cpu));
1551         break;
1552     }
1553     case 0xde4: /* SFSR */
1554         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1555             goto bad_offset;
1556         }
1557         if (!attrs.secure) {
1558             return;
1559         }
1560         cpu->env.v7m.sfsr &= ~value; /* W1C */
1561         break;
1562     case 0xde8: /* SFAR */
1563         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1564             goto bad_offset;
1565         }
1566         if (!attrs.secure) {
1567             return;
1568         }
1569         cpu->env.v7m.sfsr = value;
1570         break;
1571     case 0xf00: /* Software Triggered Interrupt Register */
1572     {
1573         int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;
1574         if (excnum < s->num_irq) {
1575             armv7m_nvic_set_pending(s, excnum, false);
1576         }
1577         break;
1578     }
1579     default:
1580     bad_offset:
1581         qemu_log_mask(LOG_GUEST_ERROR,
1582                       "NVIC: Bad write offset 0x%x\n", offset);
1583     }
1584 }
1585 
1586 static bool nvic_user_access_ok(NVICState *s, hwaddr offset, MemTxAttrs attrs)
1587 {
1588     /* Return true if unprivileged access to this register is permitted. */
1589     switch (offset) {
1590     case 0xf00: /* STIR: accessible only if CCR.USERSETMPEND permits */
1591         /* For access via STIR_NS it is the NS CCR.USERSETMPEND that
1592          * controls access even though the CPU is in Secure state (I_QDKX).
1593          */
1594         return s->cpu->env.v7m.ccr[attrs.secure] & R_V7M_CCR_USERSETMPEND_MASK;
1595     default:
1596         /* All other user accesses cause a BusFault unconditionally */
1597         return false;
1598     }
1599 }
1600 
1601 static int shpr_bank(NVICState *s, int exc, MemTxAttrs attrs)
1602 {
1603     /* Behaviour for the SHPR register field for this exception:
1604      * return M_REG_NS to use the nonsecure vector (including for
1605      * non-banked exceptions), M_REG_S for the secure version of
1606      * a banked exception, and -1 if this field should RAZ/WI.
1607      */
1608     switch (exc) {
1609     case ARMV7M_EXCP_MEM:
1610     case ARMV7M_EXCP_USAGE:
1611     case ARMV7M_EXCP_SVC:
1612     case ARMV7M_EXCP_PENDSV:
1613     case ARMV7M_EXCP_SYSTICK:
1614         /* Banked exceptions */
1615         return attrs.secure;
1616     case ARMV7M_EXCP_BUS:
1617         /* Not banked, RAZ/WI from nonsecure if BFHFNMINS is zero */
1618         if (!attrs.secure &&
1619             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1620             return -1;
1621         }
1622         return M_REG_NS;
1623     case ARMV7M_EXCP_SECURE:
1624         /* Not banked, RAZ/WI from nonsecure */
1625         if (!attrs.secure) {
1626             return -1;
1627         }
1628         return M_REG_NS;
1629     case ARMV7M_EXCP_DEBUG:
1630         /* Not banked. TODO should RAZ/WI if DEMCR.SDME is set */
1631         return M_REG_NS;
1632     case 8 ... 10:
1633     case 13:
1634         /* RES0 */
1635         return -1;
1636     default:
1637         /* Not reachable due to decode of SHPR register addresses */
1638         g_assert_not_reached();
1639     }
1640 }
1641 
1642 static MemTxResult nvic_sysreg_read(void *opaque, hwaddr addr,
1643                                     uint64_t *data, unsigned size,
1644                                     MemTxAttrs attrs)
1645 {
1646     NVICState *s = (NVICState *)opaque;
1647     uint32_t offset = addr;
1648     unsigned i, startvec, end;
1649     uint32_t val;
1650 
1651     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
1652         /* Generate BusFault for unprivileged accesses */
1653         return MEMTX_ERROR;
1654     }
1655 
1656     switch (offset) {
1657     /* reads of set and clear both return the status */
1658     case 0x100 ... 0x13f: /* NVIC Set enable */
1659         offset += 0x80;
1660         /* fall through */
1661     case 0x180 ... 0x1bf: /* NVIC Clear enable */
1662         val = 0;
1663         startvec = offset - 0x180 + NVIC_FIRST_IRQ; /* vector # */
1664 
1665         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1666             if (s->vectors[startvec + i].enabled &&
1667                 (attrs.secure || s->itns[startvec + i])) {
1668                 val |= (1 << i);
1669             }
1670         }
1671         break;
1672     case 0x200 ... 0x23f: /* NVIC Set pend */
1673         offset += 0x80;
1674         /* fall through */
1675     case 0x280 ... 0x2bf: /* NVIC Clear pend */
1676         val = 0;
1677         startvec = offset - 0x280 + NVIC_FIRST_IRQ; /* vector # */
1678         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1679             if (s->vectors[startvec + i].pending &&
1680                 (attrs.secure || s->itns[startvec + i])) {
1681                 val |= (1 << i);
1682             }
1683         }
1684         break;
1685     case 0x300 ... 0x33f: /* NVIC Active */
1686         val = 0;
1687         startvec = offset - 0x300 + NVIC_FIRST_IRQ; /* vector # */
1688 
1689         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1690             if (s->vectors[startvec + i].active &&
1691                 (attrs.secure || s->itns[startvec + i])) {
1692                 val |= (1 << i);
1693             }
1694         }
1695         break;
1696     case 0x400 ... 0x5ef: /* NVIC Priority */
1697         val = 0;
1698         startvec = offset - 0x400 + NVIC_FIRST_IRQ; /* vector # */
1699 
1700         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
1701             if (attrs.secure || s->itns[startvec + i]) {
1702                 val |= s->vectors[startvec + i].prio << (8 * i);
1703             }
1704         }
1705         break;
1706     case 0xd18 ... 0xd23: /* System Handler Priority (SHPR1, SHPR2, SHPR3) */
1707         val = 0;
1708         for (i = 0; i < size; i++) {
1709             unsigned hdlidx = (offset - 0xd14) + i;
1710             int sbank = shpr_bank(s, hdlidx, attrs);
1711 
1712             if (sbank < 0) {
1713                 continue;
1714             }
1715             val = deposit32(val, i * 8, 8, get_prio(s, hdlidx, sbank));
1716         }
1717         break;
1718     case 0xd28 ... 0xd2b: /* Configurable Fault Status (CFSR) */
1719         /* The BFSR bits [15:8] are shared between security states
1720          * and we store them in the NS copy
1721          */
1722         val = s->cpu->env.v7m.cfsr[attrs.secure];
1723         val |= s->cpu->env.v7m.cfsr[M_REG_NS] & R_V7M_CFSR_BFSR_MASK;
1724         val = extract32(val, (offset - 0xd28) * 8, size * 8);
1725         break;
1726     case 0xfe0 ... 0xfff: /* ID.  */
1727         if (offset & 3) {
1728             val = 0;
1729         } else {
1730             val = nvic_id[(offset - 0xfe0) >> 2];
1731         }
1732         break;
1733     default:
1734         if (size == 4) {
1735             val = nvic_readl(s, offset, attrs);
1736         } else {
1737             qemu_log_mask(LOG_GUEST_ERROR,
1738                           "NVIC: Bad read of size %d at offset 0x%x\n",
1739                           size, offset);
1740             val = 0;
1741         }
1742     }
1743 
1744     trace_nvic_sysreg_read(addr, val, size);
1745     *data = val;
1746     return MEMTX_OK;
1747 }
1748 
1749 static MemTxResult nvic_sysreg_write(void *opaque, hwaddr addr,
1750                                      uint64_t value, unsigned size,
1751                                      MemTxAttrs attrs)
1752 {
1753     NVICState *s = (NVICState *)opaque;
1754     uint32_t offset = addr;
1755     unsigned i, startvec, end;
1756     unsigned setval = 0;
1757 
1758     trace_nvic_sysreg_write(addr, value, size);
1759 
1760     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
1761         /* Generate BusFault for unprivileged accesses */
1762         return MEMTX_ERROR;
1763     }
1764 
1765     switch (offset) {
1766     case 0x100 ... 0x13f: /* NVIC Set enable */
1767         offset += 0x80;
1768         setval = 1;
1769         /* fall through */
1770     case 0x180 ... 0x1bf: /* NVIC Clear enable */
1771         startvec = 8 * (offset - 0x180) + NVIC_FIRST_IRQ;
1772 
1773         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1774             if (value & (1 << i) &&
1775                 (attrs.secure || s->itns[startvec + i])) {
1776                 s->vectors[startvec + i].enabled = setval;
1777             }
1778         }
1779         nvic_irq_update(s);
1780         return MEMTX_OK;
1781     case 0x200 ... 0x23f: /* NVIC Set pend */
1782         /* the special logic in armv7m_nvic_set_pending()
1783          * is not needed since IRQs are never escalated
1784          */
1785         offset += 0x80;
1786         setval = 1;
1787         /* fall through */
1788     case 0x280 ... 0x2bf: /* NVIC Clear pend */
1789         startvec = 8 * (offset - 0x280) + NVIC_FIRST_IRQ; /* vector # */
1790 
1791         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
1792             if (value & (1 << i) &&
1793                 (attrs.secure || s->itns[startvec + i])) {
1794                 s->vectors[startvec + i].pending = setval;
1795             }
1796         }
1797         nvic_irq_update(s);
1798         return MEMTX_OK;
1799     case 0x300 ... 0x33f: /* NVIC Active */
1800         return MEMTX_OK; /* R/O */
1801     case 0x400 ... 0x5ef: /* NVIC Priority */
1802         startvec = 8 * (offset - 0x400) + NVIC_FIRST_IRQ; /* vector # */
1803 
1804         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
1805             if (attrs.secure || s->itns[startvec + i]) {
1806                 set_prio(s, startvec + i, false, (value >> (i * 8)) & 0xff);
1807             }
1808         }
1809         nvic_irq_update(s);
1810         return MEMTX_OK;
1811     case 0xd18 ... 0xd23: /* System Handler Priority (SHPR1, SHPR2, SHPR3) */
1812         for (i = 0; i < size; i++) {
1813             unsigned hdlidx = (offset - 0xd14) + i;
1814             int newprio = extract32(value, i * 8, 8);
1815             int sbank = shpr_bank(s, hdlidx, attrs);
1816 
1817             if (sbank < 0) {
1818                 continue;
1819             }
1820             set_prio(s, hdlidx, sbank, newprio);
1821         }
1822         nvic_irq_update(s);
1823         return MEMTX_OK;
1824     case 0xd28 ... 0xd2b: /* Configurable Fault Status (CFSR) */
1825         /* All bits are W1C, so construct 32 bit value with 0s in
1826          * the parts not written by the access size
1827          */
1828         value <<= ((offset - 0xd28) * 8);
1829 
1830         s->cpu->env.v7m.cfsr[attrs.secure] &= ~value;
1831         if (attrs.secure) {
1832             /* The BFSR bits [15:8] are shared between security states
1833              * and we store them in the NS copy.
1834              */
1835             s->cpu->env.v7m.cfsr[M_REG_NS] &= ~(value & R_V7M_CFSR_BFSR_MASK);
1836         }
1837         return MEMTX_OK;
1838     }
1839     if (size == 4) {
1840         nvic_writel(s, offset, value, attrs);
1841         return MEMTX_OK;
1842     }
1843     qemu_log_mask(LOG_GUEST_ERROR,
1844                   "NVIC: Bad write of size %d at offset 0x%x\n", size, offset);
1845     /* This is UNPREDICTABLE; treat as RAZ/WI */
1846     return MEMTX_OK;
1847 }
1848 
1849 static const MemoryRegionOps nvic_sysreg_ops = {
1850     .read_with_attrs = nvic_sysreg_read,
1851     .write_with_attrs = nvic_sysreg_write,
1852     .endianness = DEVICE_NATIVE_ENDIAN,
1853 };
1854 
1855 static MemTxResult nvic_sysreg_ns_write(void *opaque, hwaddr addr,
1856                                         uint64_t value, unsigned size,
1857                                         MemTxAttrs attrs)
1858 {
1859     MemoryRegion *mr = opaque;
1860 
1861     if (attrs.secure) {
1862         /* S accesses to the alias act like NS accesses to the real region */
1863         attrs.secure = 0;
1864         return memory_region_dispatch_write(mr, addr, value, size, attrs);
1865     } else {
1866         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
1867         if (attrs.user) {
1868             return MEMTX_ERROR;
1869         }
1870         return MEMTX_OK;
1871     }
1872 }
1873 
1874 static MemTxResult nvic_sysreg_ns_read(void *opaque, hwaddr addr,
1875                                        uint64_t *data, unsigned size,
1876                                        MemTxAttrs attrs)
1877 {
1878     MemoryRegion *mr = opaque;
1879 
1880     if (attrs.secure) {
1881         /* S accesses to the alias act like NS accesses to the real region */
1882         attrs.secure = 0;
1883         return memory_region_dispatch_read(mr, addr, data, size, attrs);
1884     } else {
1885         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
1886         if (attrs.user) {
1887             return MEMTX_ERROR;
1888         }
1889         *data = 0;
1890         return MEMTX_OK;
1891     }
1892 }
1893 
1894 static const MemoryRegionOps nvic_sysreg_ns_ops = {
1895     .read_with_attrs = nvic_sysreg_ns_read,
1896     .write_with_attrs = nvic_sysreg_ns_write,
1897     .endianness = DEVICE_NATIVE_ENDIAN,
1898 };
1899 
1900 static MemTxResult nvic_systick_write(void *opaque, hwaddr addr,
1901                                       uint64_t value, unsigned size,
1902                                       MemTxAttrs attrs)
1903 {
1904     NVICState *s = opaque;
1905     MemoryRegion *mr;
1906 
1907     /* Direct the access to the correct systick */
1908     mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->systick[attrs.secure]), 0);
1909     return memory_region_dispatch_write(mr, addr, value, size, attrs);
1910 }
1911 
1912 static MemTxResult nvic_systick_read(void *opaque, hwaddr addr,
1913                                      uint64_t *data, unsigned size,
1914                                      MemTxAttrs attrs)
1915 {
1916     NVICState *s = opaque;
1917     MemoryRegion *mr;
1918 
1919     /* Direct the access to the correct systick */
1920     mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->systick[attrs.secure]), 0);
1921     return memory_region_dispatch_read(mr, addr, data, size, attrs);
1922 }
1923 
1924 static const MemoryRegionOps nvic_systick_ops = {
1925     .read_with_attrs = nvic_systick_read,
1926     .write_with_attrs = nvic_systick_write,
1927     .endianness = DEVICE_NATIVE_ENDIAN,
1928 };
1929 
1930 static int nvic_post_load(void *opaque, int version_id)
1931 {
1932     NVICState *s = opaque;
1933     unsigned i;
1934     int resetprio;
1935 
1936     /* Check for out of range priority settings */
1937     resetprio = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? -4 : -3;
1938 
1939     if (s->vectors[ARMV7M_EXCP_RESET].prio != resetprio ||
1940         s->vectors[ARMV7M_EXCP_NMI].prio != -2 ||
1941         s->vectors[ARMV7M_EXCP_HARD].prio != -1) {
1942         return 1;
1943     }
1944     for (i = ARMV7M_EXCP_MEM; i < s->num_irq; i++) {
1945         if (s->vectors[i].prio & ~0xff) {
1946             return 1;
1947         }
1948     }
1949 
1950     nvic_recompute_state(s);
1951 
1952     return 0;
1953 }
1954 
1955 static const VMStateDescription vmstate_VecInfo = {
1956     .name = "armv7m_nvic_info",
1957     .version_id = 1,
1958     .minimum_version_id = 1,
1959     .fields = (VMStateField[]) {
1960         VMSTATE_INT16(prio, VecInfo),
1961         VMSTATE_UINT8(enabled, VecInfo),
1962         VMSTATE_UINT8(pending, VecInfo),
1963         VMSTATE_UINT8(active, VecInfo),
1964         VMSTATE_UINT8(level, VecInfo),
1965         VMSTATE_END_OF_LIST()
1966     }
1967 };
1968 
1969 static bool nvic_security_needed(void *opaque)
1970 {
1971     NVICState *s = opaque;
1972 
1973     return arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY);
1974 }
1975 
1976 static int nvic_security_post_load(void *opaque, int version_id)
1977 {
1978     NVICState *s = opaque;
1979     int i;
1980 
1981     /* Check for out of range priority settings */
1982     if (s->sec_vectors[ARMV7M_EXCP_HARD].prio != -1
1983         && s->sec_vectors[ARMV7M_EXCP_HARD].prio != -3) {
1984         /* We can't cross-check against AIRCR.BFHFNMINS as we don't know
1985          * if the CPU state has been migrated yet; a mismatch won't
1986          * cause the emulation to blow up, though.
1987          */
1988         return 1;
1989     }
1990     for (i = ARMV7M_EXCP_MEM; i < ARRAY_SIZE(s->sec_vectors); i++) {
1991         if (s->sec_vectors[i].prio & ~0xff) {
1992             return 1;
1993         }
1994     }
1995     return 0;
1996 }
1997 
1998 static const VMStateDescription vmstate_nvic_security = {
1999     .name = "nvic/m-security",
2000     .version_id = 1,
2001     .minimum_version_id = 1,
2002     .needed = nvic_security_needed,
2003     .post_load = &nvic_security_post_load,
2004     .fields = (VMStateField[]) {
2005         VMSTATE_STRUCT_ARRAY(sec_vectors, NVICState, NVIC_INTERNAL_VECTORS, 1,
2006                              vmstate_VecInfo, VecInfo),
2007         VMSTATE_UINT32(prigroup[M_REG_S], NVICState),
2008         VMSTATE_BOOL_ARRAY(itns, NVICState, NVIC_MAX_VECTORS),
2009         VMSTATE_END_OF_LIST()
2010     }
2011 };
2012 
2013 static const VMStateDescription vmstate_nvic = {
2014     .name = "armv7m_nvic",
2015     .version_id = 4,
2016     .minimum_version_id = 4,
2017     .post_load = &nvic_post_load,
2018     .fields = (VMStateField[]) {
2019         VMSTATE_STRUCT_ARRAY(vectors, NVICState, NVIC_MAX_VECTORS, 1,
2020                              vmstate_VecInfo, VecInfo),
2021         VMSTATE_UINT32(prigroup[M_REG_NS], NVICState),
2022         VMSTATE_END_OF_LIST()
2023     },
2024     .subsections = (const VMStateDescription*[]) {
2025         &vmstate_nvic_security,
2026         NULL
2027     }
2028 };
2029 
2030 static Property props_nvic[] = {
2031     /* Number of external IRQ lines (so excluding the 16 internal exceptions) */
2032     DEFINE_PROP_UINT32("num-irq", NVICState, num_irq, 64),
2033     DEFINE_PROP_END_OF_LIST()
2034 };
2035 
2036 static void armv7m_nvic_reset(DeviceState *dev)
2037 {
2038     int resetprio;
2039     NVICState *s = NVIC(dev);
2040 
2041     memset(s->vectors, 0, sizeof(s->vectors));
2042     memset(s->sec_vectors, 0, sizeof(s->sec_vectors));
2043     s->prigroup[M_REG_NS] = 0;
2044     s->prigroup[M_REG_S] = 0;
2045 
2046     s->vectors[ARMV7M_EXCP_NMI].enabled = 1;
2047     /* MEM, BUS, and USAGE are enabled through
2048      * the System Handler Control register
2049      */
2050     s->vectors[ARMV7M_EXCP_SVC].enabled = 1;
2051     s->vectors[ARMV7M_EXCP_DEBUG].enabled = 1;
2052     s->vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
2053     s->vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
2054 
2055     resetprio = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? -4 : -3;
2056     s->vectors[ARMV7M_EXCP_RESET].prio = resetprio;
2057     s->vectors[ARMV7M_EXCP_NMI].prio = -2;
2058     s->vectors[ARMV7M_EXCP_HARD].prio = -1;
2059 
2060     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
2061         s->sec_vectors[ARMV7M_EXCP_HARD].enabled = 1;
2062         s->sec_vectors[ARMV7M_EXCP_SVC].enabled = 1;
2063         s->sec_vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
2064         s->sec_vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
2065 
2066         /* AIRCR.BFHFNMINS resets to 0 so Secure HF is priority -1 (R_CMTC) */
2067         s->sec_vectors[ARMV7M_EXCP_HARD].prio = -1;
2068         /* If AIRCR.BFHFNMINS is 0 then NS HF is (effectively) disabled */
2069         s->vectors[ARMV7M_EXCP_HARD].enabled = 0;
2070     } else {
2071         s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
2072     }
2073 
2074     /* Strictly speaking the reset handler should be enabled.
2075      * However, we don't simulate soft resets through the NVIC,
2076      * and the reset vector should never be pended.
2077      * So we leave it disabled to catch logic errors.
2078      */
2079 
2080     s->exception_prio = NVIC_NOEXC_PRIO;
2081     s->vectpending = 0;
2082     s->vectpending_is_s_banked = false;
2083     s->vectpending_prio = NVIC_NOEXC_PRIO;
2084 
2085     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
2086         memset(s->itns, 0, sizeof(s->itns));
2087     } else {
2088         /* This state is constant and not guest accessible in a non-security
2089          * NVIC; we set the bits to true to avoid having to do a feature
2090          * bit check in the NVIC enable/pend/etc register accessors.
2091          */
2092         int i;
2093 
2094         for (i = NVIC_FIRST_IRQ; i < ARRAY_SIZE(s->itns); i++) {
2095             s->itns[i] = true;
2096         }
2097     }
2098 }
2099 
2100 static void nvic_systick_trigger(void *opaque, int n, int level)
2101 {
2102     NVICState *s = opaque;
2103 
2104     if (level) {
2105         /* SysTick just asked us to pend its exception.
2106          * (This is different from an external interrupt line's
2107          * behaviour.)
2108          * n == 0 : NonSecure systick
2109          * n == 1 : Secure systick
2110          */
2111         armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, n);
2112     }
2113 }
2114 
2115 static void armv7m_nvic_realize(DeviceState *dev, Error **errp)
2116 {
2117     NVICState *s = NVIC(dev);
2118     Error *err = NULL;
2119     int regionlen;
2120 
2121     s->cpu = ARM_CPU(qemu_get_cpu(0));
2122     assert(s->cpu);
2123 
2124     if (s->num_irq > NVIC_MAX_IRQ) {
2125         error_setg(errp, "num-irq %d exceeds NVIC maximum", s->num_irq);
2126         return;
2127     }
2128 
2129     qdev_init_gpio_in(dev, set_irq_level, s->num_irq);
2130 
2131     /* include space for internal exception vectors */
2132     s->num_irq += NVIC_FIRST_IRQ;
2133 
2134     object_property_set_bool(OBJECT(&s->systick[M_REG_NS]), true,
2135                              "realized", &err);
2136     if (err != NULL) {
2137         error_propagate(errp, err);
2138         return;
2139     }
2140     sysbus_connect_irq(SYS_BUS_DEVICE(&s->systick[M_REG_NS]), 0,
2141                        qdev_get_gpio_in_named(dev, "systick-trigger",
2142                                               M_REG_NS));
2143 
2144     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
2145         /* We couldn't init the secure systick device in instance_init
2146          * as we didn't know then if the CPU had the security extensions;
2147          * so we have to do it here.
2148          */
2149         object_initialize(&s->systick[M_REG_S], sizeof(s->systick[M_REG_S]),
2150                           TYPE_SYSTICK);
2151         qdev_set_parent_bus(DEVICE(&s->systick[M_REG_S]), sysbus_get_default());
2152 
2153         object_property_set_bool(OBJECT(&s->systick[M_REG_S]), true,
2154                                  "realized", &err);
2155         if (err != NULL) {
2156             error_propagate(errp, err);
2157             return;
2158         }
2159         sysbus_connect_irq(SYS_BUS_DEVICE(&s->systick[M_REG_S]), 0,
2160                            qdev_get_gpio_in_named(dev, "systick-trigger",
2161                                                   M_REG_S));
2162     }
2163 
2164     /* The NVIC and System Control Space (SCS) starts at 0xe000e000
2165      * and looks like this:
2166      *  0x004 - ICTR
2167      *  0x010 - 0xff - systick
2168      *  0x100..0x7ec - NVIC
2169      *  0x7f0..0xcff - Reserved
2170      *  0xd00..0xd3c - SCS registers
2171      *  0xd40..0xeff - Reserved or Not implemented
2172      *  0xf00 - STIR
2173      *
2174      * Some registers within this space are banked between security states.
2175      * In v8M there is a second range 0xe002e000..0xe002efff which is the
2176      * NonSecure alias SCS; secure accesses to this behave like NS accesses
2177      * to the main SCS range, and non-secure accesses (including when
2178      * the security extension is not implemented) are RAZ/WI.
2179      * Note that both the main SCS range and the alias range are defined
2180      * to be exempt from memory attribution (R_BLJT) and so the memory
2181      * transaction attribute always matches the current CPU security
2182      * state (attrs.secure == env->v7m.secure). In the nvic_sysreg_ns_ops
2183      * wrappers we change attrs.secure to indicate the NS access; so
2184      * generally code determining which banked register to use should
2185      * use attrs.secure; code determining actual behaviour of the system
2186      * should use env->v7m.secure.
2187      */
2188     regionlen = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? 0x21000 : 0x1000;
2189     memory_region_init(&s->container, OBJECT(s), "nvic", regionlen);
2190     /* The system register region goes at the bottom of the priority
2191      * stack as it covers the whole page.
2192      */
2193     memory_region_init_io(&s->sysregmem, OBJECT(s), &nvic_sysreg_ops, s,
2194                           "nvic_sysregs", 0x1000);
2195     memory_region_add_subregion(&s->container, 0, &s->sysregmem);
2196 
2197     memory_region_init_io(&s->systickmem, OBJECT(s),
2198                           &nvic_systick_ops, s,
2199                           "nvic_systick", 0xe0);
2200 
2201     memory_region_add_subregion_overlap(&s->container, 0x10,
2202                                         &s->systickmem, 1);
2203 
2204     if (arm_feature(&s->cpu->env, ARM_FEATURE_V8)) {
2205         memory_region_init_io(&s->sysreg_ns_mem, OBJECT(s),
2206                               &nvic_sysreg_ns_ops, &s->sysregmem,
2207                               "nvic_sysregs_ns", 0x1000);
2208         memory_region_add_subregion(&s->container, 0x20000, &s->sysreg_ns_mem);
2209         memory_region_init_io(&s->systick_ns_mem, OBJECT(s),
2210                               &nvic_sysreg_ns_ops, &s->systickmem,
2211                               "nvic_systick_ns", 0xe0);
2212         memory_region_add_subregion_overlap(&s->container, 0x20010,
2213                                             &s->systick_ns_mem, 1);
2214     }
2215 
2216     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->container);
2217 }
2218 
2219 static void armv7m_nvic_instance_init(Object *obj)
2220 {
2221     /* We have a different default value for the num-irq property
2222      * than our superclass. This function runs after qdev init
2223      * has set the defaults from the Property array and before
2224      * any user-specified property setting, so just modify the
2225      * value in the GICState struct.
2226      */
2227     DeviceState *dev = DEVICE(obj);
2228     NVICState *nvic = NVIC(obj);
2229     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
2230 
2231     object_initialize(&nvic->systick[M_REG_NS],
2232                       sizeof(nvic->systick[M_REG_NS]), TYPE_SYSTICK);
2233     qdev_set_parent_bus(DEVICE(&nvic->systick[M_REG_NS]), sysbus_get_default());
2234     /* We can't initialize the secure systick here, as we don't know
2235      * yet if we need it.
2236      */
2237 
2238     sysbus_init_irq(sbd, &nvic->excpout);
2239     qdev_init_gpio_out_named(dev, &nvic->sysresetreq, "SYSRESETREQ", 1);
2240     qdev_init_gpio_in_named(dev, nvic_systick_trigger, "systick-trigger",
2241                             M_REG_NUM_BANKS);
2242 }
2243 
2244 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
2245 {
2246     DeviceClass *dc = DEVICE_CLASS(klass);
2247 
2248     dc->vmsd  = &vmstate_nvic;
2249     dc->props = props_nvic;
2250     dc->reset = armv7m_nvic_reset;
2251     dc->realize = armv7m_nvic_realize;
2252 }
2253 
2254 static const TypeInfo armv7m_nvic_info = {
2255     .name          = TYPE_NVIC,
2256     .parent        = TYPE_SYS_BUS_DEVICE,
2257     .instance_init = armv7m_nvic_instance_init,
2258     .instance_size = sizeof(NVICState),
2259     .class_init    = armv7m_nvic_class_init,
2260     .class_size    = sizeof(SysBusDeviceClass),
2261 };
2262 
2263 static void armv7m_nvic_register_types(void)
2264 {
2265     type_register_static(&armv7m_nvic_info);
2266 }
2267 
2268 type_init(armv7m_nvic_register_types)
2269