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