xref: /openbmc/qemu/hw/intc/armv7m_nvic.c (revision 59a3a1c0)
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 "cpu.h"
16 #include "hw/sysbus.h"
17 #include "migration/vmstate.h"
18 #include "qemu/timer.h"
19 #include "hw/intc/armv7m_nvic.h"
20 #include "hw/irq.h"
21 #include "hw/qdev-properties.h"
22 #include "target/arm/cpu.h"
23 #include "exec/exec-all.h"
24 #include "qemu/log.h"
25 #include "qemu/module.h"
26 #include "trace.h"
27 
28 /* IRQ number counting:
29  *
30  * the num-irq property counts the number of external IRQ lines
31  *
32  * NVICState::num_irq counts the total number of exceptions
33  * (external IRQs, the 15 internal exceptions including reset,
34  * and one for the unused exception number 0).
35  *
36  * NVIC_MAX_IRQ is the highest permitted number of external IRQ lines.
37  *
38  * NVIC_MAX_VECTORS is the highest permitted number of exceptions.
39  *
40  * Iterating through all exceptions should typically be done with
41  * for (i = 1; i < s->num_irq; i++) to avoid the unused slot 0.
42  *
43  * The external qemu_irq lines are the NVIC's external IRQ lines,
44  * so line 0 is exception 16.
45  *
46  * In the terminology of the architecture manual, "interrupts" are
47  * a subcategory of exception referring to the external interrupts
48  * (which are exception numbers NVIC_FIRST_IRQ and upward).
49  * For historical reasons QEMU tends to use "interrupt" and
50  * "exception" more or less interchangeably.
51  */
52 #define NVIC_FIRST_IRQ NVIC_INTERNAL_VECTORS
53 #define NVIC_MAX_IRQ (NVIC_MAX_VECTORS - NVIC_FIRST_IRQ)
54 
55 /* Effective running priority of the CPU when no exception is active
56  * (higher than the highest possible priority value)
57  */
58 #define NVIC_NOEXC_PRIO 0x100
59 /* Maximum priority of non-secure exceptions when AIRCR.PRIS is set */
60 #define NVIC_NS_PRIO_LIMIT 0x80
61 
62 static const uint8_t nvic_id[] = {
63     0x00, 0xb0, 0x1b, 0x00, 0x0d, 0xe0, 0x05, 0xb1
64 };
65 
66 static int nvic_pending_prio(NVICState *s)
67 {
68     /* return the group priority of the current pending interrupt,
69      * or NVIC_NOEXC_PRIO if no interrupt is pending
70      */
71     return s->vectpending_prio;
72 }
73 
74 /* Return the value of the ISCR RETTOBASE bit:
75  * 1 if there is exactly one active exception
76  * 0 if there is more than one active exception
77  * UNKNOWN if there are no active exceptions (we choose 1,
78  * which matches the choice Cortex-M3 is documented as making).
79  *
80  * NB: some versions of the documentation talk about this
81  * counting "active exceptions other than the one shown by IPSR";
82  * this is only different in the obscure corner case where guest
83  * code has manually deactivated an exception and is about
84  * to fail an exception-return integrity check. The definition
85  * above is the one from the v8M ARM ARM and is also in line
86  * with the behaviour documented for the Cortex-M3.
87  */
88 static bool nvic_rettobase(NVICState *s)
89 {
90     int irq, nhand = 0;
91     bool check_sec = arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY);
92 
93     for (irq = ARMV7M_EXCP_RESET; irq < s->num_irq; irq++) {
94         if (s->vectors[irq].active ||
95             (check_sec && irq < NVIC_INTERNAL_VECTORS &&
96              s->sec_vectors[irq].active)) {
97             nhand++;
98             if (nhand == 2) {
99                 return 0;
100             }
101         }
102     }
103 
104     return 1;
105 }
106 
107 /* Return the value of the ISCR ISRPENDING bit:
108  * 1 if an external interrupt is pending
109  * 0 if no external interrupt is pending
110  */
111 static bool nvic_isrpending(NVICState *s)
112 {
113     int irq;
114 
115     /* We can shortcut if the highest priority pending interrupt
116      * happens to be external or if there is nothing pending.
117      */
118     if (s->vectpending > NVIC_FIRST_IRQ) {
119         return true;
120     }
121     if (s->vectpending == 0) {
122         return false;
123     }
124 
125     for (irq = NVIC_FIRST_IRQ; irq < s->num_irq; irq++) {
126         if (s->vectors[irq].pending) {
127             return true;
128         }
129     }
130     return false;
131 }
132 
133 static bool exc_is_banked(int exc)
134 {
135     /* Return true if this is one of the limited set of exceptions which
136      * are banked (and thus have state in sec_vectors[])
137      */
138     return exc == ARMV7M_EXCP_HARD ||
139         exc == ARMV7M_EXCP_MEM ||
140         exc == ARMV7M_EXCP_USAGE ||
141         exc == ARMV7M_EXCP_SVC ||
142         exc == ARMV7M_EXCP_PENDSV ||
143         exc == ARMV7M_EXCP_SYSTICK;
144 }
145 
146 /* Return a mask word which clears the subpriority bits from
147  * a priority value for an M-profile exception, leaving only
148  * the group priority.
149  */
150 static inline uint32_t nvic_gprio_mask(NVICState *s, bool secure)
151 {
152     return ~0U << (s->prigroup[secure] + 1);
153 }
154 
155 static bool exc_targets_secure(NVICState *s, int exc)
156 {
157     /* Return true if this non-banked exception targets Secure state. */
158     if (!arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
159         return false;
160     }
161 
162     if (exc >= NVIC_FIRST_IRQ) {
163         return !s->itns[exc];
164     }
165 
166     /* Function shouldn't be called for banked exceptions. */
167     assert(!exc_is_banked(exc));
168 
169     switch (exc) {
170     case ARMV7M_EXCP_NMI:
171     case ARMV7M_EXCP_BUS:
172         return !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
173     case ARMV7M_EXCP_SECURE:
174         return true;
175     case ARMV7M_EXCP_DEBUG:
176         /* TODO: controlled by DEMCR.SDME, which we don't yet implement */
177         return false;
178     default:
179         /* reset, and reserved (unused) low exception numbers.
180          * We'll get called by code that loops through all the exception
181          * numbers, but it doesn't matter what we return here as these
182          * non-existent exceptions will never be pended or active.
183          */
184         return true;
185     }
186 }
187 
188 static int exc_group_prio(NVICState *s, int rawprio, bool targets_secure)
189 {
190     /* Return the group priority for this exception, given its raw
191      * (group-and-subgroup) priority value and whether it is targeting
192      * secure state or not.
193      */
194     if (rawprio < 0) {
195         return rawprio;
196     }
197     rawprio &= nvic_gprio_mask(s, targets_secure);
198     /* AIRCR.PRIS causes us to squash all NS priorities into the
199      * lower half of the total range
200      */
201     if (!targets_secure &&
202         (s->cpu->env.v7m.aircr & R_V7M_AIRCR_PRIS_MASK)) {
203         rawprio = (rawprio >> 1) + NVIC_NS_PRIO_LIMIT;
204     }
205     return rawprio;
206 }
207 
208 /* Recompute vectpending and exception_prio for a CPU which implements
209  * the Security extension
210  */
211 static void nvic_recompute_state_secure(NVICState *s)
212 {
213     int i, bank;
214     int pend_prio = NVIC_NOEXC_PRIO;
215     int active_prio = NVIC_NOEXC_PRIO;
216     int pend_irq = 0;
217     bool pending_is_s_banked = false;
218     int pend_subprio = 0;
219 
220     /* R_CQRV: precedence is by:
221      *  - lowest group priority; if both the same then
222      *  - lowest subpriority; if both the same then
223      *  - lowest exception number; if both the same (ie banked) then
224      *  - secure exception takes precedence
225      * Compare pseudocode RawExecutionPriority.
226      * Annoyingly, now we have two prigroup values (for S and NS)
227      * we can't do the loop comparison on raw priority values.
228      */
229     for (i = 1; i < s->num_irq; i++) {
230         for (bank = M_REG_S; bank >= M_REG_NS; bank--) {
231             VecInfo *vec;
232             int prio, subprio;
233             bool targets_secure;
234 
235             if (bank == M_REG_S) {
236                 if (!exc_is_banked(i)) {
237                     continue;
238                 }
239                 vec = &s->sec_vectors[i];
240                 targets_secure = true;
241             } else {
242                 vec = &s->vectors[i];
243                 targets_secure = !exc_is_banked(i) && exc_targets_secure(s, i);
244             }
245 
246             prio = exc_group_prio(s, vec->prio, targets_secure);
247             subprio = vec->prio & ~nvic_gprio_mask(s, targets_secure);
248             if (vec->enabled && vec->pending &&
249                 ((prio < pend_prio) ||
250                  (prio == pend_prio && prio >= 0 && subprio < pend_subprio))) {
251                 pend_prio = prio;
252                 pend_subprio = subprio;
253                 pend_irq = i;
254                 pending_is_s_banked = (bank == M_REG_S);
255             }
256             if (vec->active && prio < active_prio) {
257                 active_prio = prio;
258             }
259         }
260     }
261 
262     s->vectpending_is_s_banked = pending_is_s_banked;
263     s->vectpending = pend_irq;
264     s->vectpending_prio = pend_prio;
265     s->exception_prio = active_prio;
266 
267     trace_nvic_recompute_state_secure(s->vectpending,
268                                       s->vectpending_is_s_banked,
269                                       s->vectpending_prio,
270                                       s->exception_prio);
271 }
272 
273 /* Recompute vectpending and exception_prio */
274 static void nvic_recompute_state(NVICState *s)
275 {
276     int i;
277     int pend_prio = NVIC_NOEXC_PRIO;
278     int active_prio = NVIC_NOEXC_PRIO;
279     int pend_irq = 0;
280 
281     /* In theory we could write one function that handled both
282      * the "security extension present" and "not present"; however
283      * the security related changes significantly complicate the
284      * recomputation just by themselves and mixing both cases together
285      * would be even worse, so we retain a separate non-secure-only
286      * version for CPUs which don't implement the security extension.
287      */
288     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
289         nvic_recompute_state_secure(s);
290         return;
291     }
292 
293     for (i = 1; i < s->num_irq; i++) {
294         VecInfo *vec = &s->vectors[i];
295 
296         if (vec->enabled && vec->pending && vec->prio < pend_prio) {
297             pend_prio = vec->prio;
298             pend_irq = i;
299         }
300         if (vec->active && vec->prio < active_prio) {
301             active_prio = vec->prio;
302         }
303     }
304 
305     if (active_prio > 0) {
306         active_prio &= nvic_gprio_mask(s, false);
307     }
308 
309     if (pend_prio > 0) {
310         pend_prio &= nvic_gprio_mask(s, false);
311     }
312 
313     s->vectpending = pend_irq;
314     s->vectpending_prio = pend_prio;
315     s->exception_prio = active_prio;
316 
317     trace_nvic_recompute_state(s->vectpending,
318                                s->vectpending_prio,
319                                s->exception_prio);
320 }
321 
322 /* Return the current execution priority of the CPU
323  * (equivalent to the pseudocode ExecutionPriority function).
324  * This is a value between -2 (NMI priority) and NVIC_NOEXC_PRIO.
325  */
326 static inline int nvic_exec_prio(NVICState *s)
327 {
328     CPUARMState *env = &s->cpu->env;
329     int running = NVIC_NOEXC_PRIO;
330 
331     if (env->v7m.basepri[M_REG_NS] > 0) {
332         running = exc_group_prio(s, env->v7m.basepri[M_REG_NS], M_REG_NS);
333     }
334 
335     if (env->v7m.basepri[M_REG_S] > 0) {
336         int basepri = exc_group_prio(s, env->v7m.basepri[M_REG_S], M_REG_S);
337         if (running > basepri) {
338             running = basepri;
339         }
340     }
341 
342     if (env->v7m.primask[M_REG_NS]) {
343         if (env->v7m.aircr & R_V7M_AIRCR_PRIS_MASK) {
344             if (running > NVIC_NS_PRIO_LIMIT) {
345                 running = NVIC_NS_PRIO_LIMIT;
346             }
347         } else {
348             running = 0;
349         }
350     }
351 
352     if (env->v7m.primask[M_REG_S]) {
353         running = 0;
354     }
355 
356     if (env->v7m.faultmask[M_REG_NS]) {
357         if (env->v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
358             running = -1;
359         } else {
360             if (env->v7m.aircr & R_V7M_AIRCR_PRIS_MASK) {
361                 if (running > NVIC_NS_PRIO_LIMIT) {
362                     running = NVIC_NS_PRIO_LIMIT;
363                 }
364             } else {
365                 running = 0;
366             }
367         }
368     }
369 
370     if (env->v7m.faultmask[M_REG_S]) {
371         running = (env->v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) ? -3 : -1;
372     }
373 
374     /* consider priority of active handler */
375     return MIN(running, s->exception_prio);
376 }
377 
378 bool armv7m_nvic_neg_prio_requested(void *opaque, bool secure)
379 {
380     /* Return true if the requested execution priority is negative
381      * for the specified security state, ie that security state
382      * has an active NMI or HardFault or has set its FAULTMASK.
383      * Note that this is not the same as whether the execution
384      * priority is actually negative (for instance AIRCR.PRIS may
385      * mean we don't allow FAULTMASK_NS to actually make the execution
386      * priority negative). Compare pseudocode IsReqExcPriNeg().
387      */
388     NVICState *s = opaque;
389 
390     if (s->cpu->env.v7m.faultmask[secure]) {
391         return true;
392     }
393 
394     if (secure ? s->sec_vectors[ARMV7M_EXCP_HARD].active :
395         s->vectors[ARMV7M_EXCP_HARD].active) {
396         return true;
397     }
398 
399     if (s->vectors[ARMV7M_EXCP_NMI].active &&
400         exc_targets_secure(s, ARMV7M_EXCP_NMI) == secure) {
401         return true;
402     }
403 
404     return false;
405 }
406 
407 bool armv7m_nvic_can_take_pending_exception(void *opaque)
408 {
409     NVICState *s = opaque;
410 
411     return nvic_exec_prio(s) > nvic_pending_prio(s);
412 }
413 
414 int armv7m_nvic_raw_execution_priority(void *opaque)
415 {
416     NVICState *s = opaque;
417 
418     return s->exception_prio;
419 }
420 
421 /* caller must call nvic_irq_update() after this.
422  * secure indicates the bank to use for banked exceptions (we assert if
423  * we are passed secure=true for a non-banked exception).
424  */
425 static void set_prio(NVICState *s, unsigned irq, bool secure, uint8_t prio)
426 {
427     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
428     assert(irq < s->num_irq);
429 
430     prio &= MAKE_64BIT_MASK(8 - s->num_prio_bits, s->num_prio_bits);
431 
432     if (secure) {
433         assert(exc_is_banked(irq));
434         s->sec_vectors[irq].prio = prio;
435     } else {
436         s->vectors[irq].prio = prio;
437     }
438 
439     trace_nvic_set_prio(irq, secure, prio);
440 }
441 
442 /* Return the current raw priority register value.
443  * secure indicates the bank to use for banked exceptions (we assert if
444  * we are passed secure=true for a non-banked exception).
445  */
446 static int get_prio(NVICState *s, unsigned irq, bool secure)
447 {
448     assert(irq > ARMV7M_EXCP_NMI); /* only use for configurable prios */
449     assert(irq < s->num_irq);
450 
451     if (secure) {
452         assert(exc_is_banked(irq));
453         return s->sec_vectors[irq].prio;
454     } else {
455         return s->vectors[irq].prio;
456     }
457 }
458 
459 /* Recompute state and assert irq line accordingly.
460  * Must be called after changes to:
461  *  vec->active, vec->enabled, vec->pending or vec->prio for any vector
462  *  prigroup
463  */
464 static void nvic_irq_update(NVICState *s)
465 {
466     int lvl;
467     int pend_prio;
468 
469     nvic_recompute_state(s);
470     pend_prio = nvic_pending_prio(s);
471 
472     /* Raise NVIC output if this IRQ would be taken, except that we
473      * ignore the effects of the BASEPRI, FAULTMASK and PRIMASK (which
474      * will be checked for in arm_v7m_cpu_exec_interrupt()); changes
475      * to those CPU registers don't cause us to recalculate the NVIC
476      * pending info.
477      */
478     lvl = (pend_prio < s->exception_prio);
479     trace_nvic_irq_update(s->vectpending, pend_prio, s->exception_prio, lvl);
480     qemu_set_irq(s->excpout, lvl);
481 }
482 
483 /**
484  * armv7m_nvic_clear_pending: mark the specified exception as not pending
485  * @opaque: the NVIC
486  * @irq: the exception number to mark as not pending
487  * @secure: false for non-banked exceptions or for the nonsecure
488  * version of a banked exception, true for the secure version of a banked
489  * exception.
490  *
491  * Marks the specified exception as not pending. Note that we will assert()
492  * if @secure is true and @irq does not specify one of the fixed set
493  * of architecturally banked exceptions.
494  */
495 static void armv7m_nvic_clear_pending(void *opaque, int irq, bool secure)
496 {
497     NVICState *s = (NVICState *)opaque;
498     VecInfo *vec;
499 
500     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
501 
502     if (secure) {
503         assert(exc_is_banked(irq));
504         vec = &s->sec_vectors[irq];
505     } else {
506         vec = &s->vectors[irq];
507     }
508     trace_nvic_clear_pending(irq, secure, vec->enabled, vec->prio);
509     if (vec->pending) {
510         vec->pending = 0;
511         nvic_irq_update(s);
512     }
513 }
514 
515 static void do_armv7m_nvic_set_pending(void *opaque, int irq, bool secure,
516                                        bool derived)
517 {
518     /* Pend an exception, including possibly escalating it to HardFault.
519      *
520      * This function handles both "normal" pending of interrupts and
521      * exceptions, and also derived exceptions (ones which occur as
522      * a result of trying to take some other exception).
523      *
524      * If derived == true, the caller guarantees that we are part way through
525      * trying to take an exception (but have not yet called
526      * armv7m_nvic_acknowledge_irq() to make it active), and so:
527      *  - s->vectpending is the "original exception" we were trying to take
528      *  - irq is the "derived exception"
529      *  - nvic_exec_prio(s) gives the priority before exception entry
530      * Here we handle the prioritization logic which the pseudocode puts
531      * in the DerivedLateArrival() function.
532      */
533 
534     NVICState *s = (NVICState *)opaque;
535     bool banked = exc_is_banked(irq);
536     VecInfo *vec;
537     bool targets_secure;
538 
539     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
540     assert(!secure || banked);
541 
542     vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];
543 
544     targets_secure = banked ? secure : exc_targets_secure(s, irq);
545 
546     trace_nvic_set_pending(irq, secure, targets_secure,
547                            derived, vec->enabled, vec->prio);
548 
549     if (derived) {
550         /* Derived exceptions are always synchronous. */
551         assert(irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV);
552 
553         if (irq == ARMV7M_EXCP_DEBUG &&
554             exc_group_prio(s, vec->prio, secure) >= nvic_exec_prio(s)) {
555             /* DebugMonitorFault, but its priority is lower than the
556              * preempted exception priority: just ignore it.
557              */
558             return;
559         }
560 
561         if (irq == ARMV7M_EXCP_HARD && vec->prio >= s->vectpending_prio) {
562             /* If this is a terminal exception (one which means we cannot
563              * take the original exception, like a failure to read its
564              * vector table entry), then we must take the derived exception.
565              * If the derived exception can't take priority over the
566              * original exception, then we go into Lockup.
567              *
568              * For QEMU, we rely on the fact that a derived exception is
569              * terminal if and only if it's reported to us as HardFault,
570              * which saves having to have an extra argument is_terminal
571              * that we'd only use in one place.
572              */
573             cpu_abort(&s->cpu->parent_obj,
574                       "Lockup: can't take terminal derived exception "
575                       "(original exception priority %d)\n",
576                       s->vectpending_prio);
577         }
578         /* We now continue with the same code as for a normal pending
579          * exception, which will cause us to pend the derived exception.
580          * We'll then take either the original or the derived exception
581          * based on which is higher priority by the usual mechanism
582          * for selecting the highest priority pending interrupt.
583          */
584     }
585 
586     if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {
587         /* If a synchronous exception is pending then it may be
588          * escalated to HardFault if:
589          *  * it is equal or lower priority to current execution
590          *  * it is disabled
591          * (ie we need to take it immediately but we can't do so).
592          * Asynchronous exceptions (and interrupts) simply remain pending.
593          *
594          * For QEMU, we don't have any imprecise (asynchronous) faults,
595          * so we can assume that PREFETCH_ABORT and DATA_ABORT are always
596          * synchronous.
597          * Debug exceptions are awkward because only Debug exceptions
598          * resulting from the BKPT instruction should be escalated,
599          * but we don't currently implement any Debug exceptions other
600          * than those that result from BKPT, so we treat all debug exceptions
601          * as needing escalation.
602          *
603          * This all means we can identify whether to escalate based only on
604          * the exception number and don't (yet) need the caller to explicitly
605          * tell us whether this exception is synchronous or not.
606          */
607         int running = nvic_exec_prio(s);
608         bool escalate = false;
609 
610         if (exc_group_prio(s, vec->prio, secure) >= running) {
611             trace_nvic_escalate_prio(irq, vec->prio, running);
612             escalate = true;
613         } else if (!vec->enabled) {
614             trace_nvic_escalate_disabled(irq);
615             escalate = true;
616         }
617 
618         if (escalate) {
619 
620             /* We need to escalate this exception to a synchronous HardFault.
621              * If BFHFNMINS is set then we escalate to the banked HF for
622              * the target security state of the original exception; otherwise
623              * we take a Secure HardFault.
624              */
625             irq = ARMV7M_EXCP_HARD;
626             if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY) &&
627                 (targets_secure ||
628                  !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))) {
629                 vec = &s->sec_vectors[irq];
630             } else {
631                 vec = &s->vectors[irq];
632             }
633             if (running <= vec->prio) {
634                 /* We want to escalate to HardFault but we can't take the
635                  * synchronous HardFault at this point either. This is a
636                  * Lockup condition due to a guest bug. We don't model
637                  * Lockup, so report via cpu_abort() instead.
638                  */
639                 cpu_abort(&s->cpu->parent_obj,
640                           "Lockup: can't escalate %d to HardFault "
641                           "(current priority %d)\n", irq, running);
642             }
643 
644             /* HF may be banked but there is only one shared HFSR */
645             s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;
646         }
647     }
648 
649     if (!vec->pending) {
650         vec->pending = 1;
651         nvic_irq_update(s);
652     }
653 }
654 
655 void armv7m_nvic_set_pending(void *opaque, int irq, bool secure)
656 {
657     do_armv7m_nvic_set_pending(opaque, irq, secure, false);
658 }
659 
660 void armv7m_nvic_set_pending_derived(void *opaque, int irq, bool secure)
661 {
662     do_armv7m_nvic_set_pending(opaque, irq, secure, true);
663 }
664 
665 void armv7m_nvic_set_pending_lazyfp(void *opaque, int irq, bool secure)
666 {
667     /*
668      * Pend an exception during lazy FP stacking. This differs
669      * from the usual exception pending because the logic for
670      * whether we should escalate depends on the saved context
671      * in the FPCCR register, not on the current state of the CPU/NVIC.
672      */
673     NVICState *s = (NVICState *)opaque;
674     bool banked = exc_is_banked(irq);
675     VecInfo *vec;
676     bool targets_secure;
677     bool escalate = false;
678     /*
679      * We will only look at bits in fpccr if this is a banked exception
680      * (in which case 'secure' tells us whether it is the S or NS version).
681      * All the bits for the non-banked exceptions are in fpccr_s.
682      */
683     uint32_t fpccr_s = s->cpu->env.v7m.fpccr[M_REG_S];
684     uint32_t fpccr = s->cpu->env.v7m.fpccr[secure];
685 
686     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
687     assert(!secure || banked);
688 
689     vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];
690 
691     targets_secure = banked ? secure : exc_targets_secure(s, irq);
692 
693     switch (irq) {
694     case ARMV7M_EXCP_DEBUG:
695         if (!(fpccr_s & R_V7M_FPCCR_MONRDY_MASK)) {
696             /* Ignore DebugMonitor exception */
697             return;
698         }
699         break;
700     case ARMV7M_EXCP_MEM:
701         escalate = !(fpccr & R_V7M_FPCCR_MMRDY_MASK);
702         break;
703     case ARMV7M_EXCP_USAGE:
704         escalate = !(fpccr & R_V7M_FPCCR_UFRDY_MASK);
705         break;
706     case ARMV7M_EXCP_BUS:
707         escalate = !(fpccr_s & R_V7M_FPCCR_BFRDY_MASK);
708         break;
709     case ARMV7M_EXCP_SECURE:
710         escalate = !(fpccr_s & R_V7M_FPCCR_SFRDY_MASK);
711         break;
712     default:
713         g_assert_not_reached();
714     }
715 
716     if (escalate) {
717         /*
718          * Escalate to HardFault: faults that initially targeted Secure
719          * continue to do so, even if HF normally targets NonSecure.
720          */
721         irq = ARMV7M_EXCP_HARD;
722         if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY) &&
723             (targets_secure ||
724              !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))) {
725             vec = &s->sec_vectors[irq];
726         } else {
727             vec = &s->vectors[irq];
728         }
729     }
730 
731     if (!vec->enabled ||
732         nvic_exec_prio(s) <= exc_group_prio(s, vec->prio, secure)) {
733         if (!(fpccr_s & R_V7M_FPCCR_HFRDY_MASK)) {
734             /*
735              * We want to escalate to HardFault but the context the
736              * FP state belongs to prevents the exception pre-empting.
737              */
738             cpu_abort(&s->cpu->parent_obj,
739                       "Lockup: can't escalate to HardFault during "
740                       "lazy FP register stacking\n");
741         }
742     }
743 
744     if (escalate) {
745         s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;
746     }
747     if (!vec->pending) {
748         vec->pending = 1;
749         /*
750          * We do not call nvic_irq_update(), because we know our caller
751          * is going to handle causing us to take the exception by
752          * raising EXCP_LAZYFP, so raising the IRQ line would be
753          * pointless extra work. We just need to recompute the
754          * priorities so that armv7m_nvic_can_take_pending_exception()
755          * returns the right answer.
756          */
757         nvic_recompute_state(s);
758     }
759 }
760 
761 /* Make pending IRQ active.  */
762 void armv7m_nvic_acknowledge_irq(void *opaque)
763 {
764     NVICState *s = (NVICState *)opaque;
765     CPUARMState *env = &s->cpu->env;
766     const int pending = s->vectpending;
767     const int running = nvic_exec_prio(s);
768     VecInfo *vec;
769 
770     assert(pending > ARMV7M_EXCP_RESET && pending < s->num_irq);
771 
772     if (s->vectpending_is_s_banked) {
773         vec = &s->sec_vectors[pending];
774     } else {
775         vec = &s->vectors[pending];
776     }
777 
778     assert(vec->enabled);
779     assert(vec->pending);
780 
781     assert(s->vectpending_prio < running);
782 
783     trace_nvic_acknowledge_irq(pending, s->vectpending_prio);
784 
785     vec->active = 1;
786     vec->pending = 0;
787 
788     write_v7m_exception(env, s->vectpending);
789 
790     nvic_irq_update(s);
791 }
792 
793 void armv7m_nvic_get_pending_irq_info(void *opaque,
794                                       int *pirq, bool *ptargets_secure)
795 {
796     NVICState *s = (NVICState *)opaque;
797     const int pending = s->vectpending;
798     bool targets_secure;
799 
800     assert(pending > ARMV7M_EXCP_RESET && pending < s->num_irq);
801 
802     if (s->vectpending_is_s_banked) {
803         targets_secure = true;
804     } else {
805         targets_secure = !exc_is_banked(pending) &&
806             exc_targets_secure(s, pending);
807     }
808 
809     trace_nvic_get_pending_irq_info(pending, targets_secure);
810 
811     *ptargets_secure = targets_secure;
812     *pirq = pending;
813 }
814 
815 int armv7m_nvic_complete_irq(void *opaque, int irq, bool secure)
816 {
817     NVICState *s = (NVICState *)opaque;
818     VecInfo *vec = NULL;
819     int ret;
820 
821     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
822 
823     /*
824      * For negative priorities, v8M will forcibly deactivate the appropriate
825      * NMI or HardFault regardless of what interrupt we're being asked to
826      * deactivate (compare the DeActivate() pseudocode). This is a guard
827      * against software returning from NMI or HardFault with a corrupted
828      * IPSR and leaving the CPU in a negative-priority state.
829      * v7M does not do this, but simply deactivates the requested interrupt.
830      */
831     if (arm_feature(&s->cpu->env, ARM_FEATURE_V8)) {
832         switch (armv7m_nvic_raw_execution_priority(s)) {
833         case -1:
834             if (s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
835                 vec = &s->vectors[ARMV7M_EXCP_HARD];
836             } else {
837                 vec = &s->sec_vectors[ARMV7M_EXCP_HARD];
838             }
839             break;
840         case -2:
841             vec = &s->vectors[ARMV7M_EXCP_NMI];
842             break;
843         case -3:
844             vec = &s->sec_vectors[ARMV7M_EXCP_HARD];
845             break;
846         default:
847             break;
848         }
849     }
850 
851     if (!vec) {
852         if (secure && exc_is_banked(irq)) {
853             vec = &s->sec_vectors[irq];
854         } else {
855             vec = &s->vectors[irq];
856         }
857     }
858 
859     trace_nvic_complete_irq(irq, secure);
860 
861     if (!vec->active) {
862         /* Tell the caller this was an illegal exception return */
863         return -1;
864     }
865 
866     /*
867      * If this is a configurable exception and it is currently
868      * targeting the opposite security state from the one we're trying
869      * to complete it for, this counts as an illegal exception return.
870      * We still need to deactivate whatever vector the logic above has
871      * selected, though, as it might not be the same as the one for the
872      * requested exception number.
873      */
874     if (!exc_is_banked(irq) && exc_targets_secure(s, irq) != secure) {
875         ret = -1;
876     } else {
877         ret = nvic_rettobase(s);
878     }
879 
880     vec->active = 0;
881     if (vec->level) {
882         /* Re-pend the exception if it's still held high; only
883          * happens for extenal IRQs
884          */
885         assert(irq >= NVIC_FIRST_IRQ);
886         vec->pending = 1;
887     }
888 
889     nvic_irq_update(s);
890 
891     return ret;
892 }
893 
894 bool armv7m_nvic_get_ready_status(void *opaque, int irq, bool secure)
895 {
896     /*
897      * Return whether an exception is "ready", i.e. it is enabled and is
898      * configured at a priority which would allow it to interrupt the
899      * current execution priority.
900      *
901      * irq and secure have the same semantics as for armv7m_nvic_set_pending():
902      * for non-banked exceptions secure is always false; for banked exceptions
903      * it indicates which of the exceptions is required.
904      */
905     NVICState *s = (NVICState *)opaque;
906     bool banked = exc_is_banked(irq);
907     VecInfo *vec;
908     int running = nvic_exec_prio(s);
909 
910     assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);
911     assert(!secure || banked);
912 
913     /*
914      * HardFault is an odd special case: we always check against -1,
915      * even if we're secure and HardFault has priority -3; we never
916      * need to check for enabled state.
917      */
918     if (irq == ARMV7M_EXCP_HARD) {
919         return running > -1;
920     }
921 
922     vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];
923 
924     return vec->enabled &&
925         exc_group_prio(s, vec->prio, secure) < running;
926 }
927 
928 /* callback when external interrupt line is changed */
929 static void set_irq_level(void *opaque, int n, int level)
930 {
931     NVICState *s = opaque;
932     VecInfo *vec;
933 
934     n += NVIC_FIRST_IRQ;
935 
936     assert(n >= NVIC_FIRST_IRQ && n < s->num_irq);
937 
938     trace_nvic_set_irq_level(n, level);
939 
940     /* The pending status of an external interrupt is
941      * latched on rising edge and exception handler return.
942      *
943      * Pulsing the IRQ will always run the handler
944      * once, and the handler will re-run until the
945      * level is low when the handler completes.
946      */
947     vec = &s->vectors[n];
948     if (level != vec->level) {
949         vec->level = level;
950         if (level) {
951             armv7m_nvic_set_pending(s, n, false);
952         }
953     }
954 }
955 
956 /* callback when external NMI line is changed */
957 static void nvic_nmi_trigger(void *opaque, int n, int level)
958 {
959     NVICState *s = opaque;
960 
961     trace_nvic_set_nmi_level(level);
962 
963     /*
964      * The architecture doesn't specify whether NMI should share
965      * the normal-interrupt behaviour of being resampled on
966      * exception handler return. We choose not to, so just
967      * set NMI pending here and don't track the current level.
968      */
969     if (level) {
970         armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI, false);
971     }
972 }
973 
974 static uint32_t nvic_readl(NVICState *s, uint32_t offset, MemTxAttrs attrs)
975 {
976     ARMCPU *cpu = s->cpu;
977     uint32_t val;
978 
979     switch (offset) {
980     case 4: /* Interrupt Control Type.  */
981         if (!arm_feature(&cpu->env, ARM_FEATURE_V7)) {
982             goto bad_offset;
983         }
984         return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;
985     case 0xc: /* CPPWR */
986         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
987             goto bad_offset;
988         }
989         /* We make the IMPDEF choice that nothing can ever go into a
990          * non-retentive power state, which allows us to RAZ/WI this.
991          */
992         return 0;
993     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
994     {
995         int startvec = 8 * (offset - 0x380) + NVIC_FIRST_IRQ;
996         int i;
997 
998         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
999             goto bad_offset;
1000         }
1001         if (!attrs.secure) {
1002             return 0;
1003         }
1004         val = 0;
1005         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
1006             if (s->itns[startvec + i]) {
1007                 val |= (1 << i);
1008             }
1009         }
1010         return val;
1011     }
1012     case 0xd00: /* CPUID Base.  */
1013         return cpu->midr;
1014     case 0xd04: /* Interrupt Control State (ICSR) */
1015         /* VECTACTIVE */
1016         val = cpu->env.v7m.exception;
1017         /* VECTPENDING */
1018         val |= (s->vectpending & 0xff) << 12;
1019         /* ISRPENDING - set if any external IRQ is pending */
1020         if (nvic_isrpending(s)) {
1021             val |= (1 << 22);
1022         }
1023         /* RETTOBASE - set if only one handler is active */
1024         if (nvic_rettobase(s)) {
1025             val |= (1 << 11);
1026         }
1027         if (attrs.secure) {
1028             /* PENDSTSET */
1029             if (s->sec_vectors[ARMV7M_EXCP_SYSTICK].pending) {
1030                 val |= (1 << 26);
1031             }
1032             /* PENDSVSET */
1033             if (s->sec_vectors[ARMV7M_EXCP_PENDSV].pending) {
1034                 val |= (1 << 28);
1035             }
1036         } else {
1037             /* PENDSTSET */
1038             if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {
1039                 val |= (1 << 26);
1040             }
1041             /* PENDSVSET */
1042             if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {
1043                 val |= (1 << 28);
1044             }
1045         }
1046         /* NMIPENDSET */
1047         if ((attrs.secure || (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))
1048             && s->vectors[ARMV7M_EXCP_NMI].pending) {
1049             val |= (1 << 31);
1050         }
1051         /* ISRPREEMPT: RES0 when halting debug not implemented */
1052         /* STTNS: RES0 for the Main Extension */
1053         return val;
1054     case 0xd08: /* Vector Table Offset.  */
1055         return cpu->env.v7m.vecbase[attrs.secure];
1056     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
1057         val = 0xfa050000 | (s->prigroup[attrs.secure] << 8);
1058         if (attrs.secure) {
1059             /* s->aircr stores PRIS, BFHFNMINS, SYSRESETREQS */
1060             val |= cpu->env.v7m.aircr;
1061         } else {
1062             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1063                 /* BFHFNMINS is R/O from NS; other bits are RAZ/WI. If
1064                  * security isn't supported then BFHFNMINS is RAO (and
1065                  * the bit in env.v7m.aircr is always set).
1066                  */
1067                 val |= cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK;
1068             }
1069         }
1070         return val;
1071     case 0xd10: /* System Control.  */
1072         if (!arm_feature(&cpu->env, ARM_FEATURE_V7)) {
1073             goto bad_offset;
1074         }
1075         return cpu->env.v7m.scr[attrs.secure];
1076     case 0xd14: /* Configuration Control.  */
1077         /* The BFHFNMIGN bit is the only non-banked bit; we
1078          * keep it in the non-secure copy of the register.
1079          */
1080         val = cpu->env.v7m.ccr[attrs.secure];
1081         val |= cpu->env.v7m.ccr[M_REG_NS] & R_V7M_CCR_BFHFNMIGN_MASK;
1082         return val;
1083     case 0xd24: /* System Handler Control and State (SHCSR) */
1084         if (!arm_feature(&cpu->env, ARM_FEATURE_V7)) {
1085             goto bad_offset;
1086         }
1087         val = 0;
1088         if (attrs.secure) {
1089             if (s->sec_vectors[ARMV7M_EXCP_MEM].active) {
1090                 val |= (1 << 0);
1091             }
1092             if (s->sec_vectors[ARMV7M_EXCP_HARD].active) {
1093                 val |= (1 << 2);
1094             }
1095             if (s->sec_vectors[ARMV7M_EXCP_USAGE].active) {
1096                 val |= (1 << 3);
1097             }
1098             if (s->sec_vectors[ARMV7M_EXCP_SVC].active) {
1099                 val |= (1 << 7);
1100             }
1101             if (s->sec_vectors[ARMV7M_EXCP_PENDSV].active) {
1102                 val |= (1 << 10);
1103             }
1104             if (s->sec_vectors[ARMV7M_EXCP_SYSTICK].active) {
1105                 val |= (1 << 11);
1106             }
1107             if (s->sec_vectors[ARMV7M_EXCP_USAGE].pending) {
1108                 val |= (1 << 12);
1109             }
1110             if (s->sec_vectors[ARMV7M_EXCP_MEM].pending) {
1111                 val |= (1 << 13);
1112             }
1113             if (s->sec_vectors[ARMV7M_EXCP_SVC].pending) {
1114                 val |= (1 << 15);
1115             }
1116             if (s->sec_vectors[ARMV7M_EXCP_MEM].enabled) {
1117                 val |= (1 << 16);
1118             }
1119             if (s->sec_vectors[ARMV7M_EXCP_USAGE].enabled) {
1120                 val |= (1 << 18);
1121             }
1122             if (s->sec_vectors[ARMV7M_EXCP_HARD].pending) {
1123                 val |= (1 << 21);
1124             }
1125             /* SecureFault is not banked but is always RAZ/WI to NS */
1126             if (s->vectors[ARMV7M_EXCP_SECURE].active) {
1127                 val |= (1 << 4);
1128             }
1129             if (s->vectors[ARMV7M_EXCP_SECURE].enabled) {
1130                 val |= (1 << 19);
1131             }
1132             if (s->vectors[ARMV7M_EXCP_SECURE].pending) {
1133                 val |= (1 << 20);
1134             }
1135         } else {
1136             if (s->vectors[ARMV7M_EXCP_MEM].active) {
1137                 val |= (1 << 0);
1138             }
1139             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1140                 /* HARDFAULTACT, HARDFAULTPENDED not present in v7M */
1141                 if (s->vectors[ARMV7M_EXCP_HARD].active) {
1142                     val |= (1 << 2);
1143                 }
1144                 if (s->vectors[ARMV7M_EXCP_HARD].pending) {
1145                     val |= (1 << 21);
1146                 }
1147             }
1148             if (s->vectors[ARMV7M_EXCP_USAGE].active) {
1149                 val |= (1 << 3);
1150             }
1151             if (s->vectors[ARMV7M_EXCP_SVC].active) {
1152                 val |= (1 << 7);
1153             }
1154             if (s->vectors[ARMV7M_EXCP_PENDSV].active) {
1155                 val |= (1 << 10);
1156             }
1157             if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {
1158                 val |= (1 << 11);
1159             }
1160             if (s->vectors[ARMV7M_EXCP_USAGE].pending) {
1161                 val |= (1 << 12);
1162             }
1163             if (s->vectors[ARMV7M_EXCP_MEM].pending) {
1164                 val |= (1 << 13);
1165             }
1166             if (s->vectors[ARMV7M_EXCP_SVC].pending) {
1167                 val |= (1 << 15);
1168             }
1169             if (s->vectors[ARMV7M_EXCP_MEM].enabled) {
1170                 val |= (1 << 16);
1171             }
1172             if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {
1173                 val |= (1 << 18);
1174             }
1175         }
1176         if (attrs.secure || (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1177             if (s->vectors[ARMV7M_EXCP_BUS].active) {
1178                 val |= (1 << 1);
1179             }
1180             if (s->vectors[ARMV7M_EXCP_BUS].pending) {
1181                 val |= (1 << 14);
1182             }
1183             if (s->vectors[ARMV7M_EXCP_BUS].enabled) {
1184                 val |= (1 << 17);
1185             }
1186             if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
1187                 s->vectors[ARMV7M_EXCP_NMI].active) {
1188                 /* NMIACT is not present in v7M */
1189                 val |= (1 << 5);
1190             }
1191         }
1192 
1193         /* TODO: this is RAZ/WI from NS if DEMCR.SDME is set */
1194         if (s->vectors[ARMV7M_EXCP_DEBUG].active) {
1195             val |= (1 << 8);
1196         }
1197         return val;
1198     case 0xd2c: /* Hard Fault Status.  */
1199         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1200             goto bad_offset;
1201         }
1202         return cpu->env.v7m.hfsr;
1203     case 0xd30: /* Debug Fault Status.  */
1204         return cpu->env.v7m.dfsr;
1205     case 0xd34: /* MMFAR MemManage Fault Address */
1206         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1207             goto bad_offset;
1208         }
1209         return cpu->env.v7m.mmfar[attrs.secure];
1210     case 0xd38: /* Bus Fault Address.  */
1211         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1212             goto bad_offset;
1213         }
1214         if (!attrs.secure &&
1215             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1216             return 0;
1217         }
1218         return cpu->env.v7m.bfar;
1219     case 0xd3c: /* Aux Fault Status.  */
1220         /* TODO: Implement fault status registers.  */
1221         qemu_log_mask(LOG_UNIMP,
1222                       "Aux Fault status registers unimplemented\n");
1223         return 0;
1224     case 0xd40: /* PFR0.  */
1225         return cpu->id_pfr0;
1226     case 0xd44: /* PFR1.  */
1227         return cpu->id_pfr1;
1228     case 0xd48: /* DFR0.  */
1229         return cpu->id_dfr0;
1230     case 0xd4c: /* AFR0.  */
1231         return cpu->id_afr0;
1232     case 0xd50: /* MMFR0.  */
1233         return cpu->id_mmfr0;
1234     case 0xd54: /* MMFR1.  */
1235         return cpu->id_mmfr1;
1236     case 0xd58: /* MMFR2.  */
1237         return cpu->id_mmfr2;
1238     case 0xd5c: /* MMFR3.  */
1239         return cpu->id_mmfr3;
1240     case 0xd60: /* ISAR0.  */
1241         return cpu->isar.id_isar0;
1242     case 0xd64: /* ISAR1.  */
1243         return cpu->isar.id_isar1;
1244     case 0xd68: /* ISAR2.  */
1245         return cpu->isar.id_isar2;
1246     case 0xd6c: /* ISAR3.  */
1247         return cpu->isar.id_isar3;
1248     case 0xd70: /* ISAR4.  */
1249         return cpu->isar.id_isar4;
1250     case 0xd74: /* ISAR5.  */
1251         return cpu->isar.id_isar5;
1252     case 0xd78: /* CLIDR */
1253         return cpu->clidr;
1254     case 0xd7c: /* CTR */
1255         return cpu->ctr;
1256     case 0xd80: /* CSSIDR */
1257     {
1258         int idx = cpu->env.v7m.csselr[attrs.secure] & R_V7M_CSSELR_INDEX_MASK;
1259         return cpu->ccsidr[idx];
1260     }
1261     case 0xd84: /* CSSELR */
1262         return cpu->env.v7m.csselr[attrs.secure];
1263     case 0xd88: /* CPACR */
1264         if (!arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1265             return 0;
1266         }
1267         return cpu->env.v7m.cpacr[attrs.secure];
1268     case 0xd8c: /* NSACR */
1269         if (!attrs.secure || !arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1270             return 0;
1271         }
1272         return cpu->env.v7m.nsacr;
1273     /* TODO: Implement debug registers.  */
1274     case 0xd90: /* MPU_TYPE */
1275         /* Unified MPU; if the MPU is not present this value is zero */
1276         return cpu->pmsav7_dregion << 8;
1277         break;
1278     case 0xd94: /* MPU_CTRL */
1279         return cpu->env.v7m.mpu_ctrl[attrs.secure];
1280     case 0xd98: /* MPU_RNR */
1281         return cpu->env.pmsav7.rnr[attrs.secure];
1282     case 0xd9c: /* MPU_RBAR */
1283     case 0xda4: /* MPU_RBAR_A1 */
1284     case 0xdac: /* MPU_RBAR_A2 */
1285     case 0xdb4: /* MPU_RBAR_A3 */
1286     {
1287         int region = cpu->env.pmsav7.rnr[attrs.secure];
1288 
1289         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1290             /* PMSAv8M handling of the aliases is different from v7M:
1291              * aliases A1, A2, A3 override the low two bits of the region
1292              * number in MPU_RNR, and there is no 'region' field in the
1293              * RBAR register.
1294              */
1295             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1296             if (aliasno) {
1297                 region = deposit32(region, 0, 2, aliasno);
1298             }
1299             if (region >= cpu->pmsav7_dregion) {
1300                 return 0;
1301             }
1302             return cpu->env.pmsav8.rbar[attrs.secure][region];
1303         }
1304 
1305         if (region >= cpu->pmsav7_dregion) {
1306             return 0;
1307         }
1308         return (cpu->env.pmsav7.drbar[region] & ~0x1f) | (region & 0xf);
1309     }
1310     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
1311     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
1312     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
1313     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
1314     {
1315         int region = cpu->env.pmsav7.rnr[attrs.secure];
1316 
1317         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1318             /* PMSAv8M handling of the aliases is different from v7M:
1319              * aliases A1, A2, A3 override the low two bits of the region
1320              * number in MPU_RNR.
1321              */
1322             int aliasno = (offset - 0xda0) / 8; /* 0..3 */
1323             if (aliasno) {
1324                 region = deposit32(region, 0, 2, aliasno);
1325             }
1326             if (region >= cpu->pmsav7_dregion) {
1327                 return 0;
1328             }
1329             return cpu->env.pmsav8.rlar[attrs.secure][region];
1330         }
1331 
1332         if (region >= cpu->pmsav7_dregion) {
1333             return 0;
1334         }
1335         return ((cpu->env.pmsav7.dracr[region] & 0xffff) << 16) |
1336             (cpu->env.pmsav7.drsr[region] & 0xffff);
1337     }
1338     case 0xdc0: /* MPU_MAIR0 */
1339         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1340             goto bad_offset;
1341         }
1342         return cpu->env.pmsav8.mair0[attrs.secure];
1343     case 0xdc4: /* MPU_MAIR1 */
1344         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1345             goto bad_offset;
1346         }
1347         return cpu->env.pmsav8.mair1[attrs.secure];
1348     case 0xdd0: /* SAU_CTRL */
1349         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1350             goto bad_offset;
1351         }
1352         if (!attrs.secure) {
1353             return 0;
1354         }
1355         return cpu->env.sau.ctrl;
1356     case 0xdd4: /* SAU_TYPE */
1357         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1358             goto bad_offset;
1359         }
1360         if (!attrs.secure) {
1361             return 0;
1362         }
1363         return cpu->sau_sregion;
1364     case 0xdd8: /* SAU_RNR */
1365         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1366             goto bad_offset;
1367         }
1368         if (!attrs.secure) {
1369             return 0;
1370         }
1371         return cpu->env.sau.rnr;
1372     case 0xddc: /* SAU_RBAR */
1373     {
1374         int region = cpu->env.sau.rnr;
1375 
1376         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1377             goto bad_offset;
1378         }
1379         if (!attrs.secure) {
1380             return 0;
1381         }
1382         if (region >= cpu->sau_sregion) {
1383             return 0;
1384         }
1385         return cpu->env.sau.rbar[region];
1386     }
1387     case 0xde0: /* SAU_RLAR */
1388     {
1389         int region = cpu->env.sau.rnr;
1390 
1391         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1392             goto bad_offset;
1393         }
1394         if (!attrs.secure) {
1395             return 0;
1396         }
1397         if (region >= cpu->sau_sregion) {
1398             return 0;
1399         }
1400         return cpu->env.sau.rlar[region];
1401     }
1402     case 0xde4: /* SFSR */
1403         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1404             goto bad_offset;
1405         }
1406         if (!attrs.secure) {
1407             return 0;
1408         }
1409         return cpu->env.v7m.sfsr;
1410     case 0xde8: /* SFAR */
1411         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1412             goto bad_offset;
1413         }
1414         if (!attrs.secure) {
1415             return 0;
1416         }
1417         return cpu->env.v7m.sfar;
1418     case 0xf34: /* FPCCR */
1419         if (!arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1420             return 0;
1421         }
1422         if (attrs.secure) {
1423             return cpu->env.v7m.fpccr[M_REG_S];
1424         } else {
1425             /*
1426              * NS can read LSPEN, CLRONRET and MONRDY. It can read
1427              * BFRDY and HFRDY if AIRCR.BFHFNMINS != 0;
1428              * other non-banked bits RAZ.
1429              * TODO: MONRDY should RAZ/WI if DEMCR.SDME is set.
1430              */
1431             uint32_t value = cpu->env.v7m.fpccr[M_REG_S];
1432             uint32_t mask = R_V7M_FPCCR_LSPEN_MASK |
1433                 R_V7M_FPCCR_CLRONRET_MASK |
1434                 R_V7M_FPCCR_MONRDY_MASK;
1435 
1436             if (s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
1437                 mask |= R_V7M_FPCCR_BFRDY_MASK | R_V7M_FPCCR_HFRDY_MASK;
1438             }
1439 
1440             value &= mask;
1441 
1442             value |= cpu->env.v7m.fpccr[M_REG_NS];
1443             return value;
1444         }
1445     case 0xf38: /* FPCAR */
1446         if (!arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1447             return 0;
1448         }
1449         return cpu->env.v7m.fpcar[attrs.secure];
1450     case 0xf3c: /* FPDSCR */
1451         if (!arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1452             return 0;
1453         }
1454         return cpu->env.v7m.fpdscr[attrs.secure];
1455     case 0xf40: /* MVFR0 */
1456         return cpu->isar.mvfr0;
1457     case 0xf44: /* MVFR1 */
1458         return cpu->isar.mvfr1;
1459     case 0xf48: /* MVFR2 */
1460         return cpu->isar.mvfr2;
1461     default:
1462     bad_offset:
1463         qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);
1464         return 0;
1465     }
1466 }
1467 
1468 static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value,
1469                         MemTxAttrs attrs)
1470 {
1471     ARMCPU *cpu = s->cpu;
1472 
1473     switch (offset) {
1474     case 0xc: /* CPPWR */
1475         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1476             goto bad_offset;
1477         }
1478         /* Make the IMPDEF choice to RAZ/WI this. */
1479         break;
1480     case 0x380 ... 0x3bf: /* NVIC_ITNS<n> */
1481     {
1482         int startvec = 8 * (offset - 0x380) + NVIC_FIRST_IRQ;
1483         int i;
1484 
1485         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1486             goto bad_offset;
1487         }
1488         if (!attrs.secure) {
1489             break;
1490         }
1491         for (i = 0; i < 32 && startvec + i < s->num_irq; i++) {
1492             s->itns[startvec + i] = (value >> i) & 1;
1493         }
1494         nvic_irq_update(s);
1495         break;
1496     }
1497     case 0xd04: /* Interrupt Control State (ICSR) */
1498         if (attrs.secure || cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
1499             if (value & (1 << 31)) {
1500                 armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI, false);
1501             } else if (value & (1 << 30) &&
1502                        arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1503                 /* PENDNMICLR didn't exist in v7M */
1504                 armv7m_nvic_clear_pending(s, ARMV7M_EXCP_NMI, false);
1505             }
1506         }
1507         if (value & (1 << 28)) {
1508             armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
1509         } else if (value & (1 << 27)) {
1510             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV, attrs.secure);
1511         }
1512         if (value & (1 << 26)) {
1513             armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
1514         } else if (value & (1 << 25)) {
1515             armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK, attrs.secure);
1516         }
1517         break;
1518     case 0xd08: /* Vector Table Offset.  */
1519         cpu->env.v7m.vecbase[attrs.secure] = value & 0xffffff80;
1520         break;
1521     case 0xd0c: /* Application Interrupt/Reset Control (AIRCR) */
1522         if ((value >> R_V7M_AIRCR_VECTKEY_SHIFT) == 0x05fa) {
1523             if (value & R_V7M_AIRCR_SYSRESETREQ_MASK) {
1524                 if (attrs.secure ||
1525                     !(cpu->env.v7m.aircr & R_V7M_AIRCR_SYSRESETREQS_MASK)) {
1526                     qemu_irq_pulse(s->sysresetreq);
1527                 }
1528             }
1529             if (value & R_V7M_AIRCR_VECTCLRACTIVE_MASK) {
1530                 qemu_log_mask(LOG_GUEST_ERROR,
1531                               "Setting VECTCLRACTIVE when not in DEBUG mode "
1532                               "is UNPREDICTABLE\n");
1533             }
1534             if (value & R_V7M_AIRCR_VECTRESET_MASK) {
1535                 /* NB: this bit is RES0 in v8M */
1536                 qemu_log_mask(LOG_GUEST_ERROR,
1537                               "Setting VECTRESET when not in DEBUG mode "
1538                               "is UNPREDICTABLE\n");
1539             }
1540             if (arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1541                 s->prigroup[attrs.secure] =
1542                     extract32(value,
1543                               R_V7M_AIRCR_PRIGROUP_SHIFT,
1544                               R_V7M_AIRCR_PRIGROUP_LENGTH);
1545             }
1546             if (attrs.secure) {
1547                 /* These bits are only writable by secure */
1548                 cpu->env.v7m.aircr = value &
1549                     (R_V7M_AIRCR_SYSRESETREQS_MASK |
1550                      R_V7M_AIRCR_BFHFNMINS_MASK |
1551                      R_V7M_AIRCR_PRIS_MASK);
1552                 /* BFHFNMINS changes the priority of Secure HardFault, and
1553                  * allows a pending Non-secure HardFault to preempt (which
1554                  * we implement by marking it enabled).
1555                  */
1556                 if (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) {
1557                     s->sec_vectors[ARMV7M_EXCP_HARD].prio = -3;
1558                     s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
1559                 } else {
1560                     s->sec_vectors[ARMV7M_EXCP_HARD].prio = -1;
1561                     s->vectors[ARMV7M_EXCP_HARD].enabled = 0;
1562                 }
1563             }
1564             nvic_irq_update(s);
1565         }
1566         break;
1567     case 0xd10: /* System Control.  */
1568         if (!arm_feature(&cpu->env, ARM_FEATURE_V7)) {
1569             goto bad_offset;
1570         }
1571         /* We don't implement deep-sleep so these bits are RAZ/WI.
1572          * The other bits in the register are banked.
1573          * QEMU's implementation ignores SEVONPEND and SLEEPONEXIT, which
1574          * is architecturally permitted.
1575          */
1576         value &= ~(R_V7M_SCR_SLEEPDEEP_MASK | R_V7M_SCR_SLEEPDEEPS_MASK);
1577         cpu->env.v7m.scr[attrs.secure] = value;
1578         break;
1579     case 0xd14: /* Configuration Control.  */
1580         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1581             goto bad_offset;
1582         }
1583 
1584         /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */
1585         value &= (R_V7M_CCR_STKALIGN_MASK |
1586                   R_V7M_CCR_BFHFNMIGN_MASK |
1587                   R_V7M_CCR_DIV_0_TRP_MASK |
1588                   R_V7M_CCR_UNALIGN_TRP_MASK |
1589                   R_V7M_CCR_USERSETMPEND_MASK |
1590                   R_V7M_CCR_NONBASETHRDENA_MASK);
1591 
1592         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1593             /* v8M makes NONBASETHRDENA and STKALIGN be RES1 */
1594             value |= R_V7M_CCR_NONBASETHRDENA_MASK
1595                 | R_V7M_CCR_STKALIGN_MASK;
1596         }
1597         if (attrs.secure) {
1598             /* the BFHFNMIGN bit is not banked; keep that in the NS copy */
1599             cpu->env.v7m.ccr[M_REG_NS] =
1600                 (cpu->env.v7m.ccr[M_REG_NS] & ~R_V7M_CCR_BFHFNMIGN_MASK)
1601                 | (value & R_V7M_CCR_BFHFNMIGN_MASK);
1602             value &= ~R_V7M_CCR_BFHFNMIGN_MASK;
1603         }
1604 
1605         cpu->env.v7m.ccr[attrs.secure] = value;
1606         break;
1607     case 0xd24: /* System Handler Control and State (SHCSR) */
1608         if (!arm_feature(&cpu->env, ARM_FEATURE_V7)) {
1609             goto bad_offset;
1610         }
1611         if (attrs.secure) {
1612             s->sec_vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
1613             /* Secure HardFault active bit cannot be written */
1614             s->sec_vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
1615             s->sec_vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
1616             s->sec_vectors[ARMV7M_EXCP_PENDSV].active =
1617                 (value & (1 << 10)) != 0;
1618             s->sec_vectors[ARMV7M_EXCP_SYSTICK].active =
1619                 (value & (1 << 11)) != 0;
1620             s->sec_vectors[ARMV7M_EXCP_USAGE].pending =
1621                 (value & (1 << 12)) != 0;
1622             s->sec_vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
1623             s->sec_vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
1624             s->sec_vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
1625             s->sec_vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
1626             s->sec_vectors[ARMV7M_EXCP_USAGE].enabled =
1627                 (value & (1 << 18)) != 0;
1628             s->sec_vectors[ARMV7M_EXCP_HARD].pending = (value & (1 << 21)) != 0;
1629             /* SecureFault not banked, but RAZ/WI to NS */
1630             s->vectors[ARMV7M_EXCP_SECURE].active = (value & (1 << 4)) != 0;
1631             s->vectors[ARMV7M_EXCP_SECURE].enabled = (value & (1 << 19)) != 0;
1632             s->vectors[ARMV7M_EXCP_SECURE].pending = (value & (1 << 20)) != 0;
1633         } else {
1634             s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;
1635             if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1636                 /* HARDFAULTPENDED is not present in v7M */
1637                 s->vectors[ARMV7M_EXCP_HARD].pending = (value & (1 << 21)) != 0;
1638             }
1639             s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;
1640             s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;
1641             s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;
1642             s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;
1643             s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;
1644             s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;
1645             s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;
1646             s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;
1647             s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;
1648         }
1649         if (attrs.secure || (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1650             s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;
1651             s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;
1652             s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;
1653         }
1654         /* NMIACT can only be written if the write is of a zero, with
1655          * BFHFNMINS 1, and by the CPU in secure state via the NS alias.
1656          */
1657         if (!attrs.secure && cpu->env.v7m.secure &&
1658             (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) &&
1659             (value & (1 << 5)) == 0) {
1660             s->vectors[ARMV7M_EXCP_NMI].active = 0;
1661         }
1662         /* HARDFAULTACT can only be written if the write is of a zero
1663          * to the non-secure HardFault state by the CPU in secure state.
1664          * The only case where we can be targeting the non-secure HF state
1665          * when in secure state is if this is a write via the NS alias
1666          * and BFHFNMINS is 1.
1667          */
1668         if (!attrs.secure && cpu->env.v7m.secure &&
1669             (cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK) &&
1670             (value & (1 << 2)) == 0) {
1671             s->vectors[ARMV7M_EXCP_HARD].active = 0;
1672         }
1673 
1674         /* TODO: this is RAZ/WI from NS if DEMCR.SDME is set */
1675         s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;
1676         nvic_irq_update(s);
1677         break;
1678     case 0xd2c: /* Hard Fault Status.  */
1679         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1680             goto bad_offset;
1681         }
1682         cpu->env.v7m.hfsr &= ~value; /* W1C */
1683         break;
1684     case 0xd30: /* Debug Fault Status.  */
1685         cpu->env.v7m.dfsr &= ~value; /* W1C */
1686         break;
1687     case 0xd34: /* Mem Manage Address.  */
1688         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1689             goto bad_offset;
1690         }
1691         cpu->env.v7m.mmfar[attrs.secure] = value;
1692         return;
1693     case 0xd38: /* Bus Fault Address.  */
1694         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1695             goto bad_offset;
1696         }
1697         if (!attrs.secure &&
1698             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1699             return;
1700         }
1701         cpu->env.v7m.bfar = value;
1702         return;
1703     case 0xd3c: /* Aux Fault Status.  */
1704         qemu_log_mask(LOG_UNIMP,
1705                       "NVIC: Aux fault status registers unimplemented\n");
1706         break;
1707     case 0xd84: /* CSSELR */
1708         if (!arm_v7m_csselr_razwi(cpu)) {
1709             cpu->env.v7m.csselr[attrs.secure] = value & R_V7M_CSSELR_INDEX_MASK;
1710         }
1711         break;
1712     case 0xd88: /* CPACR */
1713         if (arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1714             /* We implement only the Floating Point extension's CP10/CP11 */
1715             cpu->env.v7m.cpacr[attrs.secure] = value & (0xf << 20);
1716         }
1717         break;
1718     case 0xd8c: /* NSACR */
1719         if (attrs.secure && arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1720             /* We implement only the Floating Point extension's CP10/CP11 */
1721             cpu->env.v7m.nsacr = value & (3 << 10);
1722         }
1723         break;
1724     case 0xd90: /* MPU_TYPE */
1725         return; /* RO */
1726     case 0xd94: /* MPU_CTRL */
1727         if ((value &
1728              (R_V7M_MPU_CTRL_HFNMIENA_MASK | R_V7M_MPU_CTRL_ENABLE_MASK))
1729             == R_V7M_MPU_CTRL_HFNMIENA_MASK) {
1730             qemu_log_mask(LOG_GUEST_ERROR, "MPU_CTRL: HFNMIENA and !ENABLE is "
1731                           "UNPREDICTABLE\n");
1732         }
1733         cpu->env.v7m.mpu_ctrl[attrs.secure]
1734             = value & (R_V7M_MPU_CTRL_ENABLE_MASK |
1735                        R_V7M_MPU_CTRL_HFNMIENA_MASK |
1736                        R_V7M_MPU_CTRL_PRIVDEFENA_MASK);
1737         tlb_flush(CPU(cpu));
1738         break;
1739     case 0xd98: /* MPU_RNR */
1740         if (value >= cpu->pmsav7_dregion) {
1741             qemu_log_mask(LOG_GUEST_ERROR, "MPU region out of range %"
1742                           PRIu32 "/%" PRIu32 "\n",
1743                           value, cpu->pmsav7_dregion);
1744         } else {
1745             cpu->env.pmsav7.rnr[attrs.secure] = value;
1746         }
1747         break;
1748     case 0xd9c: /* MPU_RBAR */
1749     case 0xda4: /* MPU_RBAR_A1 */
1750     case 0xdac: /* MPU_RBAR_A2 */
1751     case 0xdb4: /* MPU_RBAR_A3 */
1752     {
1753         int region;
1754 
1755         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1756             /* PMSAv8M handling of the aliases is different from v7M:
1757              * aliases A1, A2, A3 override the low two bits of the region
1758              * number in MPU_RNR, and there is no 'region' field in the
1759              * RBAR register.
1760              */
1761             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1762 
1763             region = cpu->env.pmsav7.rnr[attrs.secure];
1764             if (aliasno) {
1765                 region = deposit32(region, 0, 2, aliasno);
1766             }
1767             if (region >= cpu->pmsav7_dregion) {
1768                 return;
1769             }
1770             cpu->env.pmsav8.rbar[attrs.secure][region] = value;
1771             tlb_flush(CPU(cpu));
1772             return;
1773         }
1774 
1775         if (value & (1 << 4)) {
1776             /* VALID bit means use the region number specified in this
1777              * value and also update MPU_RNR.REGION with that value.
1778              */
1779             region = extract32(value, 0, 4);
1780             if (region >= cpu->pmsav7_dregion) {
1781                 qemu_log_mask(LOG_GUEST_ERROR,
1782                               "MPU region out of range %u/%" PRIu32 "\n",
1783                               region, cpu->pmsav7_dregion);
1784                 return;
1785             }
1786             cpu->env.pmsav7.rnr[attrs.secure] = region;
1787         } else {
1788             region = cpu->env.pmsav7.rnr[attrs.secure];
1789         }
1790 
1791         if (region >= cpu->pmsav7_dregion) {
1792             return;
1793         }
1794 
1795         cpu->env.pmsav7.drbar[region] = value & ~0x1f;
1796         tlb_flush(CPU(cpu));
1797         break;
1798     }
1799     case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */
1800     case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */
1801     case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */
1802     case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */
1803     {
1804         int region = cpu->env.pmsav7.rnr[attrs.secure];
1805 
1806         if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1807             /* PMSAv8M handling of the aliases is different from v7M:
1808              * aliases A1, A2, A3 override the low two bits of the region
1809              * number in MPU_RNR.
1810              */
1811             int aliasno = (offset - 0xd9c) / 8; /* 0..3 */
1812 
1813             region = cpu->env.pmsav7.rnr[attrs.secure];
1814             if (aliasno) {
1815                 region = deposit32(region, 0, 2, aliasno);
1816             }
1817             if (region >= cpu->pmsav7_dregion) {
1818                 return;
1819             }
1820             cpu->env.pmsav8.rlar[attrs.secure][region] = value;
1821             tlb_flush(CPU(cpu));
1822             return;
1823         }
1824 
1825         if (region >= cpu->pmsav7_dregion) {
1826             return;
1827         }
1828 
1829         cpu->env.pmsav7.drsr[region] = value & 0xff3f;
1830         cpu->env.pmsav7.dracr[region] = (value >> 16) & 0x173f;
1831         tlb_flush(CPU(cpu));
1832         break;
1833     }
1834     case 0xdc0: /* MPU_MAIR0 */
1835         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1836             goto bad_offset;
1837         }
1838         if (cpu->pmsav7_dregion) {
1839             /* Register is RES0 if no MPU regions are implemented */
1840             cpu->env.pmsav8.mair0[attrs.secure] = value;
1841         }
1842         /* We don't need to do anything else because memory attributes
1843          * only affect cacheability, and we don't implement caching.
1844          */
1845         break;
1846     case 0xdc4: /* MPU_MAIR1 */
1847         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1848             goto bad_offset;
1849         }
1850         if (cpu->pmsav7_dregion) {
1851             /* Register is RES0 if no MPU regions are implemented */
1852             cpu->env.pmsav8.mair1[attrs.secure] = value;
1853         }
1854         /* We don't need to do anything else because memory attributes
1855          * only affect cacheability, and we don't implement caching.
1856          */
1857         break;
1858     case 0xdd0: /* SAU_CTRL */
1859         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1860             goto bad_offset;
1861         }
1862         if (!attrs.secure) {
1863             return;
1864         }
1865         cpu->env.sau.ctrl = value & 3;
1866         break;
1867     case 0xdd4: /* SAU_TYPE */
1868         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1869             goto bad_offset;
1870         }
1871         break;
1872     case 0xdd8: /* SAU_RNR */
1873         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1874             goto bad_offset;
1875         }
1876         if (!attrs.secure) {
1877             return;
1878         }
1879         if (value >= cpu->sau_sregion) {
1880             qemu_log_mask(LOG_GUEST_ERROR, "SAU region out of range %"
1881                           PRIu32 "/%" PRIu32 "\n",
1882                           value, cpu->sau_sregion);
1883         } else {
1884             cpu->env.sau.rnr = value;
1885         }
1886         break;
1887     case 0xddc: /* SAU_RBAR */
1888     {
1889         int region = cpu->env.sau.rnr;
1890 
1891         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1892             goto bad_offset;
1893         }
1894         if (!attrs.secure) {
1895             return;
1896         }
1897         if (region >= cpu->sau_sregion) {
1898             return;
1899         }
1900         cpu->env.sau.rbar[region] = value & ~0x1f;
1901         tlb_flush(CPU(cpu));
1902         break;
1903     }
1904     case 0xde0: /* SAU_RLAR */
1905     {
1906         int region = cpu->env.sau.rnr;
1907 
1908         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1909             goto bad_offset;
1910         }
1911         if (!attrs.secure) {
1912             return;
1913         }
1914         if (region >= cpu->sau_sregion) {
1915             return;
1916         }
1917         cpu->env.sau.rlar[region] = value & ~0x1c;
1918         tlb_flush(CPU(cpu));
1919         break;
1920     }
1921     case 0xde4: /* SFSR */
1922         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1923             goto bad_offset;
1924         }
1925         if (!attrs.secure) {
1926             return;
1927         }
1928         cpu->env.v7m.sfsr &= ~value; /* W1C */
1929         break;
1930     case 0xde8: /* SFAR */
1931         if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1932             goto bad_offset;
1933         }
1934         if (!attrs.secure) {
1935             return;
1936         }
1937         cpu->env.v7m.sfsr = value;
1938         break;
1939     case 0xf00: /* Software Triggered Interrupt Register */
1940     {
1941         int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;
1942 
1943         if (!arm_feature(&cpu->env, ARM_FEATURE_M_MAIN)) {
1944             goto bad_offset;
1945         }
1946 
1947         if (excnum < s->num_irq) {
1948             armv7m_nvic_set_pending(s, excnum, false);
1949         }
1950         break;
1951     }
1952     case 0xf34: /* FPCCR */
1953         if (arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
1954             /* Not all bits here are banked. */
1955             uint32_t fpccr_s;
1956 
1957             if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {
1958                 /* Don't allow setting of bits not present in v7M */
1959                 value &= (R_V7M_FPCCR_LSPACT_MASK |
1960                           R_V7M_FPCCR_USER_MASK |
1961                           R_V7M_FPCCR_THREAD_MASK |
1962                           R_V7M_FPCCR_HFRDY_MASK |
1963                           R_V7M_FPCCR_MMRDY_MASK |
1964                           R_V7M_FPCCR_BFRDY_MASK |
1965                           R_V7M_FPCCR_MONRDY_MASK |
1966                           R_V7M_FPCCR_LSPEN_MASK |
1967                           R_V7M_FPCCR_ASPEN_MASK);
1968             }
1969             value &= ~R_V7M_FPCCR_RES0_MASK;
1970 
1971             if (!attrs.secure) {
1972                 /* Some non-banked bits are configurably writable by NS */
1973                 fpccr_s = cpu->env.v7m.fpccr[M_REG_S];
1974                 if (!(fpccr_s & R_V7M_FPCCR_LSPENS_MASK)) {
1975                     uint32_t lspen = FIELD_EX32(value, V7M_FPCCR, LSPEN);
1976                     fpccr_s = FIELD_DP32(fpccr_s, V7M_FPCCR, LSPEN, lspen);
1977                 }
1978                 if (!(fpccr_s & R_V7M_FPCCR_CLRONRETS_MASK)) {
1979                     uint32_t cor = FIELD_EX32(value, V7M_FPCCR, CLRONRET);
1980                     fpccr_s = FIELD_DP32(fpccr_s, V7M_FPCCR, CLRONRET, cor);
1981                 }
1982                 if ((s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
1983                     uint32_t hfrdy = FIELD_EX32(value, V7M_FPCCR, HFRDY);
1984                     uint32_t bfrdy = FIELD_EX32(value, V7M_FPCCR, BFRDY);
1985                     fpccr_s = FIELD_DP32(fpccr_s, V7M_FPCCR, HFRDY, hfrdy);
1986                     fpccr_s = FIELD_DP32(fpccr_s, V7M_FPCCR, BFRDY, bfrdy);
1987                 }
1988                 /* TODO MONRDY should RAZ/WI if DEMCR.SDME is set */
1989                 {
1990                     uint32_t monrdy = FIELD_EX32(value, V7M_FPCCR, MONRDY);
1991                     fpccr_s = FIELD_DP32(fpccr_s, V7M_FPCCR, MONRDY, monrdy);
1992                 }
1993 
1994                 /*
1995                  * All other non-banked bits are RAZ/WI from NS; write
1996                  * just the banked bits to fpccr[M_REG_NS].
1997                  */
1998                 value &= R_V7M_FPCCR_BANKED_MASK;
1999                 cpu->env.v7m.fpccr[M_REG_NS] = value;
2000             } else {
2001                 fpccr_s = value;
2002             }
2003             cpu->env.v7m.fpccr[M_REG_S] = fpccr_s;
2004         }
2005         break;
2006     case 0xf38: /* FPCAR */
2007         if (arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
2008             value &= ~7;
2009             cpu->env.v7m.fpcar[attrs.secure] = value;
2010         }
2011         break;
2012     case 0xf3c: /* FPDSCR */
2013         if (arm_feature(&cpu->env, ARM_FEATURE_VFP)) {
2014             value &= 0x07c00000;
2015             cpu->env.v7m.fpdscr[attrs.secure] = value;
2016         }
2017         break;
2018     case 0xf50: /* ICIALLU */
2019     case 0xf58: /* ICIMVAU */
2020     case 0xf5c: /* DCIMVAC */
2021     case 0xf60: /* DCISW */
2022     case 0xf64: /* DCCMVAU */
2023     case 0xf68: /* DCCMVAC */
2024     case 0xf6c: /* DCCSW */
2025     case 0xf70: /* DCCIMVAC */
2026     case 0xf74: /* DCCISW */
2027     case 0xf78: /* BPIALL */
2028         /* Cache and branch predictor maintenance: for QEMU these always NOP */
2029         break;
2030     default:
2031     bad_offset:
2032         qemu_log_mask(LOG_GUEST_ERROR,
2033                       "NVIC: Bad write offset 0x%x\n", offset);
2034     }
2035 }
2036 
2037 static bool nvic_user_access_ok(NVICState *s, hwaddr offset, MemTxAttrs attrs)
2038 {
2039     /* Return true if unprivileged access to this register is permitted. */
2040     switch (offset) {
2041     case 0xf00: /* STIR: accessible only if CCR.USERSETMPEND permits */
2042         /* For access via STIR_NS it is the NS CCR.USERSETMPEND that
2043          * controls access even though the CPU is in Secure state (I_QDKX).
2044          */
2045         return s->cpu->env.v7m.ccr[attrs.secure] & R_V7M_CCR_USERSETMPEND_MASK;
2046     default:
2047         /* All other user accesses cause a BusFault unconditionally */
2048         return false;
2049     }
2050 }
2051 
2052 static int shpr_bank(NVICState *s, int exc, MemTxAttrs attrs)
2053 {
2054     /* Behaviour for the SHPR register field for this exception:
2055      * return M_REG_NS to use the nonsecure vector (including for
2056      * non-banked exceptions), M_REG_S for the secure version of
2057      * a banked exception, and -1 if this field should RAZ/WI.
2058      */
2059     switch (exc) {
2060     case ARMV7M_EXCP_MEM:
2061     case ARMV7M_EXCP_USAGE:
2062     case ARMV7M_EXCP_SVC:
2063     case ARMV7M_EXCP_PENDSV:
2064     case ARMV7M_EXCP_SYSTICK:
2065         /* Banked exceptions */
2066         return attrs.secure;
2067     case ARMV7M_EXCP_BUS:
2068         /* Not banked, RAZ/WI from nonsecure if BFHFNMINS is zero */
2069         if (!attrs.secure &&
2070             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
2071             return -1;
2072         }
2073         return M_REG_NS;
2074     case ARMV7M_EXCP_SECURE:
2075         /* Not banked, RAZ/WI from nonsecure */
2076         if (!attrs.secure) {
2077             return -1;
2078         }
2079         return M_REG_NS;
2080     case ARMV7M_EXCP_DEBUG:
2081         /* Not banked. TODO should RAZ/WI if DEMCR.SDME is set */
2082         return M_REG_NS;
2083     case 8 ... 10:
2084     case 13:
2085         /* RES0 */
2086         return -1;
2087     default:
2088         /* Not reachable due to decode of SHPR register addresses */
2089         g_assert_not_reached();
2090     }
2091 }
2092 
2093 static MemTxResult nvic_sysreg_read(void *opaque, hwaddr addr,
2094                                     uint64_t *data, unsigned size,
2095                                     MemTxAttrs attrs)
2096 {
2097     NVICState *s = (NVICState *)opaque;
2098     uint32_t offset = addr;
2099     unsigned i, startvec, end;
2100     uint32_t val;
2101 
2102     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
2103         /* Generate BusFault for unprivileged accesses */
2104         return MEMTX_ERROR;
2105     }
2106 
2107     switch (offset) {
2108     /* reads of set and clear both return the status */
2109     case 0x100 ... 0x13f: /* NVIC Set enable */
2110         offset += 0x80;
2111         /* fall through */
2112     case 0x180 ... 0x1bf: /* NVIC Clear enable */
2113         val = 0;
2114         startvec = 8 * (offset - 0x180) + NVIC_FIRST_IRQ; /* vector # */
2115 
2116         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
2117             if (s->vectors[startvec + i].enabled &&
2118                 (attrs.secure || s->itns[startvec + i])) {
2119                 val |= (1 << i);
2120             }
2121         }
2122         break;
2123     case 0x200 ... 0x23f: /* NVIC Set pend */
2124         offset += 0x80;
2125         /* fall through */
2126     case 0x280 ... 0x2bf: /* NVIC Clear pend */
2127         val = 0;
2128         startvec = 8 * (offset - 0x280) + NVIC_FIRST_IRQ; /* vector # */
2129         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
2130             if (s->vectors[startvec + i].pending &&
2131                 (attrs.secure || s->itns[startvec + i])) {
2132                 val |= (1 << i);
2133             }
2134         }
2135         break;
2136     case 0x300 ... 0x33f: /* NVIC Active */
2137         val = 0;
2138 
2139         if (!arm_feature(&s->cpu->env, ARM_FEATURE_V7)) {
2140             break;
2141         }
2142 
2143         startvec = 8 * (offset - 0x300) + NVIC_FIRST_IRQ; /* vector # */
2144 
2145         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
2146             if (s->vectors[startvec + i].active &&
2147                 (attrs.secure || s->itns[startvec + i])) {
2148                 val |= (1 << i);
2149             }
2150         }
2151         break;
2152     case 0x400 ... 0x5ef: /* NVIC Priority */
2153         val = 0;
2154         startvec = offset - 0x400 + NVIC_FIRST_IRQ; /* vector # */
2155 
2156         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
2157             if (attrs.secure || s->itns[startvec + i]) {
2158                 val |= s->vectors[startvec + i].prio << (8 * i);
2159             }
2160         }
2161         break;
2162     case 0xd18 ... 0xd1b: /* System Handler Priority (SHPR1) */
2163         if (!arm_feature(&s->cpu->env, ARM_FEATURE_M_MAIN)) {
2164             val = 0;
2165             break;
2166         }
2167         /* fall through */
2168     case 0xd1c ... 0xd23: /* System Handler Priority (SHPR2, SHPR3) */
2169         val = 0;
2170         for (i = 0; i < size; i++) {
2171             unsigned hdlidx = (offset - 0xd14) + i;
2172             int sbank = shpr_bank(s, hdlidx, attrs);
2173 
2174             if (sbank < 0) {
2175                 continue;
2176             }
2177             val = deposit32(val, i * 8, 8, get_prio(s, hdlidx, sbank));
2178         }
2179         break;
2180     case 0xd28 ... 0xd2b: /* Configurable Fault Status (CFSR) */
2181         if (!arm_feature(&s->cpu->env, ARM_FEATURE_M_MAIN)) {
2182             val = 0;
2183             break;
2184         };
2185         /*
2186          * The BFSR bits [15:8] are shared between security states
2187          * and we store them in the NS copy. They are RAZ/WI for
2188          * NS code if AIRCR.BFHFNMINS is 0.
2189          */
2190         val = s->cpu->env.v7m.cfsr[attrs.secure];
2191         if (!attrs.secure &&
2192             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
2193             val &= ~R_V7M_CFSR_BFSR_MASK;
2194         } else {
2195             val |= s->cpu->env.v7m.cfsr[M_REG_NS] & R_V7M_CFSR_BFSR_MASK;
2196         }
2197         val = extract32(val, (offset - 0xd28) * 8, size * 8);
2198         break;
2199     case 0xfe0 ... 0xfff: /* ID.  */
2200         if (offset & 3) {
2201             val = 0;
2202         } else {
2203             val = nvic_id[(offset - 0xfe0) >> 2];
2204         }
2205         break;
2206     default:
2207         if (size == 4) {
2208             val = nvic_readl(s, offset, attrs);
2209         } else {
2210             qemu_log_mask(LOG_GUEST_ERROR,
2211                           "NVIC: Bad read of size %d at offset 0x%x\n",
2212                           size, offset);
2213             val = 0;
2214         }
2215     }
2216 
2217     trace_nvic_sysreg_read(addr, val, size);
2218     *data = val;
2219     return MEMTX_OK;
2220 }
2221 
2222 static MemTxResult nvic_sysreg_write(void *opaque, hwaddr addr,
2223                                      uint64_t value, unsigned size,
2224                                      MemTxAttrs attrs)
2225 {
2226     NVICState *s = (NVICState *)opaque;
2227     uint32_t offset = addr;
2228     unsigned i, startvec, end;
2229     unsigned setval = 0;
2230 
2231     trace_nvic_sysreg_write(addr, value, size);
2232 
2233     if (attrs.user && !nvic_user_access_ok(s, addr, attrs)) {
2234         /* Generate BusFault for unprivileged accesses */
2235         return MEMTX_ERROR;
2236     }
2237 
2238     switch (offset) {
2239     case 0x100 ... 0x13f: /* NVIC Set enable */
2240         offset += 0x80;
2241         setval = 1;
2242         /* fall through */
2243     case 0x180 ... 0x1bf: /* NVIC Clear enable */
2244         startvec = 8 * (offset - 0x180) + NVIC_FIRST_IRQ;
2245 
2246         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
2247             if (value & (1 << i) &&
2248                 (attrs.secure || s->itns[startvec + i])) {
2249                 s->vectors[startvec + i].enabled = setval;
2250             }
2251         }
2252         nvic_irq_update(s);
2253         return MEMTX_OK;
2254     case 0x200 ... 0x23f: /* NVIC Set pend */
2255         /* the special logic in armv7m_nvic_set_pending()
2256          * is not needed since IRQs are never escalated
2257          */
2258         offset += 0x80;
2259         setval = 1;
2260         /* fall through */
2261     case 0x280 ... 0x2bf: /* NVIC Clear pend */
2262         startvec = 8 * (offset - 0x280) + NVIC_FIRST_IRQ; /* vector # */
2263 
2264         for (i = 0, end = size * 8; i < end && startvec + i < s->num_irq; i++) {
2265             if (value & (1 << i) &&
2266                 (attrs.secure || s->itns[startvec + i])) {
2267                 s->vectors[startvec + i].pending = setval;
2268             }
2269         }
2270         nvic_irq_update(s);
2271         return MEMTX_OK;
2272     case 0x300 ... 0x33f: /* NVIC Active */
2273         return MEMTX_OK; /* R/O */
2274     case 0x400 ... 0x5ef: /* NVIC Priority */
2275         startvec = (offset - 0x400) + NVIC_FIRST_IRQ; /* vector # */
2276 
2277         for (i = 0; i < size && startvec + i < s->num_irq; i++) {
2278             if (attrs.secure || s->itns[startvec + i]) {
2279                 set_prio(s, startvec + i, false, (value >> (i * 8)) & 0xff);
2280             }
2281         }
2282         nvic_irq_update(s);
2283         return MEMTX_OK;
2284     case 0xd18 ... 0xd1b: /* System Handler Priority (SHPR1) */
2285         if (!arm_feature(&s->cpu->env, ARM_FEATURE_M_MAIN)) {
2286             return MEMTX_OK;
2287         }
2288         /* fall through */
2289     case 0xd1c ... 0xd23: /* System Handler Priority (SHPR2, SHPR3) */
2290         for (i = 0; i < size; i++) {
2291             unsigned hdlidx = (offset - 0xd14) + i;
2292             int newprio = extract32(value, i * 8, 8);
2293             int sbank = shpr_bank(s, hdlidx, attrs);
2294 
2295             if (sbank < 0) {
2296                 continue;
2297             }
2298             set_prio(s, hdlidx, sbank, newprio);
2299         }
2300         nvic_irq_update(s);
2301         return MEMTX_OK;
2302     case 0xd28 ... 0xd2b: /* Configurable Fault Status (CFSR) */
2303         if (!arm_feature(&s->cpu->env, ARM_FEATURE_M_MAIN)) {
2304             return MEMTX_OK;
2305         }
2306         /* All bits are W1C, so construct 32 bit value with 0s in
2307          * the parts not written by the access size
2308          */
2309         value <<= ((offset - 0xd28) * 8);
2310 
2311         if (!attrs.secure &&
2312             !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK)) {
2313             /* BFSR bits are RAZ/WI for NS if BFHFNMINS is set */
2314             value &= ~R_V7M_CFSR_BFSR_MASK;
2315         }
2316 
2317         s->cpu->env.v7m.cfsr[attrs.secure] &= ~value;
2318         if (attrs.secure) {
2319             /* The BFSR bits [15:8] are shared between security states
2320              * and we store them in the NS copy.
2321              */
2322             s->cpu->env.v7m.cfsr[M_REG_NS] &= ~(value & R_V7M_CFSR_BFSR_MASK);
2323         }
2324         return MEMTX_OK;
2325     }
2326     if (size == 4) {
2327         nvic_writel(s, offset, value, attrs);
2328         return MEMTX_OK;
2329     }
2330     qemu_log_mask(LOG_GUEST_ERROR,
2331                   "NVIC: Bad write of size %d at offset 0x%x\n", size, offset);
2332     /* This is UNPREDICTABLE; treat as RAZ/WI */
2333     return MEMTX_OK;
2334 }
2335 
2336 static const MemoryRegionOps nvic_sysreg_ops = {
2337     .read_with_attrs = nvic_sysreg_read,
2338     .write_with_attrs = nvic_sysreg_write,
2339     .endianness = DEVICE_NATIVE_ENDIAN,
2340 };
2341 
2342 static MemTxResult nvic_sysreg_ns_write(void *opaque, hwaddr addr,
2343                                         uint64_t value, unsigned size,
2344                                         MemTxAttrs attrs)
2345 {
2346     MemoryRegion *mr = opaque;
2347 
2348     if (attrs.secure) {
2349         /* S accesses to the alias act like NS accesses to the real region */
2350         attrs.secure = 0;
2351         return memory_region_dispatch_write(mr, addr, value, size, attrs);
2352     } else {
2353         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
2354         if (attrs.user) {
2355             return MEMTX_ERROR;
2356         }
2357         return MEMTX_OK;
2358     }
2359 }
2360 
2361 static MemTxResult nvic_sysreg_ns_read(void *opaque, hwaddr addr,
2362                                        uint64_t *data, unsigned size,
2363                                        MemTxAttrs attrs)
2364 {
2365     MemoryRegion *mr = opaque;
2366 
2367     if (attrs.secure) {
2368         /* S accesses to the alias act like NS accesses to the real region */
2369         attrs.secure = 0;
2370         return memory_region_dispatch_read(mr, addr, data, size, attrs);
2371     } else {
2372         /* NS attrs are RAZ/WI for privileged, and BusFault for user */
2373         if (attrs.user) {
2374             return MEMTX_ERROR;
2375         }
2376         *data = 0;
2377         return MEMTX_OK;
2378     }
2379 }
2380 
2381 static const MemoryRegionOps nvic_sysreg_ns_ops = {
2382     .read_with_attrs = nvic_sysreg_ns_read,
2383     .write_with_attrs = nvic_sysreg_ns_write,
2384     .endianness = DEVICE_NATIVE_ENDIAN,
2385 };
2386 
2387 static MemTxResult nvic_systick_write(void *opaque, hwaddr addr,
2388                                       uint64_t value, unsigned size,
2389                                       MemTxAttrs attrs)
2390 {
2391     NVICState *s = opaque;
2392     MemoryRegion *mr;
2393 
2394     /* Direct the access to the correct systick */
2395     mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->systick[attrs.secure]), 0);
2396     return memory_region_dispatch_write(mr, addr, value, size, attrs);
2397 }
2398 
2399 static MemTxResult nvic_systick_read(void *opaque, hwaddr addr,
2400                                      uint64_t *data, unsigned size,
2401                                      MemTxAttrs attrs)
2402 {
2403     NVICState *s = opaque;
2404     MemoryRegion *mr;
2405 
2406     /* Direct the access to the correct systick */
2407     mr = sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->systick[attrs.secure]), 0);
2408     return memory_region_dispatch_read(mr, addr, data, size, attrs);
2409 }
2410 
2411 static const MemoryRegionOps nvic_systick_ops = {
2412     .read_with_attrs = nvic_systick_read,
2413     .write_with_attrs = nvic_systick_write,
2414     .endianness = DEVICE_NATIVE_ENDIAN,
2415 };
2416 
2417 static int nvic_post_load(void *opaque, int version_id)
2418 {
2419     NVICState *s = opaque;
2420     unsigned i;
2421     int resetprio;
2422 
2423     /* Check for out of range priority settings */
2424     resetprio = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? -4 : -3;
2425 
2426     if (s->vectors[ARMV7M_EXCP_RESET].prio != resetprio ||
2427         s->vectors[ARMV7M_EXCP_NMI].prio != -2 ||
2428         s->vectors[ARMV7M_EXCP_HARD].prio != -1) {
2429         return 1;
2430     }
2431     for (i = ARMV7M_EXCP_MEM; i < s->num_irq; i++) {
2432         if (s->vectors[i].prio & ~0xff) {
2433             return 1;
2434         }
2435     }
2436 
2437     nvic_recompute_state(s);
2438 
2439     return 0;
2440 }
2441 
2442 static const VMStateDescription vmstate_VecInfo = {
2443     .name = "armv7m_nvic_info",
2444     .version_id = 1,
2445     .minimum_version_id = 1,
2446     .fields = (VMStateField[]) {
2447         VMSTATE_INT16(prio, VecInfo),
2448         VMSTATE_UINT8(enabled, VecInfo),
2449         VMSTATE_UINT8(pending, VecInfo),
2450         VMSTATE_UINT8(active, VecInfo),
2451         VMSTATE_UINT8(level, VecInfo),
2452         VMSTATE_END_OF_LIST()
2453     }
2454 };
2455 
2456 static bool nvic_security_needed(void *opaque)
2457 {
2458     NVICState *s = opaque;
2459 
2460     return arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY);
2461 }
2462 
2463 static int nvic_security_post_load(void *opaque, int version_id)
2464 {
2465     NVICState *s = opaque;
2466     int i;
2467 
2468     /* Check for out of range priority settings */
2469     if (s->sec_vectors[ARMV7M_EXCP_HARD].prio != -1
2470         && s->sec_vectors[ARMV7M_EXCP_HARD].prio != -3) {
2471         /* We can't cross-check against AIRCR.BFHFNMINS as we don't know
2472          * if the CPU state has been migrated yet; a mismatch won't
2473          * cause the emulation to blow up, though.
2474          */
2475         return 1;
2476     }
2477     for (i = ARMV7M_EXCP_MEM; i < ARRAY_SIZE(s->sec_vectors); i++) {
2478         if (s->sec_vectors[i].prio & ~0xff) {
2479             return 1;
2480         }
2481     }
2482     return 0;
2483 }
2484 
2485 static const VMStateDescription vmstate_nvic_security = {
2486     .name = "armv7m_nvic/m-security",
2487     .version_id = 1,
2488     .minimum_version_id = 1,
2489     .needed = nvic_security_needed,
2490     .post_load = &nvic_security_post_load,
2491     .fields = (VMStateField[]) {
2492         VMSTATE_STRUCT_ARRAY(sec_vectors, NVICState, NVIC_INTERNAL_VECTORS, 1,
2493                              vmstate_VecInfo, VecInfo),
2494         VMSTATE_UINT32(prigroup[M_REG_S], NVICState),
2495         VMSTATE_BOOL_ARRAY(itns, NVICState, NVIC_MAX_VECTORS),
2496         VMSTATE_END_OF_LIST()
2497     }
2498 };
2499 
2500 static const VMStateDescription vmstate_nvic = {
2501     .name = "armv7m_nvic",
2502     .version_id = 4,
2503     .minimum_version_id = 4,
2504     .post_load = &nvic_post_load,
2505     .fields = (VMStateField[]) {
2506         VMSTATE_STRUCT_ARRAY(vectors, NVICState, NVIC_MAX_VECTORS, 1,
2507                              vmstate_VecInfo, VecInfo),
2508         VMSTATE_UINT32(prigroup[M_REG_NS], NVICState),
2509         VMSTATE_END_OF_LIST()
2510     },
2511     .subsections = (const VMStateDescription*[]) {
2512         &vmstate_nvic_security,
2513         NULL
2514     }
2515 };
2516 
2517 static Property props_nvic[] = {
2518     /* Number of external IRQ lines (so excluding the 16 internal exceptions) */
2519     DEFINE_PROP_UINT32("num-irq", NVICState, num_irq, 64),
2520     DEFINE_PROP_END_OF_LIST()
2521 };
2522 
2523 static void armv7m_nvic_reset(DeviceState *dev)
2524 {
2525     int resetprio;
2526     NVICState *s = NVIC(dev);
2527 
2528     memset(s->vectors, 0, sizeof(s->vectors));
2529     memset(s->sec_vectors, 0, sizeof(s->sec_vectors));
2530     s->prigroup[M_REG_NS] = 0;
2531     s->prigroup[M_REG_S] = 0;
2532 
2533     s->vectors[ARMV7M_EXCP_NMI].enabled = 1;
2534     /* MEM, BUS, and USAGE are enabled through
2535      * the System Handler Control register
2536      */
2537     s->vectors[ARMV7M_EXCP_SVC].enabled = 1;
2538     s->vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
2539     s->vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
2540 
2541     /* DebugMonitor is enabled via DEMCR.MON_EN */
2542     s->vectors[ARMV7M_EXCP_DEBUG].enabled = 0;
2543 
2544     resetprio = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? -4 : -3;
2545     s->vectors[ARMV7M_EXCP_RESET].prio = resetprio;
2546     s->vectors[ARMV7M_EXCP_NMI].prio = -2;
2547     s->vectors[ARMV7M_EXCP_HARD].prio = -1;
2548 
2549     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
2550         s->sec_vectors[ARMV7M_EXCP_HARD].enabled = 1;
2551         s->sec_vectors[ARMV7M_EXCP_SVC].enabled = 1;
2552         s->sec_vectors[ARMV7M_EXCP_PENDSV].enabled = 1;
2553         s->sec_vectors[ARMV7M_EXCP_SYSTICK].enabled = 1;
2554 
2555         /* AIRCR.BFHFNMINS resets to 0 so Secure HF is priority -1 (R_CMTC) */
2556         s->sec_vectors[ARMV7M_EXCP_HARD].prio = -1;
2557         /* If AIRCR.BFHFNMINS is 0 then NS HF is (effectively) disabled */
2558         s->vectors[ARMV7M_EXCP_HARD].enabled = 0;
2559     } else {
2560         s->vectors[ARMV7M_EXCP_HARD].enabled = 1;
2561     }
2562 
2563     /* Strictly speaking the reset handler should be enabled.
2564      * However, we don't simulate soft resets through the NVIC,
2565      * and the reset vector should never be pended.
2566      * So we leave it disabled to catch logic errors.
2567      */
2568 
2569     s->exception_prio = NVIC_NOEXC_PRIO;
2570     s->vectpending = 0;
2571     s->vectpending_is_s_banked = false;
2572     s->vectpending_prio = NVIC_NOEXC_PRIO;
2573 
2574     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
2575         memset(s->itns, 0, sizeof(s->itns));
2576     } else {
2577         /* This state is constant and not guest accessible in a non-security
2578          * NVIC; we set the bits to true to avoid having to do a feature
2579          * bit check in the NVIC enable/pend/etc register accessors.
2580          */
2581         int i;
2582 
2583         for (i = NVIC_FIRST_IRQ; i < ARRAY_SIZE(s->itns); i++) {
2584             s->itns[i] = true;
2585         }
2586     }
2587 }
2588 
2589 static void nvic_systick_trigger(void *opaque, int n, int level)
2590 {
2591     NVICState *s = opaque;
2592 
2593     if (level) {
2594         /* SysTick just asked us to pend its exception.
2595          * (This is different from an external interrupt line's
2596          * behaviour.)
2597          * n == 0 : NonSecure systick
2598          * n == 1 : Secure systick
2599          */
2600         armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK, n);
2601     }
2602 }
2603 
2604 static void armv7m_nvic_realize(DeviceState *dev, Error **errp)
2605 {
2606     NVICState *s = NVIC(dev);
2607     Error *err = NULL;
2608     int regionlen;
2609 
2610     /* The armv7m container object will have set our CPU pointer */
2611     if (!s->cpu || !arm_feature(&s->cpu->env, ARM_FEATURE_M)) {
2612         error_setg(errp, "The NVIC can only be used with a Cortex-M CPU");
2613         return;
2614     }
2615 
2616     if (s->num_irq > NVIC_MAX_IRQ) {
2617         error_setg(errp, "num-irq %d exceeds NVIC maximum", s->num_irq);
2618         return;
2619     }
2620 
2621     qdev_init_gpio_in(dev, set_irq_level, s->num_irq);
2622 
2623     /* include space for internal exception vectors */
2624     s->num_irq += NVIC_FIRST_IRQ;
2625 
2626     s->num_prio_bits = arm_feature(&s->cpu->env, ARM_FEATURE_V7) ? 8 : 2;
2627 
2628     object_property_set_bool(OBJECT(&s->systick[M_REG_NS]), true,
2629                              "realized", &err);
2630     if (err != NULL) {
2631         error_propagate(errp, err);
2632         return;
2633     }
2634     sysbus_connect_irq(SYS_BUS_DEVICE(&s->systick[M_REG_NS]), 0,
2635                        qdev_get_gpio_in_named(dev, "systick-trigger",
2636                                               M_REG_NS));
2637 
2638     if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY)) {
2639         /* We couldn't init the secure systick device in instance_init
2640          * as we didn't know then if the CPU had the security extensions;
2641          * so we have to do it here.
2642          */
2643         sysbus_init_child_obj(OBJECT(dev), "systick-reg-s",
2644                               &s->systick[M_REG_S],
2645                               sizeof(s->systick[M_REG_S]), TYPE_SYSTICK);
2646 
2647         object_property_set_bool(OBJECT(&s->systick[M_REG_S]), true,
2648                                  "realized", &err);
2649         if (err != NULL) {
2650             error_propagate(errp, err);
2651             return;
2652         }
2653         sysbus_connect_irq(SYS_BUS_DEVICE(&s->systick[M_REG_S]), 0,
2654                            qdev_get_gpio_in_named(dev, "systick-trigger",
2655                                                   M_REG_S));
2656     }
2657 
2658     /* The NVIC and System Control Space (SCS) starts at 0xe000e000
2659      * and looks like this:
2660      *  0x004 - ICTR
2661      *  0x010 - 0xff - systick
2662      *  0x100..0x7ec - NVIC
2663      *  0x7f0..0xcff - Reserved
2664      *  0xd00..0xd3c - SCS registers
2665      *  0xd40..0xeff - Reserved or Not implemented
2666      *  0xf00 - STIR
2667      *
2668      * Some registers within this space are banked between security states.
2669      * In v8M there is a second range 0xe002e000..0xe002efff which is the
2670      * NonSecure alias SCS; secure accesses to this behave like NS accesses
2671      * to the main SCS range, and non-secure accesses (including when
2672      * the security extension is not implemented) are RAZ/WI.
2673      * Note that both the main SCS range and the alias range are defined
2674      * to be exempt from memory attribution (R_BLJT) and so the memory
2675      * transaction attribute always matches the current CPU security
2676      * state (attrs.secure == env->v7m.secure). In the nvic_sysreg_ns_ops
2677      * wrappers we change attrs.secure to indicate the NS access; so
2678      * generally code determining which banked register to use should
2679      * use attrs.secure; code determining actual behaviour of the system
2680      * should use env->v7m.secure.
2681      */
2682     regionlen = arm_feature(&s->cpu->env, ARM_FEATURE_V8) ? 0x21000 : 0x1000;
2683     memory_region_init(&s->container, OBJECT(s), "nvic", regionlen);
2684     /* The system register region goes at the bottom of the priority
2685      * stack as it covers the whole page.
2686      */
2687     memory_region_init_io(&s->sysregmem, OBJECT(s), &nvic_sysreg_ops, s,
2688                           "nvic_sysregs", 0x1000);
2689     memory_region_add_subregion(&s->container, 0, &s->sysregmem);
2690 
2691     memory_region_init_io(&s->systickmem, OBJECT(s),
2692                           &nvic_systick_ops, s,
2693                           "nvic_systick", 0xe0);
2694 
2695     memory_region_add_subregion_overlap(&s->container, 0x10,
2696                                         &s->systickmem, 1);
2697 
2698     if (arm_feature(&s->cpu->env, ARM_FEATURE_V8)) {
2699         memory_region_init_io(&s->sysreg_ns_mem, OBJECT(s),
2700                               &nvic_sysreg_ns_ops, &s->sysregmem,
2701                               "nvic_sysregs_ns", 0x1000);
2702         memory_region_add_subregion(&s->container, 0x20000, &s->sysreg_ns_mem);
2703         memory_region_init_io(&s->systick_ns_mem, OBJECT(s),
2704                               &nvic_sysreg_ns_ops, &s->systickmem,
2705                               "nvic_systick_ns", 0xe0);
2706         memory_region_add_subregion_overlap(&s->container, 0x20010,
2707                                             &s->systick_ns_mem, 1);
2708     }
2709 
2710     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->container);
2711 }
2712 
2713 static void armv7m_nvic_instance_init(Object *obj)
2714 {
2715     /* We have a different default value for the num-irq property
2716      * than our superclass. This function runs after qdev init
2717      * has set the defaults from the Property array and before
2718      * any user-specified property setting, so just modify the
2719      * value in the GICState struct.
2720      */
2721     DeviceState *dev = DEVICE(obj);
2722     NVICState *nvic = NVIC(obj);
2723     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
2724 
2725     sysbus_init_child_obj(obj, "systick-reg-ns", &nvic->systick[M_REG_NS],
2726                           sizeof(nvic->systick[M_REG_NS]), TYPE_SYSTICK);
2727     /* We can't initialize the secure systick here, as we don't know
2728      * yet if we need it.
2729      */
2730 
2731     sysbus_init_irq(sbd, &nvic->excpout);
2732     qdev_init_gpio_out_named(dev, &nvic->sysresetreq, "SYSRESETREQ", 1);
2733     qdev_init_gpio_in_named(dev, nvic_systick_trigger, "systick-trigger",
2734                             M_REG_NUM_BANKS);
2735     qdev_init_gpio_in_named(dev, nvic_nmi_trigger, "NMI", 1);
2736 }
2737 
2738 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
2739 {
2740     DeviceClass *dc = DEVICE_CLASS(klass);
2741 
2742     dc->vmsd  = &vmstate_nvic;
2743     dc->props = props_nvic;
2744     dc->reset = armv7m_nvic_reset;
2745     dc->realize = armv7m_nvic_realize;
2746 }
2747 
2748 static const TypeInfo armv7m_nvic_info = {
2749     .name          = TYPE_NVIC,
2750     .parent        = TYPE_SYS_BUS_DEVICE,
2751     .instance_init = armv7m_nvic_instance_init,
2752     .instance_size = sizeof(NVICState),
2753     .class_init    = armv7m_nvic_class_init,
2754     .class_size    = sizeof(SysBusDeviceClass),
2755 };
2756 
2757 static void armv7m_nvic_register_types(void)
2758 {
2759     type_register_static(&armv7m_nvic_info);
2760 }
2761 
2762 type_init(armv7m_nvic_register_types)
2763