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