]> rtime.felk.cvut.cz Git - jailhouse.git/blob - hypervisor/arch/x86/vtd.c
x86: Factor out iommu_select_fault_reporting_cpu
[jailhouse.git] / hypervisor / arch / x86 / vtd.c
1 /*
2  * Jailhouse, a Linux-based partitioning hypervisor
3  *
4  * Copyright (c) Siemens AG, 2013-2016
5  * Copyright (c) Valentine Sinitsyn, 2014
6  *
7  * Authors:
8  *  Jan Kiszka <jan.kiszka@siemens.com>
9  *  Valentine Sinitsyn <valentine.sinitsyn@gmail.com>
10  *
11  * This work is licensed under the terms of the GNU GPL, version 2.  See
12  * the COPYING file in the top-level directory.
13  */
14
15 #include <jailhouse/control.h>
16 #include <jailhouse/mmio.h>
17 #include <jailhouse/paging.h>
18 #include <jailhouse/pci.h>
19 #include <jailhouse/printk.h>
20 #include <jailhouse/string.h>
21 #include <asm/apic.h>
22 #include <asm/iommu.h>
23 #include <asm/bitops.h>
24 #include <asm/ioapic.h>
25 #include <asm/spinlock.h>
26
27 #define VTD_ROOT_PRESENT                0x00000001
28
29 #define VTD_CTX_PRESENT                 0x00000001
30 #define VTD_CTX_TTYPE_MLP_UNTRANS       0x00000000
31
32 #define VTD_CTX_AGAW_39                 0x00000001
33 #define VTD_CTX_AGAW_48                 0x00000002
34 #define VTD_CTX_DID_SHIFT               8
35
36 struct vtd_entry {
37         u64 lo_word;
38         u64 hi_word;
39 };
40
41 #define VTD_PAGE_READ                   0x00000001
42 #define VTD_PAGE_WRITE                  0x00000002
43
44 #define VTD_MAX_PAGE_TABLE_LEVELS       4
45
46 #define VTD_VER_REG                     0x00
47 # define VTD_VER_MASK                   BIT_MASK(7, 0)
48 # define VTD_VER_MIN                    0x10
49 #define VTD_CAP_REG                     0x08
50 # define VTD_CAP_NUM_DID_MASK           BIT_MASK(2, 0)
51 # define VTD_CAP_CM                     (1UL << 7)
52 # define VTD_CAP_SAGAW39                (1UL << 9)
53 # define VTD_CAP_SAGAW48                (1UL << 10)
54 # define VTD_CAP_SLLPS2M                (1UL << 34)
55 # define VTD_CAP_SLLPS1G                (1UL << 35)
56 # define VTD_CAP_FRO_MASK               BIT_MASK(33, 24)
57 # define VTD_CAP_NFR_MASK               BIT_MASK(47, 40)
58 #define VTD_ECAP_REG                    0x10
59 # define VTD_ECAP_QI                    (1UL << 1)
60 # define VTD_ECAP_IR                    (1UL << 3)
61 # define VTD_ECAP_EIM                   (1UL << 4)
62 #define VTD_GCMD_REG                    0x18
63 # define VTD_GCMD_SIRTP                 (1UL << 24)
64 # define VTD_GCMD_IRE                   (1UL << 25)
65 # define VTD_GCMD_QIE                   (1UL << 26)
66 # define VTD_GCMD_SRTP                  (1UL << 30)
67 # define VTD_GCMD_TE                    (1UL << 31)
68 #define VTD_GSTS_REG                    0x1c
69 # define VTD_GSTS_IRES                  (1UL << 25)
70 # define VTD_GSTS_QIES                  (1UL << 26)
71 # define VTD_GSTS_TES                   (1UL << 31)
72 # define VTD_GSTS_USED_CTRLS \
73         (VTD_GSTS_IRES | VTD_GSTS_QIES | VTD_GSTS_TES)
74 #define VTD_RTADDR_REG                  0x20
75 #define VTD_FSTS_REG                    0x34
76 # define VTD_FSTS_PFO                   (1UL << 0)
77 # define VTD_FSTS_PFO_CLEAR             1
78 # define VTD_FSTS_PPF                   (1UL << 1)
79 # define VTD_FSTS_FRI_MASK              BIT_MASK(15, 8)
80 #define VTD_FECTL_REG                   0x38
81 #define  VTD_FECTL_IM                   (1UL << 31)
82 #define VTD_FEDATA_REG                  0x3c
83 #define VTD_FEADDR_REG                  0x40
84 #define VTD_FEUADDR_REG                 0x44
85 #define VTD_IQH_REG                     0x80
86 # define VTD_IQH_QH_SHIFT               4
87 #define VTD_IQT_REG                     0x88
88 # define VTD_IQT_QT_MASK                BIT_MASK(18, 4)
89 #define VTD_IQA_REG                     0x90
90 # define VTD_IQA_ADDR_MASK              BIT_MASK(63, 12)
91 #define VTD_IRTA_REG                    0xb8
92 # define VTD_IRTA_SIZE_MASK             BIT_MASK(3, 0)
93 # define VTD_IRTA_EIME                  (1UL << 11)
94 # define VTD_IRTA_ADDR_MASK             BIT_MASK(63, 12)
95
96 #define VTD_REQ_INV_MASK                BIT_MASK(3, 0)
97
98 #define VTD_REQ_INV_CONTEXT             0x01
99 # define VTD_INV_CONTEXT_GLOBAL         (1UL << 4)
100 # define VTD_INV_CONTEXT_DOMAIN         (2UL << 4)
101 # define VTD_INV_CONTEXT_DOMAIN_SHIFT   16
102
103 #define VTD_REQ_INV_IOTLB               0x02
104 # define VTD_INV_IOTLB_GLOBAL           (1UL << 4)
105 # define VTD_INV_IOTLB_DOMAIN           (2UL << 4)
106 # define VTD_INV_IOTLB_DW               (1UL << 6)
107 # define VTD_INV_IOTLB_DR               (1UL << 7)
108 # define VTD_INV_IOTLB_DOMAIN_SHIFT     16
109
110 #define VTD_REQ_INV_INT                 0x04
111 # define VTD_INV_INT_GLOBAL             (0UL << 4)
112 # define VTD_INV_INT_INDEX              (1UL << 4)
113 # define VTD_INV_INT_IM_MASK            BIT_MASK(31, 27)
114 # define VTD_INV_INT_IM_SHIFT           27
115 # define VTD_INV_INT_IIDX_MASK          BIT_MASK(47, 32)
116 # define VTD_INV_INT_IIDX_SHIFT         32
117
118 #define VTD_REQ_INV_WAIT                0x05
119 #define  VTD_INV_WAIT_IF                (1UL << 4)
120 #define  VTD_INV_WAIT_SW                (1UL << 5)
121 #define  VTD_INV_WAIT_FN                (1UL << 6)
122 #define  VTD_INV_WAIT_SDATA_SHIFT       32
123
124 #define VTD_FRCD_LO_REG                 0x0
125 #define  VTD_FRCD_LO_FI_MASK            BIT_MASK(63, 12)
126 #define VTD_FRCD_HI_REG                 0x8
127 #define  VTD_FRCD_HI_SID_MASK           BIT_MASK(79-64, 64-64)
128 #define  VTD_FRCD_HI_FR_MASK            BIT_MASK(103-64, 96-64)
129 #define  VTD_FRCD_HI_TYPE               (1L << (126-64))
130 #define  VTD_FRCD_HI_F                  (1L << (127-64))
131 #define  VTD_FRCD_HI_F_CLEAR            1
132
133 union vtd_irte {
134         struct {
135                 u8 p:1;
136                 u8 fpd:1;
137                 u8 dest_logical:1;
138                 u8 redir_hint:1;
139                 u8 level_triggered:1;
140                 u8 delivery_mode:3;
141                 u8 assigned:1;
142                 u8 reserved:7;
143                 u8 vector;
144                 u8 reserved2;
145                 u32 destination;
146                 u16 sid;
147                 u16 sq:2;
148                 u16 svt:2;
149                 u16 reserved3:12;
150                 u32 reserved4;
151         } __attribute__((packed)) field;
152         u64 raw[2];
153 } __attribute__((packed));
154
155 #define VTD_IRTE_SQ_VERIFY_FULL_SID     0x0
156 #define VTD_IRTE_SVT_VERIFY_SID_SQ      0x1
157
158 /* A unit can occupy up to 3 pages for registers, we reserve 4. */
159 #define DMAR_MMIO_SIZE                  (PAGE_SIZE * 4)
160
161 struct vtd_irte_usage {
162         u16 device_id;
163         u16 vector:10,
164             used:1;
165 } __attribute__((packed));
166
167 struct vtd_emulation {
168         u64 irta;
169         unsigned int irt_entries;
170         struct vtd_irte_usage *irte_map;
171
172         u64 iqa;
173         u16 iqh;
174
175         u32 fectl;
176         u32 fedata;
177         u32 feaddr, feuaddr;
178 };
179
180 static const struct vtd_entry inv_global_context = {
181         .lo_word = VTD_REQ_INV_CONTEXT | VTD_INV_CONTEXT_GLOBAL,
182 };
183 static const struct vtd_entry inv_global_iotlb = {
184         .lo_word = VTD_REQ_INV_IOTLB | VTD_INV_IOTLB_GLOBAL |
185                 VTD_INV_IOTLB_DW | VTD_INV_IOTLB_DR,
186 };
187 static const struct vtd_entry inv_global_int = {
188         .lo_word = VTD_REQ_INV_INT | VTD_INV_INT_GLOBAL,
189 };
190
191 /* TODO: Support multiple segments */
192 static struct vtd_entry __attribute__((aligned(PAGE_SIZE)))
193         root_entry_table[256];
194 static union vtd_irte *int_remap_table;
195 static unsigned int int_remap_table_size_log2;
196 static struct paging vtd_paging[VTD_MAX_PAGE_TABLE_LEVELS];
197 static void *dmar_reg_base;
198 static void *unit_inv_queue;
199 static unsigned int dmar_units;
200 static unsigned int dmar_pt_levels;
201 static unsigned int dmar_num_did = ~0U;
202 static DEFINE_SPINLOCK(inv_queue_lock);
203 static struct vtd_emulation root_cell_units[JAILHOUSE_MAX_IOMMU_UNITS];
204 static bool dmar_units_initialized;
205
206 unsigned int iommu_mmio_count_regions(struct cell *cell)
207 {
208         return cell == &root_cell ? iommu_count_units() : 0;
209 }
210
211 static unsigned int inv_queue_write(void *inv_queue, unsigned int index,
212                                     struct vtd_entry content)
213 {
214         struct vtd_entry *entry = inv_queue;
215
216         entry[index] = content;
217         arch_paging_flush_cpu_caches(&entry[index], sizeof(*entry));
218
219         return (index + 1) % (PAGE_SIZE / sizeof(*entry));
220 }
221
222 static void vtd_submit_iq_request(void *reg_base, void *inv_queue,
223                                   const struct vtd_entry *inv_request)
224 {
225         volatile u32 completed = 0;
226         struct vtd_entry inv_wait = {
227                 .lo_word = VTD_REQ_INV_WAIT | VTD_INV_WAIT_SW |
228                         VTD_INV_WAIT_FN | (1UL << VTD_INV_WAIT_SDATA_SHIFT),
229                 .hi_word = paging_hvirt2phys(&completed),
230         };
231         unsigned int index;
232
233         spin_lock(&inv_queue_lock);
234
235         index = mmio_read64_field(reg_base + VTD_IQT_REG, VTD_IQT_QT_MASK);
236
237         if (inv_request)
238                 index = inv_queue_write(inv_queue, index, *inv_request);
239         index = inv_queue_write(inv_queue, index, inv_wait);
240
241         mmio_write64_field(reg_base + VTD_IQT_REG, VTD_IQT_QT_MASK, index);
242
243         while (!completed)
244                 cpu_relax();
245
246         spin_unlock(&inv_queue_lock);
247 }
248
249 static void vtd_flush_domain_caches(unsigned int did)
250 {
251         const struct vtd_entry inv_context = {
252                 .lo_word = VTD_REQ_INV_CONTEXT | VTD_INV_CONTEXT_DOMAIN |
253                         (did << VTD_INV_CONTEXT_DOMAIN_SHIFT),
254         };
255         const struct vtd_entry inv_iotlb = {
256                 .lo_word = VTD_REQ_INV_IOTLB | VTD_INV_IOTLB_DOMAIN |
257                         VTD_INV_IOTLB_DW | VTD_INV_IOTLB_DR |
258                         (did << VTD_INV_IOTLB_DOMAIN_SHIFT),
259         };
260         void *inv_queue = unit_inv_queue;
261         void *reg_base = dmar_reg_base;
262         unsigned int n;
263
264         for (n = 0; n < dmar_units; n++) {
265                 vtd_submit_iq_request(reg_base, inv_queue, &inv_context);
266                 vtd_submit_iq_request(reg_base, inv_queue, &inv_iotlb);
267                 reg_base += DMAR_MMIO_SIZE;
268                 inv_queue += PAGE_SIZE;
269         }
270 }
271
272 static void vtd_update_gcmd_reg(void *reg_base, u32 mask, unsigned int set)
273 {
274         u32 val = mmio_read32(reg_base + VTD_GSTS_REG) & VTD_GSTS_USED_CTRLS;
275
276         if (set)
277                 val |= mask;
278         else
279                 val &= ~mask;
280         mmio_write32(reg_base + VTD_GCMD_REG, val);
281
282         /* Note: This test is built on the fact related bits are at the same
283          * position in VTD_GCMD_REG and VTD_GSTS_REG. */
284         while ((mmio_read32(reg_base + VTD_GSTS_REG) & mask) != (val & mask))
285                 cpu_relax();
286 }
287
288 static void vtd_set_next_pt(pt_entry_t pte, unsigned long next_pt)
289 {
290         *pte = (next_pt & BIT_MASK(51, 12)) | VTD_PAGE_READ | VTD_PAGE_WRITE;
291 }
292
293 static void vtd_init_fault_nmi(void)
294 {
295         union x86_msi_vector msi = { .native.address = MSI_ADDRESS_VALUE };
296         void *reg_base = dmar_reg_base;
297         struct per_cpu *cpu_data;
298         unsigned int n;
299
300         /* Pick a suitable root cell CPU to report faults. */
301         cpu_data = iommu_select_fault_reporting_cpu();
302
303         /* We only support 8-bit APIC IDs. */
304         msi.native.destination = (u8)cpu_data->apic_id;
305
306         for (n = 0; n < dmar_units; n++, reg_base += DMAR_MMIO_SIZE) {
307                 /* Mask events */
308                 mmio_write32_field(reg_base + VTD_FECTL_REG, VTD_FECTL_IM, 1);
309
310                 /*
311                  * VT-d spec rev. 2.3 section 7.4 suggests that only reading
312                  * back FSTS or FECTL ensures no interrupt messages are still
313                  * in-flight when we change their destination below.
314                  */
315                 mmio_read32(reg_base + VTD_FECTL_REG);
316
317                 /* Program MSI message to send NMIs to the target CPU */
318                 mmio_write32(reg_base + VTD_FEDATA_REG, MSI_DM_NMI);
319                 mmio_write32(reg_base + VTD_FEADDR_REG, (u32)msi.raw.address);
320                 mmio_write32(reg_base + VTD_FEUADDR_REG, 0);
321
322                 /* Unmask events */
323                 mmio_write32_field(reg_base + VTD_FECTL_REG, VTD_FECTL_IM, 0);
324         }
325
326         /*
327          * There is a race window between setting the new reporting CPU ID and
328          * updating the target programming in the register. If a fault hits us
329          * in this window and no other NMIs arrive after that, the event will
330          * not be reported. Address this by triggering an NMI on the new
331          * reporting CPU.
332          */
333         apic_send_nmi_ipi(cpu_data);
334 }
335
336 static void *vtd_get_fault_rec_reg_addr(void *reg_base)
337 {
338         return reg_base + 16 *
339                 mmio_read64_field(reg_base + VTD_CAP_REG, VTD_CAP_FRO_MASK);
340 }
341
342 static void vtd_print_fault_record_reg_status(unsigned int unit_no,
343                                               void *reg_base)
344 {
345         unsigned int sid = mmio_read64_field(reg_base + VTD_FRCD_HI_REG,
346                                              VTD_FRCD_HI_SID_MASK);
347         unsigned int fr = mmio_read64_field(reg_base + VTD_FRCD_HI_REG,
348                                             VTD_FRCD_HI_FR_MASK);
349         unsigned long fi = mmio_read64_field(reg_base + VTD_FRCD_LO_REG,
350                                              VTD_FRCD_LO_FI_MASK);
351         unsigned int type = mmio_read64_field(reg_base + VTD_FRCD_HI_REG,
352                                               VTD_FRCD_HI_TYPE);
353
354         printk("VT-d fault event reported by IOMMU %d:\n", unit_no);
355         printk(" Source Identifier (bus:dev.func): %02x:%02x.%x\n",
356                PCI_BDF_PARAMS(sid));
357         printk(" Fault Reason: 0x%x Fault Info: %lx Type %d\n", fr, fi, type);
358 }
359
360 void iommu_check_pending_faults(void)
361 {
362         unsigned int fr_index;
363         void *reg_base = dmar_reg_base;
364         unsigned int n;
365         void *fault_reg_addr, *rec_reg_addr;
366
367         if (this_cpu_id() != fault_reporting_cpu_id)
368                 return;
369
370         for (n = 0; n < dmar_units; n++, reg_base += DMAR_MMIO_SIZE)
371                 if (mmio_read32_field(reg_base + VTD_FSTS_REG, VTD_FSTS_PPF)) {
372                         fr_index = mmio_read32_field(reg_base + VTD_FSTS_REG,
373                                                      VTD_FSTS_FRI_MASK);
374                         fault_reg_addr = vtd_get_fault_rec_reg_addr(reg_base);
375                         rec_reg_addr = fault_reg_addr + 16 * fr_index;
376                         vtd_print_fault_record_reg_status(n, rec_reg_addr);
377
378                         /* Clear faults in record registers */
379                         mmio_write64_field(rec_reg_addr + VTD_FRCD_HI_REG,
380                                            VTD_FRCD_HI_F, VTD_FRCD_HI_F_CLEAR);
381                 }
382 }
383
384 static int vtd_emulate_inv_int(unsigned int unit_no, unsigned int index)
385 {
386         struct vtd_irte_usage *irte_usage;
387         struct apic_irq_message irq_msg;
388         struct pci_device *device;
389
390         if (index >= root_cell_units[unit_no].irt_entries)
391                 return 0;
392         irte_usage = &root_cell_units[unit_no].irte_map[index];
393         if (!irte_usage->used)
394                 return 0;
395
396         device = pci_get_assigned_device(&root_cell, irte_usage->device_id);
397         if (device && device->info->type == JAILHOUSE_PCI_TYPE_IVSHMEM)
398                 return pci_ivshmem_update_msix(device);
399
400         irq_msg = iommu_get_remapped_root_int(unit_no, irte_usage->device_id,
401                                               irte_usage->vector, index);
402         return iommu_map_interrupt(&root_cell, irte_usage->device_id,
403                                    irte_usage->vector, irq_msg);
404 }
405
406 static int vtd_emulate_qi_request(unsigned int unit_no,
407                                   struct vtd_entry inv_desc)
408 {
409         unsigned int start, count, n;
410         void *status_page;
411         int result;
412
413         switch (inv_desc.lo_word & VTD_REQ_INV_MASK) {
414         case VTD_REQ_INV_INT:
415                 if (inv_desc.lo_word & VTD_INV_INT_INDEX) {
416                         start = (inv_desc.lo_word & VTD_INV_INT_IIDX_MASK) >>
417                                 VTD_INV_INT_IIDX_SHIFT;
418                         count =
419                             1 << ((inv_desc.lo_word & VTD_INV_INT_IM_MASK) >>
420                                   VTD_INV_INT_IM_SHIFT);
421                 } else {
422                         start = 0;
423                         count = root_cell_units[unit_no].irt_entries;
424                 }
425                 for (n = start; n < start + count; n++) {
426                         result = vtd_emulate_inv_int(unit_no, n);
427                         if (result < 0)
428                                 return result;
429                 }
430                 return 0;
431         case VTD_REQ_INV_WAIT:
432                 if (inv_desc.lo_word & VTD_INV_WAIT_IF ||
433                     !(inv_desc.lo_word & VTD_INV_WAIT_SW))
434                         return -EINVAL;
435
436                 status_page = paging_get_guest_pages(NULL, inv_desc.hi_word, 1,
437                                                      PAGE_DEFAULT_FLAGS);
438                 if (!status_page)
439                         return -EINVAL;
440
441                 *(u32 *)(status_page + (inv_desc.hi_word & ~PAGE_MASK)) =
442                         inv_desc.lo_word >> 32;
443
444                 return 0;
445         }
446         return -EINVAL;
447 }
448
449 static enum mmio_result vtd_unit_access_handler(void *arg,
450                                                 struct mmio_access *mmio)
451 {
452         struct vtd_emulation *unit = arg;
453         unsigned int unit_no = unit - root_cell_units;
454         struct vtd_entry inv_desc;
455         void *inv_desc_page;
456
457         if (mmio->address == VTD_FSTS_REG && !mmio->is_write) {
458                 /*
459                  * Nothing to report this way, vtd_check_pending_faults takes
460                  * care for the whole system.
461                  */
462                 mmio->value = 0;
463                 return MMIO_HANDLED;
464         }
465         if (mmio->address == VTD_IQT_REG && mmio->is_write) {
466                 while (unit->iqh != (mmio->value & ~PAGE_MASK)) {
467                         inv_desc_page =
468                                 paging_get_guest_pages(NULL, unit->iqa, 1,
469                                                        PAGE_READONLY_FLAGS);
470                         if (!inv_desc_page)
471                                 goto invalid_iq_entry;
472
473                         inv_desc =
474                             *(struct vtd_entry *)(inv_desc_page + unit->iqh);
475
476                         if (vtd_emulate_qi_request(unit_no, inv_desc) != 0)
477                                 goto invalid_iq_entry;
478
479                         unit->iqh += 1 << VTD_IQH_QH_SHIFT;
480                         unit->iqh &= ~PAGE_MASK;
481                 }
482                 return MMIO_HANDLED;
483         }
484         panic_printk("FATAL: Unhandled DMAR unit %s access, register %02x\n",
485                      mmio->is_write ? "write" : "read", mmio->address);
486         return MMIO_ERROR;
487
488 invalid_iq_entry:
489         panic_printk("FATAL: Invalid/unsupported invalidation queue entry\n");
490         return -1;
491 }
492
493 static void vtd_init_unit(void *reg_base, void *inv_queue)
494 {
495         void *fault_reg_base;
496         unsigned int nfr, n;
497
498         /* Disabled QI and IR in case it was already on */
499         vtd_update_gcmd_reg(reg_base, VTD_GCMD_QIE, 0);
500         vtd_update_gcmd_reg(reg_base, VTD_GCMD_IRE, 0);
501
502         nfr = mmio_read64_field(reg_base + VTD_CAP_REG, VTD_CAP_NFR_MASK);
503         fault_reg_base = vtd_get_fault_rec_reg_addr(reg_base);
504
505         for (n = 0; n < nfr; n++)
506                 /* Clear fault recording register status */
507                 mmio_write64_field(fault_reg_base + 16 * n + VTD_FRCD_HI_REG,
508                                    VTD_FRCD_HI_F, VTD_FRCD_HI_F_CLEAR);
509
510         /* Clear fault overflow status */
511         mmio_write32_field(reg_base + VTD_FSTS_REG, VTD_FSTS_PFO,
512                            VTD_FSTS_PFO_CLEAR);
513
514         /* Set root entry table pointer */
515         mmio_write64(reg_base + VTD_RTADDR_REG,
516                      paging_hvirt2phys(root_entry_table));
517         vtd_update_gcmd_reg(reg_base, VTD_GCMD_SRTP, 1);
518
519         /* Set interrupt remapping table pointer */
520         mmio_write64(reg_base + VTD_IRTA_REG,
521                      paging_hvirt2phys(int_remap_table) |
522                      (using_x2apic ? VTD_IRTA_EIME : 0) |
523                      (int_remap_table_size_log2 - 1));
524         vtd_update_gcmd_reg(reg_base, VTD_GCMD_SIRTP, 1);
525
526         /* Setup and activate invalidation queue */
527         mmio_write64(reg_base + VTD_IQT_REG, 0);
528         mmio_write64(reg_base + VTD_IQA_REG, paging_hvirt2phys(inv_queue));
529         vtd_update_gcmd_reg(reg_base, VTD_GCMD_QIE, 1);
530
531         vtd_submit_iq_request(reg_base, inv_queue, &inv_global_context);
532         vtd_submit_iq_request(reg_base, inv_queue, &inv_global_iotlb);
533         vtd_submit_iq_request(reg_base, inv_queue, &inv_global_int);
534
535         vtd_update_gcmd_reg(reg_base, VTD_GCMD_TE, 1);
536         vtd_update_gcmd_reg(reg_base, VTD_GCMD_IRE, 1);
537 }
538
539 static int vtd_init_ir_emulation(unsigned int unit_no, void *reg_base)
540 {
541         struct vtd_emulation *unit = &root_cell_units[unit_no];
542         unsigned long base, size;
543         u64 iqt;
544
545         root_cell.arch.vtd.ir_emulation = true;
546
547         base = system_config->platform_info.x86.iommu_units[unit_no].base;
548         mmio_region_register(&root_cell, base, PAGE_SIZE,
549                              vtd_unit_access_handler, unit);
550
551         unit->irta = mmio_read64(reg_base + VTD_IRTA_REG);
552         unit->irt_entries = 2 << (unit->irta & VTD_IRTA_SIZE_MASK);
553
554         size = PAGE_ALIGN(sizeof(struct vtd_irte_usage) * unit->irt_entries);
555         unit->irte_map = page_alloc(&mem_pool, size / PAGE_SIZE);
556         if (!unit->irte_map)
557                 return -ENOMEM;
558
559         iqt = mmio_read64(reg_base + VTD_IQT_REG);
560         while (mmio_read64(reg_base + VTD_IQH_REG) != iqt)
561                 cpu_relax();
562         unit->iqh = iqt;
563
564         unit->iqa = mmio_read64(reg_base + VTD_IQA_REG);
565         if (unit->iqa & ~VTD_IQA_ADDR_MASK)
566                 return trace_error(-EIO);
567
568         unit->fectl = mmio_read32(reg_base + VTD_FECTL_REG);
569         unit->fedata = mmio_read32(reg_base + VTD_FEDATA_REG);
570         unit->feaddr = mmio_read32(reg_base + VTD_FEADDR_REG);
571         unit->feuaddr = mmio_read32(reg_base + VTD_FEUADDR_REG);
572
573         return 0;
574 }
575
576 int iommu_init(void)
577 {
578         unsigned long version, caps, ecaps, ctrls, sllps_caps = ~0UL;
579         unsigned int units, pt_levels, num_did, n;
580         struct jailhouse_iommu *unit;
581         void *reg_base;
582         int err;
583
584         /* n = roundup(log2(system_config->interrupt_limit)) */
585         for (n = 0; (1UL << n) < (system_config->interrupt_limit); n++)
586                 ; /* empty loop */
587         if (n >= 16)
588                 return trace_error(-EINVAL);
589
590         int_remap_table =
591                 page_alloc(&mem_pool, PAGES(sizeof(union vtd_irte) << n));
592         if (!int_remap_table)
593                 return -ENOMEM;
594
595         int_remap_table_size_log2 = n;
596
597         units = iommu_count_units();
598         if (units == 0)
599                 return trace_error(-EINVAL);
600
601         dmar_reg_base = page_alloc(&remap_pool, units * PAGES(DMAR_MMIO_SIZE));
602         if (!dmar_reg_base)
603                 return trace_error(-ENOMEM);
604
605         unit_inv_queue = page_alloc(&mem_pool, units);
606         if (!unit_inv_queue)
607                 return -ENOMEM;
608
609         for (n = 0; n < units; n++) {
610                 unit = &system_config->platform_info.x86.iommu_units[n];
611
612                 reg_base = dmar_reg_base + n * DMAR_MMIO_SIZE;
613
614                 err = paging_create(&hv_paging_structs, unit->base, unit->size,
615                                     (unsigned long)reg_base,
616                                     PAGE_DEFAULT_FLAGS | PAGE_FLAG_DEVICE,
617                                     PAGING_NON_COHERENT);
618                 if (err)
619                         return err;
620
621                 version = mmio_read64(reg_base + VTD_VER_REG) & VTD_VER_MASK;
622                 if (version < VTD_VER_MIN || version == 0xff) {
623                         //return -EIO;
624                         // HACK for QEMU
625                         printk("WARNING: No VT-d support found!\n");
626                         return 0;
627                 }
628
629                 printk("DMAR unit @0x%lx/0x%x\n", unit->base, unit->size);
630
631                 caps = mmio_read64(reg_base + VTD_CAP_REG);
632                 if (caps & VTD_CAP_SAGAW39)
633                         pt_levels = 3;
634                 else if (caps & VTD_CAP_SAGAW48)
635                         pt_levels = 4;
636                 else
637                         return trace_error(-EIO);
638                 sllps_caps &= caps;
639
640                 if (dmar_pt_levels > 0 && dmar_pt_levels != pt_levels)
641                         return trace_error(-EIO);
642                 dmar_pt_levels = pt_levels;
643
644                 if (caps & VTD_CAP_CM)
645                         return trace_error(-EIO);
646
647                 ecaps = mmio_read64(reg_base + VTD_ECAP_REG);
648                 if (!(ecaps & VTD_ECAP_QI) || !(ecaps & VTD_ECAP_IR) ||
649                     (using_x2apic && !(ecaps & VTD_ECAP_EIM)))
650                         return trace_error(-EIO);
651
652                 ctrls = mmio_read32(reg_base + VTD_GSTS_REG) &
653                         VTD_GSTS_USED_CTRLS;
654                 if (ctrls != 0) {
655                         if (ctrls != (VTD_GSTS_IRES | VTD_GSTS_QIES))
656                                 return trace_error(-EBUSY);
657                         err = vtd_init_ir_emulation(n, reg_base);
658                         if (err)
659                                 return err;
660                 } else if (root_cell.arch.vtd.ir_emulation) {
661                         /* IR+QI must be either on or off in all units */
662                         return trace_error(-EIO);
663                 }
664
665                 num_did = 1 << (4 + (caps & VTD_CAP_NUM_DID_MASK) * 2);
666                 if (num_did < dmar_num_did)
667                         dmar_num_did = num_did;
668         }
669
670         dmar_units = units;
671
672         /*
673          * Derive vdt_paging from very similar x86_64_paging,
674          * replicating 0..3 for 4 levels and 1..3 for 3 levels.
675          */
676         memcpy(vtd_paging, &x86_64_paging[4 - dmar_pt_levels],
677                sizeof(struct paging) * dmar_pt_levels);
678         for (n = 0; n < dmar_pt_levels; n++)
679                 vtd_paging[n].set_next_pt = vtd_set_next_pt;
680         if (!(sllps_caps & VTD_CAP_SLLPS1G))
681                 vtd_paging[dmar_pt_levels - 3].page_size = 0;
682         if (!(sllps_caps & VTD_CAP_SLLPS2M))
683                 vtd_paging[dmar_pt_levels - 2].page_size = 0;
684
685         return iommu_cell_init(&root_cell);
686 }
687
688 static void vtd_update_irte(unsigned int index, union vtd_irte content)
689 {
690         const struct vtd_entry inv_int = {
691                 .lo_word = VTD_REQ_INV_INT | VTD_INV_INT_INDEX |
692                         ((u64)index << VTD_INV_INT_IIDX_SHIFT),
693         };
694         union vtd_irte *irte = &int_remap_table[index];
695         void *inv_queue = unit_inv_queue;
696         void *reg_base = dmar_reg_base;
697         unsigned int n;
698
699         if (content.field.p) {
700                 /*
701                  * Write upper half first to preserve non-presence.
702                  * If the entry was present before, we are only modifying the
703                  * lower half's content (destination etc.), so writing the
704                  * upper half becomes a nop and is safely done first.
705                  */
706                 irte->raw[1] = content.raw[1];
707                 memory_barrier();
708                 irte->raw[0] = content.raw[0];
709         } else {
710                 /*
711                  * Write only lower half - we are clearing presence and
712                  * assignment.
713                  */
714                 irte->raw[0] = content.raw[0];
715         }
716         arch_paging_flush_cpu_caches(irte, sizeof(*irte));
717
718         for (n = 0; n < dmar_units; n++) {
719                 vtd_submit_iq_request(reg_base, inv_queue, &inv_int);
720                 reg_base += DMAR_MMIO_SIZE;
721                 inv_queue += PAGE_SIZE;
722         }
723 }
724
725 static int vtd_find_int_remap_region(u16 device_id)
726 {
727         int n;
728
729         /* interrupt_limit is < 2^16, see vtd_init */
730         for (n = 0; n < system_config->interrupt_limit; n++)
731                 if (int_remap_table[n].field.assigned &&
732                     int_remap_table[n].field.sid == device_id)
733                         return n;
734
735         return -ENOENT;
736 }
737
738 static int vtd_reserve_int_remap_region(u16 device_id, unsigned int length)
739 {
740         int n, start = -E2BIG;
741
742         if (length == 0 || vtd_find_int_remap_region(device_id) >= 0)
743                 return 0;
744
745         for (n = 0; n < system_config->interrupt_limit; n++) {
746                 if (int_remap_table[n].field.assigned) {
747                         start = -E2BIG;
748                         continue;
749                 }
750                 if (start < 0)
751                         start = n;
752                 if (n + 1 == start + length) {
753                         printk("Reserving %u interrupt(s) for device %04x "
754                                "at index %d\n", length, device_id, start);
755                         for (n = start; n < start + length; n++) {
756                                 int_remap_table[n].field.assigned = 1;
757                                 int_remap_table[n].field.sid = device_id;
758                         }
759                         return start;
760                 }
761         }
762         return trace_error(-E2BIG);
763 }
764
765 static void vtd_free_int_remap_region(u16 device_id, unsigned int length)
766 {
767         union vtd_irte free_irte = { .field.p = 0, .field.assigned = 0 };
768         int pos = vtd_find_int_remap_region(device_id);
769
770         if (pos >= 0) {
771                 printk("Freeing %u interrupt(s) for device %04x at index %d\n",
772                        length, device_id, pos);
773                 while (length-- > 0)
774                         vtd_update_irte(pos++, free_irte);
775         }
776 }
777
778 int iommu_add_pci_device(struct cell *cell, struct pci_device *device)
779 {
780         unsigned int max_vectors = MAX(device->info->num_msi_vectors,
781                                        device->info->num_msix_vectors);
782         u16 bdf = device->info->bdf;
783         u64 *root_entry_lo = &root_entry_table[PCI_BUS(bdf)].lo_word;
784         struct vtd_entry *context_entry_table, *context_entry;
785         int result;
786
787         // HACK for QEMU
788         if (dmar_units == 0)
789                 return 0;
790
791         result = vtd_reserve_int_remap_region(bdf, max_vectors);
792         if (result < 0)
793                 return result;
794
795         if (*root_entry_lo & VTD_ROOT_PRESENT) {
796                 context_entry_table =
797                         paging_phys2hvirt(*root_entry_lo & PAGE_MASK);
798         } else {
799                 context_entry_table = page_alloc(&mem_pool, 1);
800                 if (!context_entry_table)
801                         goto error_nomem;
802                 *root_entry_lo = VTD_ROOT_PRESENT |
803                         paging_hvirt2phys(context_entry_table);
804                 arch_paging_flush_cpu_caches(root_entry_lo, sizeof(u64));
805         }
806
807         context_entry = &context_entry_table[PCI_DEVFN(bdf)];
808         context_entry->lo_word = VTD_CTX_PRESENT | VTD_CTX_TTYPE_MLP_UNTRANS |
809                 paging_hvirt2phys(cell->arch.vtd.pg_structs.root_table);
810         context_entry->hi_word =
811                 (dmar_pt_levels == 3 ? VTD_CTX_AGAW_39 : VTD_CTX_AGAW_48) |
812                 (cell->id << VTD_CTX_DID_SHIFT);
813         arch_paging_flush_cpu_caches(context_entry, sizeof(*context_entry));
814
815         return 0;
816
817 error_nomem:
818         vtd_free_int_remap_region(bdf, max_vectors);
819         return -ENOMEM;
820 }
821
822 void iommu_remove_pci_device(struct pci_device *device)
823 {
824         u16 bdf = device->info->bdf;
825         u64 *root_entry_lo = &root_entry_table[PCI_BUS(bdf)].lo_word;
826         struct vtd_entry *context_entry_table;
827         struct vtd_entry *context_entry;
828         unsigned int n;
829
830         // HACK for QEMU
831         if (dmar_units == 0)
832                 return;
833
834         vtd_free_int_remap_region(bdf, MAX(device->info->num_msi_vectors,
835                                            device->info->num_msix_vectors));
836
837         context_entry_table = paging_phys2hvirt(*root_entry_lo & PAGE_MASK);
838         context_entry = &context_entry_table[PCI_DEVFN(bdf)];
839
840         context_entry->lo_word &= ~VTD_CTX_PRESENT;
841         arch_paging_flush_cpu_caches(&context_entry->lo_word, sizeof(u64));
842
843         for (n = 0; n < 256; n++)
844                 if (context_entry_table[n].lo_word & VTD_CTX_PRESENT)
845                         return;
846
847         *root_entry_lo &= ~VTD_ROOT_PRESENT;
848         arch_paging_flush_cpu_caches(root_entry_lo, sizeof(u64));
849         page_free(&mem_pool, context_entry_table, 1);
850 }
851
852 int iommu_cell_init(struct cell *cell)
853 {
854         const struct jailhouse_irqchip *irqchip =
855                 jailhouse_cell_irqchips(cell->config);
856         unsigned int n;
857         int result;
858
859         // HACK for QEMU
860         if (dmar_units == 0)
861                 return 0;
862
863         if (cell->id >= dmar_num_did)
864                 return trace_error(-ERANGE);
865
866         cell->arch.vtd.pg_structs.root_paging = vtd_paging;
867         cell->arch.vtd.pg_structs.root_table = page_alloc(&mem_pool, 1);
868         if (!cell->arch.vtd.pg_structs.root_table)
869                 return -ENOMEM;
870
871         /* reserve regions for IRQ chips (if not done already) */
872         for (n = 0; n < cell->config->num_irqchips; n++, irqchip++) {
873                 result = vtd_reserve_int_remap_region(irqchip->id,
874                                                       IOAPIC_NUM_PINS);
875                 if (result < 0) {
876                         iommu_cell_exit(cell);
877                         return result;
878                 }
879         }
880
881         return 0;
882 }
883
884 int iommu_map_memory_region(struct cell *cell,
885                             const struct jailhouse_memory *mem)
886 {
887         u32 flags = 0;
888
889         // HACK for QEMU
890         if (dmar_units == 0)
891                 return 0;
892
893         if (!(mem->flags & JAILHOUSE_MEM_DMA))
894                 return 0;
895
896         if (mem->virt_start & BIT_MASK(63, 12 + 9 * dmar_pt_levels))
897                 return trace_error(-E2BIG);
898
899         if (mem->flags & JAILHOUSE_MEM_READ)
900                 flags |= VTD_PAGE_READ;
901         if (mem->flags & JAILHOUSE_MEM_WRITE)
902                 flags |= VTD_PAGE_WRITE;
903
904         return paging_create(&cell->arch.vtd.pg_structs, mem->phys_start,
905                              mem->size, mem->virt_start, flags,
906                              PAGING_COHERENT);
907 }
908
909 int iommu_unmap_memory_region(struct cell *cell,
910                               const struct jailhouse_memory *mem)
911 {
912         // HACK for QEMU
913         if (dmar_units == 0)
914                 return 0;
915
916         if (!(mem->flags & JAILHOUSE_MEM_DMA))
917                 return 0;
918
919         return paging_destroy(&cell->arch.vtd.pg_structs, mem->virt_start,
920                               mem->size, PAGING_COHERENT);
921 }
922
923 struct apic_irq_message
924 iommu_get_remapped_root_int(unsigned int iommu, u16 device_id,
925                             unsigned int vector, unsigned int remap_index)
926 {
927         struct vtd_emulation *unit = &root_cell_units[iommu];
928         struct apic_irq_message irq_msg = { .valid = 0 };
929         union vtd_irte root_irte;
930         unsigned long irte_addr;
931         void *irte_page;
932
933         if (remap_index >= unit->irt_entries)
934                 return irq_msg;
935         unit->irte_map[remap_index].used = 0;
936
937         irte_addr = (unit->irta & VTD_IRTA_ADDR_MASK) +
938                 remap_index * sizeof(union vtd_irte);
939         irte_page = paging_get_guest_pages(NULL, irte_addr, 1,
940                                            PAGE_READONLY_FLAGS);
941         if (!irte_page)
942                 return irq_msg;
943
944         root_irte = *(union vtd_irte *)(irte_page + (irte_addr & ~PAGE_MASK));
945
946         irq_msg.valid =
947                 (root_irte.field.p && root_irte.field.sid == device_id);
948         irq_msg.vector = root_irte.field.vector;
949         irq_msg.delivery_mode = root_irte.field.delivery_mode;
950         irq_msg.dest_logical = root_irte.field.dest_logical;
951         irq_msg.level_triggered = root_irte.field.level_triggered;
952         irq_msg.redir_hint = root_irte.field.redir_hint;
953         irq_msg.destination = root_irte.field.destination;
954         if (!using_x2apic)
955                 /* xAPIC in flat mode: APIC ID in 47:40 (of 63:32) */
956                 irq_msg.destination >>= 8;
957
958         unit->irte_map[remap_index].device_id = device_id;
959         unit->irte_map[remap_index].vector = vector;
960         unit->irte_map[remap_index].used = 1;
961
962         return irq_msg;
963 }
964
965 int iommu_map_interrupt(struct cell *cell, u16 device_id, unsigned int vector,
966                         struct apic_irq_message irq_msg)
967 {
968         union vtd_irte irte;
969         int base_index;
970
971         // HACK for QEMU
972         if (dmar_units == 0)
973                 return -ENOSYS;
974
975         base_index = vtd_find_int_remap_region(device_id);
976         if (base_index < 0)
977                 return base_index;
978
979         if (vector >= system_config->interrupt_limit ||
980             base_index >= system_config->interrupt_limit - vector)
981                 return -ERANGE;
982
983         irte = int_remap_table[base_index + vector];
984         if (!irte.field.assigned || irte.field.sid != device_id)
985                 return -ERANGE;
986
987         irte.field.p = irq_msg.valid;
988         if (!irte.field.p)
989                 /*
990                  * Do not validate non-present entries, they may contain
991                  * invalid data and cause false-positives.
992                  */
993                 goto update_irte;
994
995         /*
996          * Validate delivery mode and destination(s).
997          * Note that we do support redirection hint only in logical
998          * destination mode.
999          */
1000         if ((irq_msg.delivery_mode != APIC_MSG_DLVR_FIXED &&
1001              irq_msg.delivery_mode != APIC_MSG_DLVR_LOWPRI) ||
1002             irq_msg.dest_logical != irq_msg.redir_hint)
1003                 return -EINVAL;
1004         if (!apic_filter_irq_dest(cell, &irq_msg))
1005                 return -EPERM;
1006
1007         irte.field.dest_logical = irq_msg.dest_logical;
1008         irte.field.redir_hint = irq_msg.redir_hint;
1009         irte.field.level_triggered = irq_msg.level_triggered;
1010         irte.field.delivery_mode = irq_msg.delivery_mode;
1011         irte.field.vector = irq_msg.vector;
1012         irte.field.destination = irq_msg.destination;
1013         if (!using_x2apic)
1014                 /* xAPIC in flat mode: APIC ID in 47:40 (of 63:32) */
1015                 irte.field.destination <<= 8;
1016         irte.field.sq = VTD_IRTE_SQ_VERIFY_FULL_SID;
1017         irte.field.svt = VTD_IRTE_SVT_VERIFY_SID_SQ;
1018
1019 update_irte:
1020         vtd_update_irte(base_index + vector, irte);
1021
1022         return base_index + vector;
1023 }
1024
1025 void iommu_cell_exit(struct cell *cell)
1026 {
1027         // HACK for QEMU
1028         if (dmar_units == 0)
1029                 return;
1030
1031         page_free(&mem_pool, cell->arch.vtd.pg_structs.root_table, 1);
1032
1033         /*
1034          * Note that reservation regions of IOAPICs won't be released because
1035          * they might be shared with other cells
1036          */
1037 }
1038
1039 void iommu_config_commit(struct cell *cell_added_removed)
1040 {
1041         void *inv_queue = unit_inv_queue;
1042         void *reg_base = dmar_reg_base;
1043         int n;
1044
1045         // HACK for QEMU
1046         if (dmar_units == 0)
1047                 return;
1048
1049         if (cell_added_removed)
1050                 vtd_init_fault_nmi();
1051
1052         if (cell_added_removed == &root_cell) {
1053                 for (n = 0; n < dmar_units; n++) {
1054                         vtd_init_unit(reg_base, inv_queue);
1055                         reg_base += DMAR_MMIO_SIZE;
1056                         inv_queue += PAGE_SIZE;
1057                 }
1058                 dmar_units_initialized = true;
1059         } else {
1060                 if (cell_added_removed)
1061                         vtd_flush_domain_caches(cell_added_removed->id);
1062                 vtd_flush_domain_caches(root_cell.id);
1063         }
1064 }
1065
1066 static void vtd_restore_ir(unsigned int unit_no, void *reg_base)
1067 {
1068         struct vtd_emulation *unit = &root_cell_units[unit_no];
1069         void *inv_queue = unit_inv_queue + unit_no * PAGE_SIZE;
1070         void *root_inv_queue;
1071         u64 iqh;
1072
1073         mmio_write64(reg_base + VTD_IRTA_REG, unit->irta);
1074         vtd_update_gcmd_reg(reg_base, VTD_GCMD_SIRTP, 1);
1075         vtd_submit_iq_request(reg_base, inv_queue, &inv_global_int);
1076
1077         vtd_update_gcmd_reg(reg_base, VTD_GCMD_QIE, 0);
1078         mmio_write64(reg_base + VTD_IQT_REG, 0);
1079         mmio_write64(reg_base + VTD_IQA_REG, unit->iqa);
1080         vtd_update_gcmd_reg(reg_base, VTD_GCMD_QIE, 1);
1081
1082         /*
1083          * Restore invalidation queue head pointer by issuing dummy requests
1084          * until the hardware is in sync with the Linux state again.
1085          */
1086         iqh =unit->iqh;
1087         root_inv_queue = paging_get_guest_pages(NULL, unit->iqa, 1,
1088                                                 PAGE_DEFAULT_FLAGS);
1089         if (root_inv_queue)
1090                 while (mmio_read64(reg_base + VTD_IQH_REG) != iqh)
1091                         vtd_submit_iq_request(reg_base, root_inv_queue, NULL);
1092         else
1093                 printk("WARNING: Failed to restore invalidation queue head\n");
1094
1095         vtd_update_gcmd_reg(reg_base, VTD_GCMD_IRE, 1);
1096
1097         mmio_write32(reg_base + VTD_FEDATA_REG, unit->fedata);
1098         mmio_write32(reg_base + VTD_FEADDR_REG, unit->feaddr);
1099         mmio_write32(reg_base + VTD_FEUADDR_REG, unit->feuaddr);
1100         mmio_write32(reg_base + VTD_FECTL_REG, unit->fectl);
1101 }
1102
1103 void iommu_shutdown(void)
1104 {
1105         void *reg_base = dmar_reg_base;
1106         unsigned int n;
1107
1108         if (dmar_units_initialized)
1109                 for (n = 0; n < dmar_units; n++, reg_base += DMAR_MMIO_SIZE) {
1110                         vtd_update_gcmd_reg(reg_base, VTD_GCMD_TE, 0);
1111                         vtd_update_gcmd_reg(reg_base, VTD_GCMD_IRE, 0);
1112                         if (root_cell.arch.vtd.ir_emulation)
1113                                 vtd_restore_ir(n, reg_base);
1114                         else
1115                                 vtd_update_gcmd_reg(reg_base, VTD_GCMD_QIE, 0);
1116                 }
1117 }
1118
1119 bool iommu_cell_emulates_ir(struct cell *cell)
1120 {
1121         return cell->arch.vtd.ir_emulation;
1122 }