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