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