xref: /illumos-gate/usr/src/uts/intel/io/vmm/intel/vtd.c (revision 8130f8e1)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #include <sys/kernel.h>
36 #include <sys/systm.h>
37 #include <sys/kmem.h>
38 
39 #include <dev/pci/pcireg.h>
40 
41 #include <machine/vmparam.h>
42 #include <sys/vmm_vm.h>
43 
44 #include <contrib/dev/acpica/include/acpi.h>
45 
46 #include <sys/sunndi.h>
47 
48 #include "io/iommu.h"
49 
50 /*
51  * Documented in the "Intel Virtualization Technology for Directed I/O",
52  * Architecture Spec, September 2008.
53  */
54 
55 #define	VTD_DRHD_INCLUDE_PCI_ALL(Flags)  (((Flags) >> 0) & 0x1)
56 
57 /* Section 10.4 "Register Descriptions" */
58 struct vtdmap {
59 	volatile uint32_t	version;
60 	volatile uint32_t	res0;
61 	volatile uint64_t	cap;
62 	volatile uint64_t	ext_cap;
63 	volatile uint32_t	gcr;
64 	volatile uint32_t	gsr;
65 	volatile uint64_t	rta;
66 	volatile uint64_t	ccr;
67 };
68 
69 #define	VTD_CAP_SAGAW(cap)	(((cap) >> 8) & 0x1F)
70 #define	VTD_CAP_ND(cap)		((cap) & 0x7)
71 #define	VTD_CAP_CM(cap)		(((cap) >> 7) & 0x1)
72 #define	VTD_CAP_SPS(cap)	(((cap) >> 34) & 0xF)
73 #define	VTD_CAP_RWBF(cap)	(((cap) >> 4) & 0x1)
74 
75 #define	VTD_ECAP_DI(ecap)	(((ecap) >> 2) & 0x1)
76 #define	VTD_ECAP_COHERENCY(ecap) ((ecap) & 0x1)
77 #define	VTD_ECAP_IRO(ecap)	(((ecap) >> 8) & 0x3FF)
78 
79 #define	VTD_GCR_WBF		(1 << 27)
80 #define	VTD_GCR_SRTP		(1 << 30)
81 #define	VTD_GCR_TE		(1U << 31)
82 
83 #define	VTD_GSR_WBFS		(1 << 27)
84 #define	VTD_GSR_RTPS		(1 << 30)
85 #define	VTD_GSR_TES		(1U << 31)
86 
87 #define	VTD_CCR_ICC		(1UL << 63)	/* invalidate context cache */
88 #define	VTD_CCR_CIRG_GLOBAL	(1UL << 61)	/* global invalidation */
89 
90 #define	VTD_IIR_IVT		(1UL << 63)	/* invalidation IOTLB */
91 #define	VTD_IIR_IIRG_GLOBAL	(1ULL << 60)	/* global IOTLB invalidation */
92 #define	VTD_IIR_IIRG_DOMAIN	(2ULL << 60)	/* domain IOTLB invalidation */
93 #define	VTD_IIR_IIRG_PAGE	(3ULL << 60)	/* page IOTLB invalidation */
94 #define	VTD_IIR_DRAIN_READS	(1ULL << 49)	/* drain pending DMA reads */
95 #define	VTD_IIR_DRAIN_WRITES	(1ULL << 48)	/* drain pending DMA writes */
96 #define	VTD_IIR_DOMAIN_P	32
97 
98 #define	VTD_ROOT_PRESENT	0x1
99 #define	VTD_CTX_PRESENT		0x1
100 #define	VTD_CTX_TT_ALL		(1UL << 2)
101 
102 #define	VTD_PTE_RD		(1UL << 0)
103 #define	VTD_PTE_WR		(1UL << 1)
104 #define	VTD_PTE_SUPERPAGE	(1UL << 7)
105 #define	VTD_PTE_ADDR_M		(0x000FFFFFFFFFF000UL)
106 
107 #define	VTD_RID2IDX(rid)	(((rid) & 0xff) * 2)
108 
109 struct domain {
110 	uint64_t	*ptp;		/* first level page table page */
111 	int		pt_levels;	/* number of page table levels */
112 	int		addrwidth;	/* 'AW' field in context entry */
113 	int		spsmask;	/* supported super page sizes */
114 	uint_t		id;		/* domain id */
115 	vm_paddr_t	maxaddr;	/* highest address to be mapped */
116 	SLIST_ENTRY(domain) next;
117 };
118 
119 static SLIST_HEAD(, domain) domhead;
120 
121 #define	DRHD_MAX_UNITS	8
122 static ACPI_DMAR_HARDWARE_UNIT	*drhds[DRHD_MAX_UNITS];
123 static int			drhd_num;
124 static struct vtdmap		*vtdmaps[DRHD_MAX_UNITS];
125 static int			max_domains;
126 typedef int			(*drhd_ident_func_t)(void);
127 #ifndef __FreeBSD__
128 static dev_info_t	*vtddips[DRHD_MAX_UNITS];
129 #endif
130 
131 static uint64_t root_table[PAGE_SIZE / sizeof (uint64_t)] __aligned(4096);
132 static uint64_t ctx_tables[256][PAGE_SIZE / sizeof (uint64_t)] __aligned(4096);
133 
134 static int
135 vtd_max_domains(struct vtdmap *vtdmap)
136 {
137 	int nd;
138 
139 	nd = VTD_CAP_ND(vtdmap->cap);
140 
141 	switch (nd) {
142 	case 0:
143 		return (16);
144 	case 1:
145 		return (64);
146 	case 2:
147 		return (256);
148 	case 3:
149 		return (1024);
150 	case 4:
151 		return (4 * 1024);
152 	case 5:
153 		return (16 * 1024);
154 	case 6:
155 		return (64 * 1024);
156 	default:
157 		panic("vtd_max_domains: invalid value of nd (0x%0x)", nd);
158 	}
159 }
160 
161 static uint_t
162 domain_id(void)
163 {
164 	uint_t id;
165 	struct domain *dom;
166 
167 	/* Skip domain id 0 - it is reserved when Caching Mode field is set */
168 	for (id = 1; id < max_domains; id++) {
169 		SLIST_FOREACH(dom, &domhead, next) {
170 			if (dom->id == id)
171 				break;
172 		}
173 		if (dom == NULL)
174 			break;		/* found it */
175 	}
176 
177 	if (id >= max_domains)
178 		panic("domain ids exhausted");
179 
180 	return (id);
181 }
182 
183 static struct vtdmap *
184 vtd_device_scope(uint16_t rid)
185 {
186 	int i, remaining, pathrem;
187 	char *end, *pathend;
188 	struct vtdmap *vtdmap;
189 	ACPI_DMAR_HARDWARE_UNIT *drhd;
190 	ACPI_DMAR_DEVICE_SCOPE *device_scope;
191 	ACPI_DMAR_PCI_PATH *path;
192 
193 	for (i = 0; i < drhd_num; i++) {
194 		drhd = drhds[i];
195 
196 		if (VTD_DRHD_INCLUDE_PCI_ALL(drhd->Flags)) {
197 			/*
198 			 * From Intel VT-d arch spec, version 3.0:
199 			 * If a DRHD structure with INCLUDE_PCI_ALL flag Set is
200 			 * reported for a Segment, it must be enumerated by BIOS
201 			 * after all other DRHD structures for the same Segment.
202 			 */
203 			vtdmap = vtdmaps[i];
204 			return (vtdmap);
205 		}
206 
207 		end = (char *)drhd + drhd->Header.Length;
208 		remaining = drhd->Header.Length -
209 		    sizeof (ACPI_DMAR_HARDWARE_UNIT);
210 		while (remaining > sizeof (ACPI_DMAR_DEVICE_SCOPE)) {
211 			device_scope =
212 			    (ACPI_DMAR_DEVICE_SCOPE *)(end - remaining);
213 			remaining -= device_scope->Length;
214 
215 			switch (device_scope->EntryType) {
216 				/* 0x01 and 0x02 are PCI device entries */
217 				case 0x01:
218 				case 0x02:
219 					break;
220 				default:
221 					continue;
222 			}
223 
224 			if (PCI_RID2BUS(rid) != device_scope->Bus)
225 				continue;
226 
227 			pathend = (char *)device_scope + device_scope->Length;
228 			pathrem = device_scope->Length -
229 			    sizeof (ACPI_DMAR_DEVICE_SCOPE);
230 			while (pathrem >= sizeof (ACPI_DMAR_PCI_PATH)) {
231 				path = (ACPI_DMAR_PCI_PATH *)
232 				    (pathend - pathrem);
233 				pathrem -= sizeof (ACPI_DMAR_PCI_PATH);
234 
235 				if (PCI_RID2SLOT(rid) != path->Device)
236 					continue;
237 				if (PCI_RID2FUNC(rid) != path->Function)
238 					continue;
239 
240 				vtdmap = vtdmaps[i];
241 				return (vtdmap);
242 			}
243 		}
244 	}
245 
246 	/* No matching scope */
247 	return (NULL);
248 }
249 
250 static void
251 vtd_wbflush(struct vtdmap *vtdmap)
252 {
253 
254 	if (VTD_ECAP_COHERENCY(vtdmap->ext_cap) == 0)
255 		invalidate_cache_all();
256 
257 	if (VTD_CAP_RWBF(vtdmap->cap)) {
258 		vtdmap->gcr = VTD_GCR_WBF;
259 		while ((vtdmap->gsr & VTD_GSR_WBFS) != 0)
260 			;
261 	}
262 }
263 
264 static void
265 vtd_ctx_global_invalidate(struct vtdmap *vtdmap)
266 {
267 
268 	vtdmap->ccr = VTD_CCR_ICC | VTD_CCR_CIRG_GLOBAL;
269 	while ((vtdmap->ccr & VTD_CCR_ICC) != 0)
270 		;
271 }
272 
273 static void
274 vtd_iotlb_global_invalidate(struct vtdmap *vtdmap)
275 {
276 	int offset;
277 	volatile uint64_t *iotlb_reg, val;
278 
279 	vtd_wbflush(vtdmap);
280 
281 	offset = VTD_ECAP_IRO(vtdmap->ext_cap) * 16;
282 	iotlb_reg = (volatile uint64_t *)((caddr_t)vtdmap + offset + 8);
283 
284 	*iotlb_reg =  VTD_IIR_IVT | VTD_IIR_IIRG_GLOBAL |
285 	    VTD_IIR_DRAIN_READS | VTD_IIR_DRAIN_WRITES;
286 
287 	while (1) {
288 		val = *iotlb_reg;
289 		if ((val & VTD_IIR_IVT) == 0)
290 			break;
291 	}
292 }
293 
294 static void
295 vtd_translation_enable(struct vtdmap *vtdmap)
296 {
297 
298 	vtdmap->gcr = VTD_GCR_TE;
299 	while ((vtdmap->gsr & VTD_GSR_TES) == 0)
300 		;
301 }
302 
303 static void
304 vtd_translation_disable(struct vtdmap *vtdmap)
305 {
306 
307 	vtdmap->gcr = 0;
308 	while ((vtdmap->gsr & VTD_GSR_TES) != 0)
309 		;
310 }
311 
312 static void *
313 vtd_map(dev_info_t *dip)
314 {
315 	caddr_t regs;
316 	ddi_acc_handle_t hdl;
317 	int error;
318 
319 	static ddi_device_acc_attr_t regs_attr = {
320 		DDI_DEVICE_ATTR_V0,
321 		DDI_NEVERSWAP_ACC,
322 		DDI_STRICTORDER_ACC,
323 	};
324 
325 	error = ddi_regs_map_setup(dip, 0, &regs, 0, PAGE_SIZE, &regs_attr,
326 	    &hdl);
327 
328 	if (error != DDI_SUCCESS)
329 		return (NULL);
330 
331 	ddi_set_driver_private(dip, hdl);
332 
333 	return (regs);
334 }
335 
336 static void
337 vtd_unmap(dev_info_t *dip)
338 {
339 	ddi_acc_handle_t hdl = ddi_get_driver_private(dip);
340 
341 	if (hdl != NULL)
342 		ddi_regs_map_free(&hdl);
343 }
344 
345 #ifndef __FreeBSD__
346 /*
347  * This lives in vtd_sol.c for license reasons.
348  */
349 extern dev_info_t *vtd_get_dip(ACPI_DMAR_HARDWARE_UNIT *, int);
350 #endif
351 
352 static int
353 vtd_init(void)
354 {
355 	int i, units, remaining, tmp;
356 	struct vtdmap *vtdmap;
357 	vm_paddr_t ctx_paddr;
358 	char *end;
359 #ifdef __FreeBSD__
360 	char envname[32];
361 	unsigned long mapaddr;
362 #endif
363 	ACPI_STATUS status;
364 	ACPI_TABLE_DMAR *dmar;
365 	ACPI_DMAR_HEADER *hdr;
366 	ACPI_DMAR_HARDWARE_UNIT *drhd;
367 
368 #ifdef __FreeBSD__
369 	/*
370 	 * Allow the user to override the ACPI DMAR table by specifying the
371 	 * physical address of each remapping unit.
372 	 *
373 	 * The following example specifies two remapping units at
374 	 * physical addresses 0xfed90000 and 0xfeda0000 respectively.
375 	 * set vtd.regmap.0.addr=0xfed90000
376 	 * set vtd.regmap.1.addr=0xfeda0000
377 	 */
378 	for (units = 0; units < DRHD_MAX_UNITS; units++) {
379 		snprintf(envname, sizeof (envname), "vtd.regmap.%d.addr",
380 		    units);
381 		if (getenv_ulong(envname, &mapaddr) == 0)
382 			break;
383 		vtdmaps[units] = (struct vtdmap *)PHYS_TO_DMAP(mapaddr);
384 	}
385 
386 	if (units > 0)
387 		goto skip_dmar;
388 #else
389 	units = 0;
390 #endif
391 	/* Search for DMAR table. */
392 	status = AcpiGetTable(ACPI_SIG_DMAR, 0, (ACPI_TABLE_HEADER **)&dmar);
393 	if (ACPI_FAILURE(status))
394 		return (ENXIO);
395 
396 	end = (char *)dmar + dmar->Header.Length;
397 	remaining = dmar->Header.Length - sizeof (ACPI_TABLE_DMAR);
398 	while (remaining > sizeof (ACPI_DMAR_HEADER)) {
399 		hdr = (ACPI_DMAR_HEADER *)(end - remaining);
400 		if (hdr->Length > remaining)
401 			break;
402 		/*
403 		 * From Intel VT-d arch spec, version 1.3:
404 		 * BIOS implementations must report mapping structures
405 		 * in numerical order, i.e. All remapping structures of
406 		 * type 0 (DRHD) enumerated before remapping structures of
407 		 * type 1 (RMRR) and so forth.
408 		 */
409 		if (hdr->Type != ACPI_DMAR_TYPE_HARDWARE_UNIT)
410 			break;
411 
412 		drhd = (ACPI_DMAR_HARDWARE_UNIT *)hdr;
413 		drhds[units] = drhd;
414 #ifdef __FreeBSD__
415 		vtdmaps[units] = (struct vtdmap *)PHYS_TO_DMAP(drhd->Address);
416 #else
417 		vtddips[units] = vtd_get_dip(drhd, units);
418 		vtdmaps[units] = (struct vtdmap *)vtd_map(vtddips[units]);
419 		if (vtdmaps[units] == NULL)
420 			goto fail;
421 #endif
422 		if (++units >= DRHD_MAX_UNITS)
423 			break;
424 		remaining -= hdr->Length;
425 	}
426 
427 	if (units <= 0)
428 		return (ENXIO);
429 
430 #ifdef __FreeBSD__
431 skip_dmar:
432 #endif
433 	drhd_num = units;
434 
435 	max_domains = 64 * 1024; /* maximum valid value */
436 	for (i = 0; i < drhd_num; i++) {
437 		vtdmap = vtdmaps[i];
438 
439 		if (VTD_CAP_CM(vtdmap->cap) != 0)
440 			panic("vtd_init: invalid caching mode");
441 
442 		/* take most compatible (minimum) value */
443 		if ((tmp = vtd_max_domains(vtdmap)) < max_domains)
444 			max_domains = tmp;
445 	}
446 
447 	/*
448 	 * Set up the root-table to point to the context-entry tables
449 	 */
450 	for (i = 0; i < 256; i++) {
451 		ctx_paddr = vtophys(ctx_tables[i]);
452 		if (ctx_paddr & PAGE_MASK)
453 			panic("ctx table (0x%0lx) not page aligned", ctx_paddr);
454 
455 		root_table[i * 2] = ctx_paddr | VTD_ROOT_PRESENT;
456 	}
457 
458 	return (0);
459 
460 #ifndef __FreeBSD__
461 fail:
462 	for (i = 0; i <= units; i++)
463 		vtd_unmap(vtddips[i]);
464 	return (ENXIO);
465 #endif
466 }
467 
468 static void
469 vtd_cleanup(void)
470 {
471 #ifndef __FreeBSD__
472 	int i;
473 
474 	KASSERT(SLIST_EMPTY(&domhead), ("domain list not empty"));
475 
476 	bzero(root_table, sizeof (root_table));
477 
478 	for (i = 0; i <= drhd_num; i++) {
479 		vtdmaps[i] = NULL;
480 		/*
481 		 * Unmap the vtd registers. Note that the devinfo nodes
482 		 * themselves aren't removed, they are considered system state
483 		 * and can be reused when the module is reloaded.
484 		 */
485 		if (vtddips[i] != NULL)
486 			vtd_unmap(vtddips[i]);
487 	}
488 #endif
489 }
490 
491 static void
492 vtd_enable(void)
493 {
494 	int i;
495 	struct vtdmap *vtdmap;
496 
497 	for (i = 0; i < drhd_num; i++) {
498 		vtdmap = vtdmaps[i];
499 		vtd_wbflush(vtdmap);
500 
501 		/* Update the root table address */
502 		vtdmap->rta = vtophys(root_table);
503 		vtdmap->gcr = VTD_GCR_SRTP;
504 		while ((vtdmap->gsr & VTD_GSR_RTPS) == 0)
505 			;
506 
507 		vtd_ctx_global_invalidate(vtdmap);
508 		vtd_iotlb_global_invalidate(vtdmap);
509 
510 		vtd_translation_enable(vtdmap);
511 	}
512 }
513 
514 static void
515 vtd_disable(void)
516 {
517 	int i;
518 	struct vtdmap *vtdmap;
519 
520 	for (i = 0; i < drhd_num; i++) {
521 		vtdmap = vtdmaps[i];
522 		vtd_translation_disable(vtdmap);
523 	}
524 }
525 
526 static void
527 vtd_add_device(void *arg, uint16_t rid)
528 {
529 	int idx;
530 	uint64_t *ctxp;
531 	struct domain *dom = arg;
532 	vm_paddr_t pt_paddr;
533 	struct vtdmap *vtdmap;
534 	uint8_t bus;
535 
536 	bus = PCI_RID2BUS(rid);
537 	ctxp = ctx_tables[bus];
538 	pt_paddr = vtophys(dom->ptp);
539 	idx = VTD_RID2IDX(rid);
540 
541 	if (ctxp[idx] & VTD_CTX_PRESENT) {
542 		panic("vtd_add_device: device %x is already owned by "
543 		    "domain %d", rid, (uint16_t)(ctxp[idx + 1] >> 8));
544 	}
545 
546 	if ((vtdmap = vtd_device_scope(rid)) == NULL)
547 		panic("vtd_add_device: device %x is not in scope for "
548 		    "any DMA remapping unit", rid);
549 
550 	/*
551 	 * Order is important. The 'present' bit is set only after all fields
552 	 * of the context pointer are initialized.
553 	 */
554 	ctxp[idx + 1] = dom->addrwidth | (dom->id << 8);
555 
556 	if (VTD_ECAP_DI(vtdmap->ext_cap))
557 		ctxp[idx] = VTD_CTX_TT_ALL;
558 	else
559 		ctxp[idx] = 0;
560 
561 	ctxp[idx] |= pt_paddr | VTD_CTX_PRESENT;
562 
563 	/*
564 	 * 'Not Present' entries are not cached in either the Context Cache
565 	 * or in the IOTLB, so there is no need to invalidate either of them.
566 	 */
567 }
568 
569 static void
570 vtd_remove_device(void *arg, uint16_t rid)
571 {
572 	int i, idx;
573 	uint64_t *ctxp;
574 	struct vtdmap *vtdmap;
575 	uint8_t bus;
576 
577 	bus = PCI_RID2BUS(rid);
578 	ctxp = ctx_tables[bus];
579 	idx = VTD_RID2IDX(rid);
580 
581 	/*
582 	 * Order is important. The 'present' bit is must be cleared first.
583 	 */
584 	ctxp[idx] = 0;
585 	ctxp[idx + 1] = 0;
586 
587 	/*
588 	 * Invalidate the Context Cache and the IOTLB.
589 	 *
590 	 * XXX use device-selective invalidation for Context Cache
591 	 * XXX use domain-selective invalidation for IOTLB
592 	 */
593 	for (i = 0; i < drhd_num; i++) {
594 		vtdmap = vtdmaps[i];
595 		vtd_ctx_global_invalidate(vtdmap);
596 		vtd_iotlb_global_invalidate(vtdmap);
597 	}
598 }
599 
600 #define	CREATE_MAPPING	0
601 #define	REMOVE_MAPPING	1
602 
603 static uint64_t
604 vtd_update_mapping(void *arg, vm_paddr_t gpa, vm_paddr_t hpa, uint64_t len,
605     int remove)
606 {
607 	struct domain *dom;
608 	int i, spshift, ptpshift, ptpindex, nlevels;
609 	uint64_t spsize, *ptp;
610 
611 	dom = arg;
612 	ptpindex = 0;
613 	ptpshift = 0;
614 
615 	KASSERT(gpa + len > gpa, ("%s: invalid gpa range %lx/%lx", __func__,
616 	    gpa, len));
617 	KASSERT(gpa + len <= dom->maxaddr, ("%s: gpa range %lx/%lx beyond "
618 	    "domain maxaddr %lx", __func__, gpa, len, dom->maxaddr));
619 
620 	if (gpa & PAGE_MASK)
621 		panic("vtd_create_mapping: unaligned gpa 0x%0lx", gpa);
622 
623 	if (hpa & PAGE_MASK)
624 		panic("vtd_create_mapping: unaligned hpa 0x%0lx", hpa);
625 
626 	if (len & PAGE_MASK)
627 		panic("vtd_create_mapping: unaligned len 0x%0lx", len);
628 
629 	/*
630 	 * Compute the size of the mapping that we can accommodate.
631 	 *
632 	 * This is based on three factors:
633 	 * - supported super page size
634 	 * - alignment of the region starting at 'gpa' and 'hpa'
635 	 * - length of the region 'len'
636 	 */
637 	spshift = 48;
638 	for (i = 3; i >= 0; i--) {
639 		spsize = 1UL << spshift;
640 		if ((dom->spsmask & (1 << i)) != 0 &&
641 		    (gpa & (spsize - 1)) == 0 &&
642 		    (hpa & (spsize - 1)) == 0 &&
643 		    (len >= spsize)) {
644 			break;
645 		}
646 		spshift -= 9;
647 	}
648 
649 	ptp = dom->ptp;
650 	nlevels = dom->pt_levels;
651 	while (--nlevels >= 0) {
652 		ptpshift = 12 + nlevels * 9;
653 		ptpindex = (gpa >> ptpshift) & 0x1FF;
654 
655 		/* We have reached the leaf mapping */
656 		if (spshift >= ptpshift) {
657 			break;
658 		}
659 
660 		/*
661 		 * We are working on a non-leaf page table page.
662 		 *
663 		 * Create a downstream page table page if necessary and point
664 		 * to it from the current page table.
665 		 */
666 		if (ptp[ptpindex] == 0) {
667 			void *nlp = vmm_ptp_alloc();
668 			ptp[ptpindex] = vtophys(nlp)| VTD_PTE_RD | VTD_PTE_WR;
669 		}
670 
671 		ptp = (uint64_t *)PHYS_TO_DMAP(ptp[ptpindex] & VTD_PTE_ADDR_M);
672 	}
673 
674 	if ((gpa & ((1UL << ptpshift) - 1)) != 0)
675 		panic("gpa 0x%lx and ptpshift %d mismatch", gpa, ptpshift);
676 
677 	/*
678 	 * Update the 'gpa' -> 'hpa' mapping
679 	 */
680 	if (remove) {
681 		ptp[ptpindex] = 0;
682 	} else {
683 		ptp[ptpindex] = hpa | VTD_PTE_RD | VTD_PTE_WR;
684 
685 		if (nlevels > 0)
686 			ptp[ptpindex] |= VTD_PTE_SUPERPAGE;
687 	}
688 
689 	return (1UL << ptpshift);
690 }
691 
692 static uint64_t
693 vtd_create_mapping(void *arg, vm_paddr_t gpa, vm_paddr_t hpa, uint64_t len)
694 {
695 
696 	return (vtd_update_mapping(arg, gpa, hpa, len, CREATE_MAPPING));
697 }
698 
699 static uint64_t
700 vtd_remove_mapping(void *arg, vm_paddr_t gpa, uint64_t len)
701 {
702 
703 	return (vtd_update_mapping(arg, gpa, 0, len, REMOVE_MAPPING));
704 }
705 
706 static void
707 vtd_invalidate_tlb(void *dom)
708 {
709 	int i;
710 	struct vtdmap *vtdmap;
711 
712 	/*
713 	 * Invalidate the IOTLB.
714 	 * XXX use domain-selective invalidation for IOTLB
715 	 */
716 	for (i = 0; i < drhd_num; i++) {
717 		vtdmap = vtdmaps[i];
718 		vtd_iotlb_global_invalidate(vtdmap);
719 	}
720 }
721 
722 static void *
723 vtd_create_domain(vm_paddr_t maxaddr)
724 {
725 	struct domain *dom;
726 	vm_paddr_t addr;
727 	int tmp, i, gaw, agaw, sagaw, res, pt_levels, addrwidth;
728 	struct vtdmap *vtdmap;
729 
730 	if (drhd_num <= 0)
731 		panic("vtd_create_domain: no dma remapping hardware available");
732 
733 	/*
734 	 * Calculate AGAW.
735 	 * Section 3.4.2 "Adjusted Guest Address Width", Architecture Spec.
736 	 */
737 	addr = 0;
738 	for (gaw = 0; addr < maxaddr; gaw++)
739 		addr = 1ULL << gaw;
740 
741 	res = (gaw - 12) % 9;
742 	if (res == 0)
743 		agaw = gaw;
744 	else
745 		agaw = gaw + 9 - res;
746 
747 	if (agaw > 64)
748 		agaw = 64;
749 
750 	/*
751 	 * Select the smallest Supported AGAW and the corresponding number
752 	 * of page table levels.
753 	 */
754 	pt_levels = 2;
755 	sagaw = 30;
756 	addrwidth = 0;
757 
758 	tmp = ~0;
759 	for (i = 0; i < drhd_num; i++) {
760 		vtdmap = vtdmaps[i];
761 		/* take most compatible value */
762 		tmp &= VTD_CAP_SAGAW(vtdmap->cap);
763 	}
764 
765 	for (i = 0; i < 5; i++) {
766 		if ((tmp & (1 << i)) != 0 && sagaw >= agaw)
767 			break;
768 		pt_levels++;
769 		addrwidth++;
770 		sagaw += 9;
771 		if (sagaw > 64)
772 			sagaw = 64;
773 	}
774 
775 	if (i >= 5) {
776 		panic("vtd_create_domain: SAGAW 0x%x does not support AGAW %d",
777 		    tmp, agaw);
778 	}
779 
780 	dom = kmem_zalloc(sizeof (struct domain), KM_SLEEP);
781 	dom->pt_levels = pt_levels;
782 	dom->addrwidth = addrwidth;
783 	dom->id = domain_id();
784 	dom->maxaddr = maxaddr;
785 	dom->ptp = vmm_ptp_alloc();
786 	if ((uintptr_t)dom->ptp & PAGE_MASK)
787 		panic("vtd_create_domain: ptp (%p) not page aligned", dom->ptp);
788 
789 #ifdef __FreeBSD__
790 #ifdef notyet
791 	/*
792 	 * XXX superpage mappings for the iommu do not work correctly.
793 	 *
794 	 * By default all physical memory is mapped into the host_domain.
795 	 * When a VM is allocated wired memory the pages belonging to it
796 	 * are removed from the host_domain and added to the vm's domain.
797 	 *
798 	 * If the page being removed was mapped using a superpage mapping
799 	 * in the host_domain then we need to demote the mapping before
800 	 * removing the page.
801 	 *
802 	 * There is not any code to deal with the demotion at the moment
803 	 * so we disable superpage mappings altogether.
804 	 */
805 	dom->spsmask = ~0;
806 	for (i = 0; i < drhd_num; i++) {
807 		vtdmap = vtdmaps[i];
808 		/* take most compatible value */
809 		dom->spsmask &= VTD_CAP_SPS(vtdmap->cap);
810 	}
811 #endif
812 #else
813 	/*
814 	 * On illumos we decidedly do not remove memory mapped to a VM's domain
815 	 * from the host_domain, so we don't have to deal with page demotion and
816 	 * can just use large pages.
817 	 *
818 	 * Since VM memory is currently allocated as 4k pages and mapped into
819 	 * the VM domain page by page, the use of large pages is essentially
820 	 * limited to the host_domain.
821 	 */
822 	dom->spsmask = VTD_CAP_SPS(vtdmap->cap);
823 #endif
824 
825 	SLIST_INSERT_HEAD(&domhead, dom, next);
826 
827 	return (dom);
828 }
829 
830 static void
831 vtd_free_ptp(uint64_t *ptp, int level)
832 {
833 	int i;
834 	uint64_t *nlp;
835 
836 	if (level > 1) {
837 		for (i = 0; i < 512; i++) {
838 			if ((ptp[i] & (VTD_PTE_RD | VTD_PTE_WR)) == 0)
839 				continue;
840 			if ((ptp[i] & VTD_PTE_SUPERPAGE) != 0)
841 				continue;
842 			nlp = (uint64_t *)PHYS_TO_DMAP(ptp[i] & VTD_PTE_ADDR_M);
843 			vtd_free_ptp(nlp, level - 1);
844 		}
845 	}
846 
847 	vmm_ptp_free(ptp);
848 }
849 
850 static void
851 vtd_destroy_domain(void *arg)
852 {
853 	struct domain *dom;
854 
855 	dom = arg;
856 
857 	SLIST_REMOVE(&domhead, dom, domain, next);
858 	vtd_free_ptp(dom->ptp, dom->pt_levels);
859 	kmem_free(dom, sizeof (*dom));
860 }
861 
862 const struct iommu_ops iommu_ops_intel = {
863 	.init = vtd_init,
864 	.cleanup = vtd_cleanup,
865 	.enable = vtd_enable,
866 	.disable = vtd_disable,
867 	.create_domain = vtd_create_domain,
868 	.destroy_domain = vtd_destroy_domain,
869 	.create_mapping = vtd_create_mapping,
870 	.remove_mapping = vtd_remove_mapping,
871 	.add_device = vtd_add_device,
872 	.remove_device = vtd_remove_device,
873 	.invalidate_tlb = vtd_invalidate_tlb,
874 };
875