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