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