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