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