xref: /freebsd/sys/x86/iommu/intel_idpgtbl.c (revision 87b759f0fa1f7554d50ce640c40138512bbded44)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2013 The FreeBSD Foundation
5  *
6  * This software was developed by Konstantin Belousov <kib@FreeBSD.org>
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/malloc.h>
34 #include <sys/bus.h>
35 #include <sys/interrupt.h>
36 #include <sys/kernel.h>
37 #include <sys/ktr.h>
38 #include <sys/lock.h>
39 #include <sys/memdesc.h>
40 #include <sys/mutex.h>
41 #include <sys/proc.h>
42 #include <sys/rwlock.h>
43 #include <sys/rman.h>
44 #include <sys/sf_buf.h>
45 #include <sys/sysctl.h>
46 #include <sys/taskqueue.h>
47 #include <sys/tree.h>
48 #include <sys/uio.h>
49 #include <sys/vmem.h>
50 #include <sys/vmmeter.h>
51 #include <vm/vm.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_kern.h>
54 #include <vm/vm_object.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_pager.h>
57 #include <vm/vm_map.h>
58 #include <dev/pci/pcireg.h>
59 #include <machine/atomic.h>
60 #include <machine/bus.h>
61 #include <machine/cpu.h>
62 #include <machine/md_var.h>
63 #include <machine/specialreg.h>
64 #include <x86/include/busdma_impl.h>
65 #include <dev/iommu/busdma_iommu.h>
66 #include <x86/iommu/intel_reg.h>
67 #include <x86/iommu/x86_iommu.h>
68 #include <x86/iommu/intel_dmar.h>
69 
70 static int dmar_unmap_buf_locked(struct dmar_domain *domain,
71     iommu_gaddr_t base, iommu_gaddr_t size, int flags,
72     struct iommu_map_entry *entry);
73 
74 /*
75  * The cache of the identity mapping page tables for the DMARs.  Using
76  * the cache saves significant amount of memory for page tables by
77  * reusing the page tables, since usually DMARs are identical and have
78  * the same capabilities.  Still, cache records the information needed
79  * to match DMAR capabilities and page table format, to correctly
80  * handle different DMARs.
81  */
82 
83 struct idpgtbl {
84 	iommu_gaddr_t maxaddr;	/* Page table covers the guest address
85 				   range [0..maxaddr) */
86 	int pglvl;		/* Total page table levels ignoring
87 				   superpages */
88 	int leaf;		/* The last materialized page table
89 				   level, it is non-zero if superpages
90 				   are supported */
91 	vm_object_t pgtbl_obj;	/* The page table pages */
92 	LIST_ENTRY(idpgtbl) link;
93 };
94 
95 static struct sx idpgtbl_lock;
96 SX_SYSINIT(idpgtbl, &idpgtbl_lock, "idpgtbl");
97 static LIST_HEAD(, idpgtbl) idpgtbls = LIST_HEAD_INITIALIZER(idpgtbls);
98 static MALLOC_DEFINE(M_DMAR_IDPGTBL, "dmar_idpgtbl",
99     "Intel DMAR Identity mappings cache elements");
100 
101 /*
102  * Build the next level of the page tables for the identity mapping.
103  * - lvl is the level to build;
104  * - idx is the index of the page table page in the pgtbl_obj, which is
105  *   being allocated filled now;
106  * - addr is the starting address in the bus address space which is
107  *   mapped by the page table page.
108  */
109 static void
110 dmar_idmap_nextlvl(struct idpgtbl *tbl, int lvl, vm_pindex_t idx,
111     iommu_gaddr_t addr)
112 {
113 	vm_page_t m1;
114 	iommu_pte_t *pte;
115 	struct sf_buf *sf;
116 	iommu_gaddr_t f, pg_sz;
117 	vm_pindex_t base;
118 	int i;
119 
120 	VM_OBJECT_ASSERT_LOCKED(tbl->pgtbl_obj);
121 	if (addr >= tbl->maxaddr)
122 		return;
123 	(void)iommu_pgalloc(tbl->pgtbl_obj, idx, IOMMU_PGF_OBJL |
124 	    IOMMU_PGF_WAITOK | IOMMU_PGF_ZERO);
125 	base = idx * IOMMU_NPTEPG + 1; /* Index of the first child page of idx */
126 	pg_sz = pglvl_page_size(tbl->pglvl, lvl);
127 	if (lvl != tbl->leaf) {
128 		for (i = 0, f = addr; i < IOMMU_NPTEPG; i++, f += pg_sz)
129 			dmar_idmap_nextlvl(tbl, lvl + 1, base + i, f);
130 	}
131 	VM_OBJECT_WUNLOCK(tbl->pgtbl_obj);
132 	pte = iommu_map_pgtbl(tbl->pgtbl_obj, idx, IOMMU_PGF_WAITOK, &sf);
133 	if (lvl == tbl->leaf) {
134 		for (i = 0, f = addr; i < IOMMU_NPTEPG; i++, f += pg_sz) {
135 			if (f >= tbl->maxaddr)
136 				break;
137 			pte[i].pte = (DMAR_PTE_ADDR_MASK & f) |
138 			    DMAR_PTE_R | DMAR_PTE_W;
139 		}
140 	} else {
141 		for (i = 0, f = addr; i < IOMMU_NPTEPG; i++, f += pg_sz) {
142 			if (f >= tbl->maxaddr)
143 				break;
144 			m1 = iommu_pgalloc(tbl->pgtbl_obj, base + i,
145 			    IOMMU_PGF_NOALLOC);
146 			KASSERT(m1 != NULL, ("lost page table page"));
147 			pte[i].pte = (DMAR_PTE_ADDR_MASK &
148 			    VM_PAGE_TO_PHYS(m1)) | DMAR_PTE_R | DMAR_PTE_W;
149 		}
150 	}
151 	/* dmar_get_idmap_pgtbl flushes CPU cache if needed. */
152 	iommu_unmap_pgtbl(sf);
153 	VM_OBJECT_WLOCK(tbl->pgtbl_obj);
154 }
155 
156 /*
157  * Find a ready and compatible identity-mapping page table in the
158  * cache. If not found, populate the identity-mapping page table for
159  * the context, up to the maxaddr. The maxaddr byte is allowed to be
160  * not mapped, which is aligned with the definition of Maxmem as the
161  * highest usable physical address + 1.  If superpages are used, the
162  * maxaddr is typically mapped.
163  */
164 vm_object_t
165 dmar_get_idmap_pgtbl(struct dmar_domain *domain, iommu_gaddr_t maxaddr)
166 {
167 	struct dmar_unit *unit;
168 	struct idpgtbl *tbl;
169 	vm_object_t res;
170 	vm_page_t m;
171 	int leaf, i;
172 
173 	leaf = 0; /* silence gcc */
174 
175 	/*
176 	 * First, determine where to stop the paging structures.
177 	 */
178 	for (i = 0; i < domain->pglvl; i++) {
179 		if (i == domain->pglvl - 1 || domain_is_sp_lvl(domain, i)) {
180 			leaf = i;
181 			break;
182 		}
183 	}
184 
185 	/*
186 	 * Search the cache for a compatible page table.  Qualified
187 	 * page table must map up to maxaddr, its level must be
188 	 * supported by the DMAR and leaf should be equal to the
189 	 * calculated value.  The later restriction could be lifted
190 	 * but I believe it is currently impossible to have any
191 	 * deviations for existing hardware.
192 	 */
193 	sx_slock(&idpgtbl_lock);
194 	LIST_FOREACH(tbl, &idpgtbls, link) {
195 		if (tbl->maxaddr >= maxaddr &&
196 		    dmar_pglvl_supported(domain->dmar, tbl->pglvl) &&
197 		    tbl->leaf == leaf) {
198 			res = tbl->pgtbl_obj;
199 			vm_object_reference(res);
200 			sx_sunlock(&idpgtbl_lock);
201 			domain->pglvl = tbl->pglvl; /* XXXKIB ? */
202 			goto end;
203 		}
204 	}
205 
206 	/*
207 	 * Not found in cache, relock the cache into exclusive mode to
208 	 * be able to add element, and recheck cache again after the
209 	 * relock.
210 	 */
211 	sx_sunlock(&idpgtbl_lock);
212 	sx_xlock(&idpgtbl_lock);
213 	LIST_FOREACH(tbl, &idpgtbls, link) {
214 		if (tbl->maxaddr >= maxaddr &&
215 		    dmar_pglvl_supported(domain->dmar, tbl->pglvl) &&
216 		    tbl->leaf == leaf) {
217 			res = tbl->pgtbl_obj;
218 			vm_object_reference(res);
219 			sx_xunlock(&idpgtbl_lock);
220 			domain->pglvl = tbl->pglvl; /* XXXKIB ? */
221 			return (res);
222 		}
223 	}
224 
225 	/*
226 	 * Still not found, create new page table.
227 	 */
228 	tbl = malloc(sizeof(*tbl), M_DMAR_IDPGTBL, M_WAITOK);
229 	tbl->pglvl = domain->pglvl;
230 	tbl->leaf = leaf;
231 	tbl->maxaddr = maxaddr;
232 	tbl->pgtbl_obj = vm_pager_allocate(OBJT_PHYS, NULL,
233 	    IDX_TO_OFF(pglvl_max_pages(tbl->pglvl)), 0, 0, NULL);
234 	VM_OBJECT_WLOCK(tbl->pgtbl_obj);
235 	dmar_idmap_nextlvl(tbl, 0, 0, 0);
236 	VM_OBJECT_WUNLOCK(tbl->pgtbl_obj);
237 	LIST_INSERT_HEAD(&idpgtbls, tbl, link);
238 	res = tbl->pgtbl_obj;
239 	vm_object_reference(res);
240 	sx_xunlock(&idpgtbl_lock);
241 
242 end:
243 	/*
244 	 * Table was found or created.
245 	 *
246 	 * If DMAR does not snoop paging structures accesses, flush
247 	 * CPU cache to memory.  Note that dmar_unmap_pgtbl() coherent
248 	 * argument was possibly invalid at the time of the identity
249 	 * page table creation, since DMAR which was passed at the
250 	 * time of creation could be coherent, while current DMAR is
251 	 * not.
252 	 *
253 	 * If DMAR cannot look into the chipset write buffer, flush it
254 	 * as well.
255 	 */
256 	unit = domain->dmar;
257 	if (!DMAR_IS_COHERENT(unit)) {
258 		VM_OBJECT_WLOCK(res);
259 		for (m = vm_page_lookup(res, 0); m != NULL;
260 		     m = vm_page_next(m))
261 			pmap_invalidate_cache_pages(&m, 1);
262 		VM_OBJECT_WUNLOCK(res);
263 	}
264 	if ((unit->hw_cap & DMAR_CAP_RWBF) != 0) {
265 		DMAR_LOCK(unit);
266 		dmar_flush_write_bufs(unit);
267 		DMAR_UNLOCK(unit);
268 	}
269 
270 	return (res);
271 }
272 
273 /*
274  * Return a reference to the identity mapping page table to the cache.
275  */
276 void
277 dmar_put_idmap_pgtbl(vm_object_t obj)
278 {
279 	struct idpgtbl *tbl, *tbl1;
280 	vm_object_t rmobj;
281 
282 	sx_slock(&idpgtbl_lock);
283 	KASSERT(obj->ref_count >= 2, ("lost cache reference"));
284 	vm_object_deallocate(obj);
285 
286 	/*
287 	 * Cache always owns one last reference on the page table object.
288 	 * If there is an additional reference, object must stay.
289 	 */
290 	if (obj->ref_count > 1) {
291 		sx_sunlock(&idpgtbl_lock);
292 		return;
293 	}
294 
295 	/*
296 	 * Cache reference is the last, remove cache element and free
297 	 * page table object, returning the page table pages to the
298 	 * system.
299 	 */
300 	sx_sunlock(&idpgtbl_lock);
301 	sx_xlock(&idpgtbl_lock);
302 	LIST_FOREACH_SAFE(tbl, &idpgtbls, link, tbl1) {
303 		rmobj = tbl->pgtbl_obj;
304 		if (rmobj->ref_count == 1) {
305 			LIST_REMOVE(tbl, link);
306 			atomic_subtract_int(&iommu_tbl_pagecnt,
307 			    rmobj->resident_page_count);
308 			vm_object_deallocate(rmobj);
309 			free(tbl, M_DMAR_IDPGTBL);
310 		}
311 	}
312 	sx_xunlock(&idpgtbl_lock);
313 }
314 
315 /*
316  * The core routines to map and unmap host pages at the given guest
317  * address.  Support superpages.
318  */
319 
320 static iommu_pte_t *
321 dmar_pgtbl_map_pte(struct dmar_domain *domain, iommu_gaddr_t base, int lvl,
322     int flags, vm_pindex_t *idxp, struct sf_buf **sf)
323 {
324 	vm_page_t m;
325 	struct sf_buf *sfp;
326 	iommu_pte_t *pte, *ptep;
327 	vm_pindex_t idx, idx1;
328 
329 	DMAR_DOMAIN_ASSERT_PGLOCKED(domain);
330 	KASSERT((flags & IOMMU_PGF_OBJL) != 0, ("lost PGF_OBJL"));
331 
332 	idx = pglvl_pgtbl_get_pindex(domain->pglvl, base, lvl);
333 	if (*sf != NULL && idx == *idxp) {
334 		pte = (iommu_pte_t *)sf_buf_kva(*sf);
335 	} else {
336 		if (*sf != NULL)
337 			iommu_unmap_pgtbl(*sf);
338 		*idxp = idx;
339 retry:
340 		pte = iommu_map_pgtbl(domain->pgtbl_obj, idx, flags, sf);
341 		if (pte == NULL) {
342 			KASSERT(lvl > 0,
343 			    ("lost root page table page %p", domain));
344 			/*
345 			 * Page table page does not exist, allocate
346 			 * it and create a pte in the preceeding page level
347 			 * to reference the allocated page table page.
348 			 */
349 			m = iommu_pgalloc(domain->pgtbl_obj, idx, flags |
350 			    IOMMU_PGF_ZERO);
351 			if (m == NULL)
352 				return (NULL);
353 
354 			/*
355 			 * Prevent potential free while pgtbl_obj is
356 			 * unlocked in the recursive call to
357 			 * domain_pgtbl_map_pte(), if other thread did
358 			 * pte write and clean while the lock is
359 			 * dropped.
360 			 */
361 			vm_page_wire(m);
362 
363 			sfp = NULL;
364 			ptep = dmar_pgtbl_map_pte(domain, base, lvl - 1,
365 			    flags, &idx1, &sfp);
366 			if (ptep == NULL) {
367 				KASSERT(m->pindex != 0,
368 				    ("loosing root page %p", domain));
369 				vm_page_unwire_noq(m);
370 				iommu_pgfree(domain->pgtbl_obj, m->pindex,
371 				    flags, NULL);
372 				return (NULL);
373 			}
374 			dmar_pte_store(&ptep->pte, DMAR_PTE_R | DMAR_PTE_W |
375 			    VM_PAGE_TO_PHYS(m));
376 			dmar_flush_pte_to_ram(domain->dmar, ptep);
377 			vm_page_wire(sf_buf_page(sfp));
378 			vm_page_unwire_noq(m);
379 			iommu_unmap_pgtbl(sfp);
380 			/* Only executed once. */
381 			goto retry;
382 		}
383 	}
384 	pte += pglvl_pgtbl_pte_off(domain->pglvl, base, lvl);
385 	return (pte);
386 }
387 
388 static int
389 dmar_map_buf_locked(struct dmar_domain *domain, iommu_gaddr_t base,
390     iommu_gaddr_t size, vm_page_t *ma, uint64_t pflags, int flags,
391     struct iommu_map_entry *entry)
392 {
393 	iommu_pte_t *pte;
394 	struct sf_buf *sf;
395 	iommu_gaddr_t pg_sz, base1;
396 	vm_pindex_t pi, c, idx, run_sz;
397 	int lvl;
398 	bool superpage;
399 
400 	DMAR_DOMAIN_ASSERT_PGLOCKED(domain);
401 
402 	base1 = base;
403 	flags |= IOMMU_PGF_OBJL;
404 	TD_PREP_PINNED_ASSERT;
405 
406 	for (sf = NULL, pi = 0; size > 0; base += pg_sz, size -= pg_sz,
407 	    pi += run_sz) {
408 		for (lvl = 0, c = 0, superpage = false;; lvl++) {
409 			pg_sz = domain_page_size(domain, lvl);
410 			run_sz = pg_sz >> IOMMU_PAGE_SHIFT;
411 			if (lvl == domain->pglvl - 1)
412 				break;
413 			/*
414 			 * Check if the current base suitable for the
415 			 * superpage mapping.  First, verify the level.
416 			 */
417 			if (!domain_is_sp_lvl(domain, lvl))
418 				continue;
419 			/*
420 			 * Next, look at the size of the mapping and
421 			 * alignment of both guest and host addresses.
422 			 */
423 			if (size < pg_sz || (base & (pg_sz - 1)) != 0 ||
424 			    (VM_PAGE_TO_PHYS(ma[pi]) & (pg_sz - 1)) != 0)
425 				continue;
426 			/* All passed, check host pages contiguouty. */
427 			if (c == 0) {
428 				for (c = 1; c < run_sz; c++) {
429 					if (VM_PAGE_TO_PHYS(ma[pi + c]) !=
430 					    VM_PAGE_TO_PHYS(ma[pi + c - 1]) +
431 					    PAGE_SIZE)
432 						break;
433 				}
434 			}
435 			if (c >= run_sz) {
436 				superpage = true;
437 				break;
438 			}
439 		}
440 		KASSERT(size >= pg_sz,
441 		    ("mapping loop overflow %p %jx %jx %jx", domain,
442 		    (uintmax_t)base, (uintmax_t)size, (uintmax_t)pg_sz));
443 		KASSERT(pg_sz > 0, ("pg_sz 0 lvl %d", lvl));
444 		pte = dmar_pgtbl_map_pte(domain, base, lvl, flags, &idx, &sf);
445 		if (pte == NULL) {
446 			KASSERT((flags & IOMMU_PGF_WAITOK) == 0,
447 			    ("failed waitable pte alloc %p", domain));
448 			if (sf != NULL)
449 				iommu_unmap_pgtbl(sf);
450 			dmar_unmap_buf_locked(domain, base1, base - base1,
451 			    flags, entry);
452 			TD_PINNED_ASSERT;
453 			return (ENOMEM);
454 		}
455 		dmar_pte_store(&pte->pte, VM_PAGE_TO_PHYS(ma[pi]) | pflags |
456 		    (superpage ? DMAR_PTE_SP : 0));
457 		dmar_flush_pte_to_ram(domain->dmar, pte);
458 		vm_page_wire(sf_buf_page(sf));
459 	}
460 	if (sf != NULL)
461 		iommu_unmap_pgtbl(sf);
462 	TD_PINNED_ASSERT;
463 	return (0);
464 }
465 
466 static int
467 dmar_map_buf(struct iommu_domain *iodom, struct iommu_map_entry *entry,
468     vm_page_t *ma, uint64_t eflags, int flags)
469 {
470 	struct dmar_domain *domain;
471 	struct dmar_unit *unit;
472 	iommu_gaddr_t base, size;
473 	uint64_t pflags;
474 	int error;
475 
476 	base = entry->start;
477 	size  = entry->end - entry->start;
478 
479 	pflags = ((eflags & IOMMU_MAP_ENTRY_READ) != 0 ? DMAR_PTE_R : 0) |
480 	    ((eflags & IOMMU_MAP_ENTRY_WRITE) != 0 ? DMAR_PTE_W : 0) |
481 	    ((eflags & IOMMU_MAP_ENTRY_SNOOP) != 0 ? DMAR_PTE_SNP : 0) |
482 	    ((eflags & IOMMU_MAP_ENTRY_TM) != 0 ? DMAR_PTE_TM : 0);
483 
484 	domain = IODOM2DOM(iodom);
485 	unit = domain->dmar;
486 
487 	KASSERT((iodom->flags & IOMMU_DOMAIN_IDMAP) == 0,
488 	    ("modifying idmap pagetable domain %p", domain));
489 	KASSERT((base & IOMMU_PAGE_MASK) == 0,
490 	    ("non-aligned base %p %jx %jx", domain, (uintmax_t)base,
491 	    (uintmax_t)size));
492 	KASSERT((size & IOMMU_PAGE_MASK) == 0,
493 	    ("non-aligned size %p %jx %jx", domain, (uintmax_t)base,
494 	    (uintmax_t)size));
495 	KASSERT(size > 0, ("zero size %p %jx %jx", domain, (uintmax_t)base,
496 	    (uintmax_t)size));
497 	KASSERT(base < (1ULL << domain->agaw),
498 	    ("base too high %p %jx %jx agaw %d", domain, (uintmax_t)base,
499 	    (uintmax_t)size, domain->agaw));
500 	KASSERT(base + size < (1ULL << domain->agaw),
501 	    ("end too high %p %jx %jx agaw %d", domain, (uintmax_t)base,
502 	    (uintmax_t)size, domain->agaw));
503 	KASSERT(base + size > base,
504 	    ("size overflow %p %jx %jx", domain, (uintmax_t)base,
505 	    (uintmax_t)size));
506 	KASSERT((pflags & (DMAR_PTE_R | DMAR_PTE_W)) != 0,
507 	    ("neither read nor write %jx", (uintmax_t)pflags));
508 	KASSERT((pflags & ~(DMAR_PTE_R | DMAR_PTE_W | DMAR_PTE_SNP |
509 	    DMAR_PTE_TM)) == 0,
510 	    ("invalid pte flags %jx", (uintmax_t)pflags));
511 	KASSERT((pflags & DMAR_PTE_SNP) == 0 ||
512 	    (unit->hw_ecap & DMAR_ECAP_SC) != 0,
513 	    ("PTE_SNP for dmar without snoop control %p %jx",
514 	    domain, (uintmax_t)pflags));
515 	KASSERT((pflags & DMAR_PTE_TM) == 0 ||
516 	    (unit->hw_ecap & DMAR_ECAP_DI) != 0,
517 	    ("PTE_TM for dmar without DIOTLB %p %jx",
518 	    domain, (uintmax_t)pflags));
519 	KASSERT((flags & ~IOMMU_PGF_WAITOK) == 0, ("invalid flags %x", flags));
520 
521 	DMAR_DOMAIN_PGLOCK(domain);
522 	error = dmar_map_buf_locked(domain, base, size, ma, pflags, flags,
523 	    entry);
524 	DMAR_DOMAIN_PGUNLOCK(domain);
525 	if (error != 0)
526 		return (error);
527 
528 	if ((unit->hw_cap & DMAR_CAP_CM) != 0)
529 		dmar_flush_iotlb_sync(domain, base, size);
530 	else if ((unit->hw_cap & DMAR_CAP_RWBF) != 0) {
531 		/* See 11.1 Write Buffer Flushing. */
532 		DMAR_LOCK(unit);
533 		dmar_flush_write_bufs(unit);
534 		DMAR_UNLOCK(unit);
535 	}
536 	return (0);
537 }
538 
539 static void dmar_unmap_clear_pte(struct dmar_domain *domain,
540     iommu_gaddr_t base, int lvl, int flags, iommu_pte_t *pte,
541     struct sf_buf **sf, struct iommu_map_entry *entry, bool free_fs);
542 
543 static void
544 dmar_free_pgtbl_pde(struct dmar_domain *domain, iommu_gaddr_t base,
545     int lvl, int flags, struct iommu_map_entry *entry)
546 {
547 	struct sf_buf *sf;
548 	iommu_pte_t *pde;
549 	vm_pindex_t idx;
550 
551 	sf = NULL;
552 	pde = dmar_pgtbl_map_pte(domain, base, lvl, flags, &idx, &sf);
553 	dmar_unmap_clear_pte(domain, base, lvl, flags, pde, &sf,
554 	    entry, true);
555 }
556 
557 static void
558 dmar_unmap_clear_pte(struct dmar_domain *domain, iommu_gaddr_t base, int lvl,
559     int flags, iommu_pte_t *pte, struct sf_buf **sf,
560     struct iommu_map_entry *entry, bool free_sf)
561 {
562 	vm_page_t m;
563 
564 	dmar_pte_clear(&pte->pte);
565 	dmar_flush_pte_to_ram(domain->dmar, pte);
566 	m = sf_buf_page(*sf);
567 	if (free_sf) {
568 		iommu_unmap_pgtbl(*sf);
569 		*sf = NULL;
570 	}
571 	if (!vm_page_unwire_noq(m))
572 		return;
573 	KASSERT(lvl != 0,
574 	    ("lost reference (lvl) on root pg domain %p base %jx lvl %d",
575 	    domain, (uintmax_t)base, lvl));
576 	KASSERT(m->pindex != 0,
577 	    ("lost reference (idx) on root pg domain %p base %jx lvl %d",
578 	    domain, (uintmax_t)base, lvl));
579 	iommu_pgfree(domain->pgtbl_obj, m->pindex, flags, entry);
580 	dmar_free_pgtbl_pde(domain, base, lvl - 1, flags, entry);
581 }
582 
583 /*
584  * Assumes that the unmap is never partial.
585  */
586 static int
587 dmar_unmap_buf_locked(struct dmar_domain *domain, iommu_gaddr_t base,
588     iommu_gaddr_t size, int flags, struct iommu_map_entry *entry)
589 {
590 	iommu_pte_t *pte;
591 	struct sf_buf *sf;
592 	vm_pindex_t idx;
593 	iommu_gaddr_t pg_sz;
594 	int lvl;
595 
596 	DMAR_DOMAIN_ASSERT_PGLOCKED(domain);
597 	if (size == 0)
598 		return (0);
599 
600 	KASSERT((domain->iodom.flags & IOMMU_DOMAIN_IDMAP) == 0,
601 	    ("modifying idmap pagetable domain %p", domain));
602 	KASSERT((base & IOMMU_PAGE_MASK) == 0,
603 	    ("non-aligned base %p %jx %jx", domain, (uintmax_t)base,
604 	    (uintmax_t)size));
605 	KASSERT((size & IOMMU_PAGE_MASK) == 0,
606 	    ("non-aligned size %p %jx %jx", domain, (uintmax_t)base,
607 	    (uintmax_t)size));
608 	KASSERT(base < (1ULL << domain->agaw),
609 	    ("base too high %p %jx %jx agaw %d", domain, (uintmax_t)base,
610 	    (uintmax_t)size, domain->agaw));
611 	KASSERT(base + size < (1ULL << domain->agaw),
612 	    ("end too high %p %jx %jx agaw %d", domain, (uintmax_t)base,
613 	    (uintmax_t)size, domain->agaw));
614 	KASSERT(base + size > base,
615 	    ("size overflow %p %jx %jx", domain, (uintmax_t)base,
616 	    (uintmax_t)size));
617 	KASSERT((flags & ~IOMMU_PGF_WAITOK) == 0, ("invalid flags %x", flags));
618 
619 	pg_sz = 0; /* silence gcc */
620 	flags |= IOMMU_PGF_OBJL;
621 	TD_PREP_PINNED_ASSERT;
622 
623 	for (sf = NULL; size > 0; base += pg_sz, size -= pg_sz) {
624 		for (lvl = 0; lvl < domain->pglvl; lvl++) {
625 			if (lvl != domain->pglvl - 1 &&
626 			    !domain_is_sp_lvl(domain, lvl))
627 				continue;
628 			pg_sz = domain_page_size(domain, lvl);
629 			if (pg_sz > size)
630 				continue;
631 			pte = dmar_pgtbl_map_pte(domain, base, lvl, flags,
632 			    &idx, &sf);
633 			KASSERT(pte != NULL,
634 			    ("sleeping or page missed %p %jx %d 0x%x",
635 			    domain, (uintmax_t)base, lvl, flags));
636 			if ((pte->pte & DMAR_PTE_SP) != 0 ||
637 			    lvl == domain->pglvl - 1) {
638 				dmar_unmap_clear_pte(domain, base, lvl,
639 				    flags, pte, &sf, entry, false);
640 				break;
641 			}
642 		}
643 		KASSERT(size >= pg_sz,
644 		    ("unmapping loop overflow %p %jx %jx %jx", domain,
645 		    (uintmax_t)base, (uintmax_t)size, (uintmax_t)pg_sz));
646 	}
647 	if (sf != NULL)
648 		iommu_unmap_pgtbl(sf);
649 	/*
650 	 * See 11.1 Write Buffer Flushing for an explanation why RWBF
651 	 * can be ignored there.
652 	 */
653 
654 	TD_PINNED_ASSERT;
655 	return (0);
656 }
657 
658 static int
659 dmar_unmap_buf(struct iommu_domain *iodom, struct iommu_map_entry *entry,
660     int flags)
661 {
662 	struct dmar_domain *domain;
663 	int error;
664 
665 	domain = IODOM2DOM(iodom);
666 
667 	DMAR_DOMAIN_PGLOCK(domain);
668 	error = dmar_unmap_buf_locked(domain, entry->start, entry->end -
669 	    entry->start, flags, entry);
670 	DMAR_DOMAIN_PGUNLOCK(domain);
671 	return (error);
672 }
673 
674 int
675 dmar_domain_alloc_pgtbl(struct dmar_domain *domain)
676 {
677 	vm_page_t m;
678 
679 	KASSERT(domain->pgtbl_obj == NULL,
680 	    ("already initialized %p", domain));
681 
682 	domain->pgtbl_obj = vm_pager_allocate(OBJT_PHYS, NULL,
683 	    IDX_TO_OFF(pglvl_max_pages(domain->pglvl)), 0, 0, NULL);
684 	DMAR_DOMAIN_PGLOCK(domain);
685 	m = iommu_pgalloc(domain->pgtbl_obj, 0, IOMMU_PGF_WAITOK |
686 	    IOMMU_PGF_ZERO | IOMMU_PGF_OBJL);
687 	/* No implicit free of the top level page table page. */
688 	vm_page_wire(m);
689 	DMAR_DOMAIN_PGUNLOCK(domain);
690 	DMAR_LOCK(domain->dmar);
691 	domain->iodom.flags |= IOMMU_DOMAIN_PGTBL_INITED;
692 	DMAR_UNLOCK(domain->dmar);
693 	return (0);
694 }
695 
696 void
697 dmar_domain_free_pgtbl(struct dmar_domain *domain)
698 {
699 	vm_object_t obj;
700 	vm_page_t m;
701 
702 	obj = domain->pgtbl_obj;
703 	if (obj == NULL) {
704 		KASSERT((domain->dmar->hw_ecap & DMAR_ECAP_PT) != 0 &&
705 		    (domain->iodom.flags & IOMMU_DOMAIN_IDMAP) != 0,
706 		    ("lost pagetable object domain %p", domain));
707 		return;
708 	}
709 	DMAR_DOMAIN_ASSERT_PGLOCKED(domain);
710 	domain->pgtbl_obj = NULL;
711 
712 	if ((domain->iodom.flags & IOMMU_DOMAIN_IDMAP) != 0) {
713 		dmar_put_idmap_pgtbl(obj);
714 		domain->iodom.flags &= ~IOMMU_DOMAIN_IDMAP;
715 		return;
716 	}
717 
718 	/* Obliterate ref_counts */
719 	VM_OBJECT_ASSERT_WLOCKED(obj);
720 	for (m = vm_page_lookup(obj, 0); m != NULL; m = vm_page_next(m)) {
721 		vm_page_clearref(m);
722 		vm_wire_sub(1);
723 	}
724 	VM_OBJECT_WUNLOCK(obj);
725 	vm_object_deallocate(obj);
726 }
727 
728 static inline uint64_t
729 dmar_wait_iotlb_flush(struct dmar_unit *unit, uint64_t wt, int iro)
730 {
731 	uint64_t iotlbr;
732 
733 	dmar_write8(unit, iro + DMAR_IOTLB_REG_OFF, DMAR_IOTLB_IVT |
734 	    DMAR_IOTLB_DR | DMAR_IOTLB_DW | wt);
735 	for (;;) {
736 		iotlbr = dmar_read8(unit, iro + DMAR_IOTLB_REG_OFF);
737 		if ((iotlbr & DMAR_IOTLB_IVT) == 0)
738 			break;
739 		cpu_spinwait();
740 	}
741 	return (iotlbr);
742 }
743 
744 void
745 dmar_flush_iotlb_sync(struct dmar_domain *domain, iommu_gaddr_t base,
746     iommu_gaddr_t size)
747 {
748 	struct dmar_unit *unit;
749 	iommu_gaddr_t isize;
750 	uint64_t iotlbr;
751 	int am, iro;
752 
753 	unit = domain->dmar;
754 	KASSERT(!unit->qi_enabled, ("dmar%d: sync iotlb flush call",
755 	    unit->iommu.unit));
756 	iro = DMAR_ECAP_IRO(unit->hw_ecap) * 16;
757 	DMAR_LOCK(unit);
758 	if ((unit->hw_cap & DMAR_CAP_PSI) == 0 || size > 2 * 1024 * 1024) {
759 		iotlbr = dmar_wait_iotlb_flush(unit, DMAR_IOTLB_IIRG_DOM |
760 		    DMAR_IOTLB_DID(domain->domain), iro);
761 		KASSERT((iotlbr & DMAR_IOTLB_IAIG_MASK) !=
762 		    DMAR_IOTLB_IAIG_INVLD,
763 		    ("dmar%d: invalidation failed %jx", unit->iommu.unit,
764 		    (uintmax_t)iotlbr));
765 	} else {
766 		for (; size > 0; base += isize, size -= isize) {
767 			am = calc_am(unit, base, size, &isize);
768 			dmar_write8(unit, iro, base | am);
769 			iotlbr = dmar_wait_iotlb_flush(unit,
770 			    DMAR_IOTLB_IIRG_PAGE |
771 			    DMAR_IOTLB_DID(domain->domain), iro);
772 			KASSERT((iotlbr & DMAR_IOTLB_IAIG_MASK) !=
773 			    DMAR_IOTLB_IAIG_INVLD,
774 			    ("dmar%d: PSI invalidation failed "
775 			    "iotlbr 0x%jx base 0x%jx size 0x%jx am %d",
776 			    unit->iommu.unit, (uintmax_t)iotlbr,
777 			    (uintmax_t)base, (uintmax_t)size, am));
778 			/*
779 			 * Any non-page granularity covers whole guest
780 			 * address space for the domain.
781 			 */
782 			if ((iotlbr & DMAR_IOTLB_IAIG_MASK) !=
783 			    DMAR_IOTLB_IAIG_PAGE)
784 				break;
785 		}
786 	}
787 	DMAR_UNLOCK(unit);
788 }
789 
790 const struct iommu_domain_map_ops dmar_domain_map_ops = {
791 	.map = dmar_map_buf,
792 	.unmap = dmar_unmap_buf,
793 };
794