xref: /openbmc/qemu/hw/misc/tz-mpc.c (revision 6a0acfff)
1 /*
2  * ARM AHB5 TrustZone Memory Protection Controller emulation
3  *
4  * Copyright (c) 2018 Linaro Limited
5  * Written by Peter Maydell
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 or
9  * (at your option) any later version.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qemu/log.h"
14 #include "qemu/module.h"
15 #include "qapi/error.h"
16 #include "trace.h"
17 #include "hw/sysbus.h"
18 #include "hw/registerfields.h"
19 #include "hw/irq.h"
20 #include "hw/misc/tz-mpc.h"
21 
22 /* Our IOMMU has two IOMMU indexes, one for secure transactions and one for
23  * non-secure transactions.
24  */
25 enum {
26     IOMMU_IDX_S,
27     IOMMU_IDX_NS,
28     IOMMU_NUM_INDEXES,
29 };
30 
31 /* Config registers */
32 REG32(CTRL, 0x00)
33     FIELD(CTRL, SEC_RESP, 4, 1)
34     FIELD(CTRL, AUTOINC, 8, 1)
35     FIELD(CTRL, LOCKDOWN, 31, 1)
36 REG32(BLK_MAX, 0x10)
37 REG32(BLK_CFG, 0x14)
38 REG32(BLK_IDX, 0x18)
39 REG32(BLK_LUT, 0x1c)
40 REG32(INT_STAT, 0x20)
41     FIELD(INT_STAT, IRQ, 0, 1)
42 REG32(INT_CLEAR, 0x24)
43     FIELD(INT_CLEAR, IRQ, 0, 1)
44 REG32(INT_EN, 0x28)
45     FIELD(INT_EN, IRQ, 0, 1)
46 REG32(INT_INFO1, 0x2c)
47 REG32(INT_INFO2, 0x30)
48     FIELD(INT_INFO2, HMASTER, 0, 16)
49     FIELD(INT_INFO2, HNONSEC, 16, 1)
50     FIELD(INT_INFO2, CFG_NS, 17, 1)
51 REG32(INT_SET, 0x34)
52     FIELD(INT_SET, IRQ, 0, 1)
53 REG32(PIDR4, 0xfd0)
54 REG32(PIDR5, 0xfd4)
55 REG32(PIDR6, 0xfd8)
56 REG32(PIDR7, 0xfdc)
57 REG32(PIDR0, 0xfe0)
58 REG32(PIDR1, 0xfe4)
59 REG32(PIDR2, 0xfe8)
60 REG32(PIDR3, 0xfec)
61 REG32(CIDR0, 0xff0)
62 REG32(CIDR1, 0xff4)
63 REG32(CIDR2, 0xff8)
64 REG32(CIDR3, 0xffc)
65 
66 static const uint8_t tz_mpc_idregs[] = {
67     0x04, 0x00, 0x00, 0x00,
68     0x60, 0xb8, 0x1b, 0x00,
69     0x0d, 0xf0, 0x05, 0xb1,
70 };
71 
72 static void tz_mpc_irq_update(TZMPC *s)
73 {
74     qemu_set_irq(s->irq, s->int_stat && s->int_en);
75 }
76 
77 static void tz_mpc_iommu_notify(TZMPC *s, uint32_t lutidx,
78                                 uint32_t oldlut, uint32_t newlut)
79 {
80     /* Called when the LUT word at lutidx has changed from oldlut to newlut;
81      * must call the IOMMU notifiers for the changed blocks.
82      */
83     IOMMUTLBEntry entry = {
84         .addr_mask = s->blocksize - 1,
85     };
86     hwaddr addr = lutidx * s->blocksize * 32;
87     int i;
88 
89     for (i = 0; i < 32; i++, addr += s->blocksize) {
90         bool block_is_ns;
91 
92         if (!((oldlut ^ newlut) & (1 << i))) {
93             continue;
94         }
95         /* This changes the mappings for both the S and the NS space,
96          * so we need to do four notifies: an UNMAP then a MAP for each.
97          */
98         block_is_ns = newlut & (1 << i);
99 
100         trace_tz_mpc_iommu_notify(addr);
101         entry.iova = addr;
102         entry.translated_addr = addr;
103 
104         entry.perm = IOMMU_NONE;
105         memory_region_notify_iommu(&s->upstream, IOMMU_IDX_S, entry);
106         memory_region_notify_iommu(&s->upstream, IOMMU_IDX_NS, entry);
107 
108         entry.perm = IOMMU_RW;
109         if (block_is_ns) {
110             entry.target_as = &s->blocked_io_as;
111         } else {
112             entry.target_as = &s->downstream_as;
113         }
114         memory_region_notify_iommu(&s->upstream, IOMMU_IDX_S, entry);
115         if (block_is_ns) {
116             entry.target_as = &s->downstream_as;
117         } else {
118             entry.target_as = &s->blocked_io_as;
119         }
120         memory_region_notify_iommu(&s->upstream, IOMMU_IDX_NS, entry);
121     }
122 }
123 
124 static void tz_mpc_autoinc_idx(TZMPC *s, unsigned access_size)
125 {
126     /* Auto-increment BLK_IDX if necessary */
127     if (access_size == 4 && (s->ctrl & R_CTRL_AUTOINC_MASK)) {
128         s->blk_idx++;
129         s->blk_idx %= s->blk_max;
130     }
131 }
132 
133 static MemTxResult tz_mpc_reg_read(void *opaque, hwaddr addr,
134                                    uint64_t *pdata,
135                                    unsigned size, MemTxAttrs attrs)
136 {
137     TZMPC *s = TZ_MPC(opaque);
138     uint64_t r;
139     uint32_t offset = addr & ~0x3;
140 
141     if (!attrs.secure && offset < A_PIDR4) {
142         /* NS accesses can only see the ID registers */
143         qemu_log_mask(LOG_GUEST_ERROR,
144                       "TZ MPC register read: NS access to offset 0x%x\n",
145                       offset);
146         r = 0;
147         goto read_out;
148     }
149 
150     switch (offset) {
151     case A_CTRL:
152         r = s->ctrl;
153         break;
154     case A_BLK_MAX:
155         r = s->blk_max - 1;
156         break;
157     case A_BLK_CFG:
158         /* We are never in "init in progress state", so this just indicates
159          * the block size. s->blocksize == (1 << BLK_CFG + 5), so
160          * BLK_CFG == ctz32(s->blocksize) - 5
161          */
162         r = ctz32(s->blocksize) - 5;
163         break;
164     case A_BLK_IDX:
165         r = s->blk_idx;
166         break;
167     case A_BLK_LUT:
168         r = s->blk_lut[s->blk_idx];
169         tz_mpc_autoinc_idx(s, size);
170         break;
171     case A_INT_STAT:
172         r = s->int_stat;
173         break;
174     case A_INT_EN:
175         r = s->int_en;
176         break;
177     case A_INT_INFO1:
178         r = s->int_info1;
179         break;
180     case A_INT_INFO2:
181         r = s->int_info2;
182         break;
183     case A_PIDR4:
184     case A_PIDR5:
185     case A_PIDR6:
186     case A_PIDR7:
187     case A_PIDR0:
188     case A_PIDR1:
189     case A_PIDR2:
190     case A_PIDR3:
191     case A_CIDR0:
192     case A_CIDR1:
193     case A_CIDR2:
194     case A_CIDR3:
195         r = tz_mpc_idregs[(offset - A_PIDR4) / 4];
196         break;
197     case A_INT_CLEAR:
198     case A_INT_SET:
199         qemu_log_mask(LOG_GUEST_ERROR,
200                       "TZ MPC register read: write-only offset 0x%x\n",
201                       offset);
202         r = 0;
203         break;
204     default:
205         qemu_log_mask(LOG_GUEST_ERROR,
206                       "TZ MPC register read: bad offset 0x%x\n", offset);
207         r = 0;
208         break;
209     }
210 
211     if (size != 4) {
212         /* None of our registers are read-sensitive (except BLK_LUT,
213          * which can special case the "size not 4" case), so just
214          * pull the right bytes out of the word read result.
215          */
216         r = extract32(r, (addr & 3) * 8, size * 8);
217     }
218 
219 read_out:
220     trace_tz_mpc_reg_read(addr, r, size);
221     *pdata = r;
222     return MEMTX_OK;
223 }
224 
225 static MemTxResult tz_mpc_reg_write(void *opaque, hwaddr addr,
226                                     uint64_t value,
227                                     unsigned size, MemTxAttrs attrs)
228 {
229     TZMPC *s = TZ_MPC(opaque);
230     uint32_t offset = addr & ~0x3;
231 
232     trace_tz_mpc_reg_write(addr, value, size);
233 
234     if (!attrs.secure && offset < A_PIDR4) {
235         /* NS accesses can only see the ID registers */
236         qemu_log_mask(LOG_GUEST_ERROR,
237                       "TZ MPC register write: NS access to offset 0x%x\n",
238                       offset);
239         return MEMTX_OK;
240     }
241 
242     if (size != 4) {
243         /* Expand the byte or halfword write to a full word size.
244          * In most cases we can do this with zeroes; the exceptions
245          * are CTRL, BLK_IDX and BLK_LUT.
246          */
247         uint32_t oldval;
248 
249         switch (offset) {
250         case A_CTRL:
251             oldval = s->ctrl;
252             break;
253         case A_BLK_IDX:
254             oldval = s->blk_idx;
255             break;
256         case A_BLK_LUT:
257             oldval = s->blk_lut[s->blk_idx];
258             break;
259         default:
260             oldval = 0;
261             break;
262         }
263         value = deposit32(oldval, (addr & 3) * 8, size * 8, value);
264     }
265 
266     if ((s->ctrl & R_CTRL_LOCKDOWN_MASK) &&
267         (offset == A_CTRL || offset == A_BLK_LUT || offset == A_INT_EN)) {
268         /* Lockdown mode makes these three registers read-only, and
269          * the only way out of it is to reset the device.
270          */
271         qemu_log_mask(LOG_GUEST_ERROR, "TZ MPC register write to offset 0x%x "
272                       "while MPC is in lockdown mode\n", offset);
273         return MEMTX_OK;
274     }
275 
276     switch (offset) {
277     case A_CTRL:
278         /* We don't implement the 'data gating' feature so all other bits
279          * are reserved and we make them RAZ/WI.
280          */
281         s->ctrl = value & (R_CTRL_SEC_RESP_MASK |
282                            R_CTRL_AUTOINC_MASK |
283                            R_CTRL_LOCKDOWN_MASK);
284         break;
285     case A_BLK_IDX:
286         s->blk_idx = value % s->blk_max;
287         break;
288     case A_BLK_LUT:
289         tz_mpc_iommu_notify(s, s->blk_idx, s->blk_lut[s->blk_idx], value);
290         s->blk_lut[s->blk_idx] = value;
291         tz_mpc_autoinc_idx(s, size);
292         break;
293     case A_INT_CLEAR:
294         if (value & R_INT_CLEAR_IRQ_MASK) {
295             s->int_stat = 0;
296             tz_mpc_irq_update(s);
297         }
298         break;
299     case A_INT_EN:
300         s->int_en = value & R_INT_EN_IRQ_MASK;
301         tz_mpc_irq_update(s);
302         break;
303     case A_INT_SET:
304         if (value & R_INT_SET_IRQ_MASK) {
305             s->int_stat = R_INT_STAT_IRQ_MASK;
306             tz_mpc_irq_update(s);
307         }
308         break;
309     case A_PIDR4:
310     case A_PIDR5:
311     case A_PIDR6:
312     case A_PIDR7:
313     case A_PIDR0:
314     case A_PIDR1:
315     case A_PIDR2:
316     case A_PIDR3:
317     case A_CIDR0:
318     case A_CIDR1:
319     case A_CIDR2:
320     case A_CIDR3:
321         qemu_log_mask(LOG_GUEST_ERROR,
322                       "TZ MPC register write: read-only offset 0x%x\n", offset);
323         break;
324     default:
325         qemu_log_mask(LOG_GUEST_ERROR,
326                       "TZ MPC register write: bad offset 0x%x\n", offset);
327         break;
328     }
329 
330     return MEMTX_OK;
331 }
332 
333 static const MemoryRegionOps tz_mpc_reg_ops = {
334     .read_with_attrs = tz_mpc_reg_read,
335     .write_with_attrs = tz_mpc_reg_write,
336     .endianness = DEVICE_LITTLE_ENDIAN,
337     .valid.min_access_size = 1,
338     .valid.max_access_size = 4,
339     .impl.min_access_size = 1,
340     .impl.max_access_size = 4,
341 };
342 
343 static inline bool tz_mpc_cfg_ns(TZMPC *s, hwaddr addr)
344 {
345     /* Return the cfg_ns bit from the LUT for the specified address */
346     hwaddr blknum = addr / s->blocksize;
347     hwaddr blkword = blknum / 32;
348     uint32_t blkbit = 1U << (blknum % 32);
349 
350     /* This would imply the address was larger than the size we
351      * defined this memory region to be, so it can't happen.
352      */
353     assert(blkword < s->blk_max);
354     return s->blk_lut[blkword] & blkbit;
355 }
356 
357 static MemTxResult tz_mpc_handle_block(TZMPC *s, hwaddr addr, MemTxAttrs attrs)
358 {
359     /* Handle a blocked transaction: raise IRQ, capture info, etc */
360     if (!s->int_stat) {
361         /* First blocked transfer: capture information into INT_INFO1 and
362          * INT_INFO2. Subsequent transfers are still blocked but don't
363          * capture information until the guest clears the interrupt.
364          */
365 
366         s->int_info1 = addr;
367         s->int_info2 = 0;
368         s->int_info2 = FIELD_DP32(s->int_info2, INT_INFO2, HMASTER,
369                                   attrs.requester_id & 0xffff);
370         s->int_info2 = FIELD_DP32(s->int_info2, INT_INFO2, HNONSEC,
371                                   ~attrs.secure);
372         s->int_info2 = FIELD_DP32(s->int_info2, INT_INFO2, CFG_NS,
373                                   tz_mpc_cfg_ns(s, addr));
374         s->int_stat |= R_INT_STAT_IRQ_MASK;
375         tz_mpc_irq_update(s);
376     }
377 
378     /* Generate bus error if desired; otherwise RAZ/WI */
379     return (s->ctrl & R_CTRL_SEC_RESP_MASK) ? MEMTX_ERROR : MEMTX_OK;
380 }
381 
382 /* Accesses only reach these read and write functions if the MPC is
383  * blocking them; non-blocked accesses go directly to the downstream
384  * memory region without passing through this code.
385  */
386 static MemTxResult tz_mpc_mem_blocked_read(void *opaque, hwaddr addr,
387                                            uint64_t *pdata,
388                                            unsigned size, MemTxAttrs attrs)
389 {
390     TZMPC *s = TZ_MPC(opaque);
391 
392     trace_tz_mpc_mem_blocked_read(addr, size, attrs.secure);
393 
394     *pdata = 0;
395     return tz_mpc_handle_block(s, addr, attrs);
396 }
397 
398 static MemTxResult tz_mpc_mem_blocked_write(void *opaque, hwaddr addr,
399                                             uint64_t value,
400                                             unsigned size, MemTxAttrs attrs)
401 {
402     TZMPC *s = TZ_MPC(opaque);
403 
404     trace_tz_mpc_mem_blocked_write(addr, value, size, attrs.secure);
405 
406     return tz_mpc_handle_block(s, addr, attrs);
407 }
408 
409 static const MemoryRegionOps tz_mpc_mem_blocked_ops = {
410     .read_with_attrs = tz_mpc_mem_blocked_read,
411     .write_with_attrs = tz_mpc_mem_blocked_write,
412     .endianness = DEVICE_LITTLE_ENDIAN,
413     .valid.min_access_size = 1,
414     .valid.max_access_size = 8,
415     .impl.min_access_size = 1,
416     .impl.max_access_size = 8,
417 };
418 
419 static IOMMUTLBEntry tz_mpc_translate(IOMMUMemoryRegion *iommu,
420                                       hwaddr addr, IOMMUAccessFlags flags,
421                                       int iommu_idx)
422 {
423     TZMPC *s = TZ_MPC(container_of(iommu, TZMPC, upstream));
424     bool ok;
425 
426     IOMMUTLBEntry ret = {
427         .iova = addr & ~(s->blocksize - 1),
428         .translated_addr = addr & ~(s->blocksize - 1),
429         .addr_mask = s->blocksize - 1,
430         .perm = IOMMU_RW,
431     };
432 
433     /* Look at the per-block configuration for this address, and
434      * return a TLB entry directing the transaction at either
435      * downstream_as or blocked_io_as, as appropriate.
436      * If the LUT cfg_ns bit is 1, only non-secure transactions
437      * may pass. If the bit is 0, only secure transactions may pass.
438      */
439     ok = tz_mpc_cfg_ns(s, addr) == (iommu_idx == IOMMU_IDX_NS);
440 
441     trace_tz_mpc_translate(addr, flags,
442                            iommu_idx == IOMMU_IDX_S ? "S" : "NS",
443                            ok ? "pass" : "block");
444 
445     ret.target_as = ok ? &s->downstream_as : &s->blocked_io_as;
446     return ret;
447 }
448 
449 static int tz_mpc_attrs_to_index(IOMMUMemoryRegion *iommu, MemTxAttrs attrs)
450 {
451     /* We treat unspecified attributes like secure. Transactions with
452      * unspecified attributes come from places like
453      * rom_reset() for initial image load, and we want
454      * those to pass through the from-reset "everything is secure" config.
455      * All the real during-emulation transactions from the CPU will
456      * specify attributes.
457      */
458     return (attrs.unspecified || attrs.secure) ? IOMMU_IDX_S : IOMMU_IDX_NS;
459 }
460 
461 static int tz_mpc_num_indexes(IOMMUMemoryRegion *iommu)
462 {
463     return IOMMU_NUM_INDEXES;
464 }
465 
466 static void tz_mpc_reset(DeviceState *dev)
467 {
468     TZMPC *s = TZ_MPC(dev);
469 
470     s->ctrl = 0x00000100;
471     s->blk_idx = 0;
472     s->int_stat = 0;
473     s->int_en = 1;
474     s->int_info1 = 0;
475     s->int_info2 = 0;
476 
477     memset(s->blk_lut, 0, s->blk_max * sizeof(uint32_t));
478 }
479 
480 static void tz_mpc_init(Object *obj)
481 {
482     DeviceState *dev = DEVICE(obj);
483     TZMPC *s = TZ_MPC(obj);
484 
485     qdev_init_gpio_out_named(dev, &s->irq, "irq", 1);
486 }
487 
488 static void tz_mpc_realize(DeviceState *dev, Error **errp)
489 {
490     Object *obj = OBJECT(dev);
491     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
492     TZMPC *s = TZ_MPC(dev);
493     uint64_t size;
494 
495     /* We can't create the upstream end of the port until realize,
496      * as we don't know the size of the MR used as the downstream until then.
497      * We insist on having a downstream, to avoid complicating the code
498      * with handling the "don't know how big this is" case. It's easy
499      * enough for the user to create an unimplemented_device as downstream
500      * if they have nothing else to plug into this.
501      */
502     if (!s->downstream) {
503         error_setg(errp, "MPC 'downstream' link not set");
504         return;
505     }
506 
507     size = memory_region_size(s->downstream);
508 
509     memory_region_init_iommu(&s->upstream, sizeof(s->upstream),
510                              TYPE_TZ_MPC_IOMMU_MEMORY_REGION,
511                              obj, "tz-mpc-upstream", size);
512 
513     /* In real hardware the block size is configurable. In QEMU we could
514      * make it configurable but will need it to be at least as big as the
515      * target page size so we can execute out of the resulting MRs. Guest
516      * software is supposed to check the block size using the BLK_CFG
517      * register, so make it fixed at the page size.
518      */
519     s->blocksize = memory_region_iommu_get_min_page_size(&s->upstream);
520     if (size % s->blocksize != 0) {
521         error_setg(errp,
522                    "MPC 'downstream' size %" PRId64
523                    " is not a multiple of %" HWADDR_PRIx " bytes",
524                    size, s->blocksize);
525         object_unref(OBJECT(&s->upstream));
526         return;
527     }
528 
529     /* BLK_MAX is the max value of BLK_IDX, which indexes an array of 32-bit
530      * words, each bit of which indicates one block.
531      */
532     s->blk_max = DIV_ROUND_UP(size / s->blocksize, 32);
533 
534     memory_region_init_io(&s->regmr, obj, &tz_mpc_reg_ops,
535                           s, "tz-mpc-regs", 0x1000);
536     sysbus_init_mmio(sbd, &s->regmr);
537 
538     sysbus_init_mmio(sbd, MEMORY_REGION(&s->upstream));
539 
540     /* This memory region is not exposed to users of this device as a
541      * sysbus MMIO region, but is instead used internally as something
542      * that our IOMMU translate function might direct accesses to.
543      */
544     memory_region_init_io(&s->blocked_io, obj, &tz_mpc_mem_blocked_ops,
545                           s, "tz-mpc-blocked-io", size);
546 
547     address_space_init(&s->downstream_as, s->downstream,
548                        "tz-mpc-downstream");
549     address_space_init(&s->blocked_io_as, &s->blocked_io,
550                        "tz-mpc-blocked-io");
551 
552     s->blk_lut = g_new0(uint32_t, s->blk_max);
553 }
554 
555 static int tz_mpc_post_load(void *opaque, int version_id)
556 {
557     TZMPC *s = TZ_MPC(opaque);
558 
559     /* Check the incoming data doesn't point blk_idx off the end of blk_lut. */
560     if (s->blk_idx >= s->blk_max) {
561         return -1;
562     }
563     return 0;
564 }
565 
566 static const VMStateDescription tz_mpc_vmstate = {
567     .name = "tz-mpc",
568     .version_id = 1,
569     .minimum_version_id = 1,
570     .post_load = tz_mpc_post_load,
571     .fields = (VMStateField[]) {
572         VMSTATE_UINT32(ctrl, TZMPC),
573         VMSTATE_UINT32(blk_idx, TZMPC),
574         VMSTATE_UINT32(int_stat, TZMPC),
575         VMSTATE_UINT32(int_en, TZMPC),
576         VMSTATE_UINT32(int_info1, TZMPC),
577         VMSTATE_UINT32(int_info2, TZMPC),
578         VMSTATE_VARRAY_UINT32(blk_lut, TZMPC, blk_max,
579                               0, vmstate_info_uint32, uint32_t),
580         VMSTATE_END_OF_LIST()
581     }
582 };
583 
584 static Property tz_mpc_properties[] = {
585     DEFINE_PROP_LINK("downstream", TZMPC, downstream,
586                      TYPE_MEMORY_REGION, MemoryRegion *),
587     DEFINE_PROP_END_OF_LIST(),
588 };
589 
590 static void tz_mpc_class_init(ObjectClass *klass, void *data)
591 {
592     DeviceClass *dc = DEVICE_CLASS(klass);
593 
594     dc->realize = tz_mpc_realize;
595     dc->vmsd = &tz_mpc_vmstate;
596     dc->reset = tz_mpc_reset;
597     dc->props = tz_mpc_properties;
598 }
599 
600 static const TypeInfo tz_mpc_info = {
601     .name = TYPE_TZ_MPC,
602     .parent = TYPE_SYS_BUS_DEVICE,
603     .instance_size = sizeof(TZMPC),
604     .instance_init = tz_mpc_init,
605     .class_init = tz_mpc_class_init,
606 };
607 
608 static void tz_mpc_iommu_memory_region_class_init(ObjectClass *klass,
609                                                   void *data)
610 {
611     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
612 
613     imrc->translate = tz_mpc_translate;
614     imrc->attrs_to_index = tz_mpc_attrs_to_index;
615     imrc->num_indexes = tz_mpc_num_indexes;
616 }
617 
618 static const TypeInfo tz_mpc_iommu_memory_region_info = {
619     .name = TYPE_TZ_MPC_IOMMU_MEMORY_REGION,
620     .parent = TYPE_IOMMU_MEMORY_REGION,
621     .class_init = tz_mpc_iommu_memory_region_class_init,
622 };
623 
624 static void tz_mpc_register_types(void)
625 {
626     type_register_static(&tz_mpc_info);
627     type_register_static(&tz_mpc_iommu_memory_region_info);
628 }
629 
630 type_init(tz_mpc_register_types);
631