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