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