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