]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/iommu/busdma_iommu.c
o Move the buswide_ctxs bitmap to iommu_unit and rename related functions.
[FreeBSD/FreeBSD.git] / sys / dev / iommu / busdma_iommu.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/domainset.h>
38 #include <sys/malloc.h>
39 #include <sys/bus.h>
40 #include <sys/conf.h>
41 #include <sys/interrupt.h>
42 #include <sys/kernel.h>
43 #include <sys/ktr.h>
44 #include <sys/lock.h>
45 #include <sys/proc.h>
46 #include <sys/memdesc.h>
47 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
49 #include <sys/rman.h>
50 #include <sys/taskqueue.h>
51 #include <sys/tree.h>
52 #include <sys/uio.h>
53 #include <sys/vmem.h>
54 #include <dev/pci/pcireg.h>
55 #include <dev/pci/pcivar.h>
56 #include <vm/vm.h>
57 #include <vm/vm_extern.h>
58 #include <vm/vm_kern.h>
59 #include <vm/vm_object.h>
60 #include <vm/vm_page.h>
61 #include <vm/vm_map.h>
62 #include <machine/atomic.h>
63 #include <machine/bus.h>
64 #include <machine/md_var.h>
65 #if defined(__amd64__) || defined(__i386__)
66 #include <machine/specialreg.h>
67 #include <x86/include/busdma_impl.h>
68 #include <x86/iommu/intel_reg.h>
69 #include <dev/iommu/busdma_iommu.h>
70 #include <dev/iommu/iommu.h>
71 #include <x86/iommu/intel_dmar.h>
72 #endif
73
74 /*
75  * busdma_iommu.c, the implementation of the busdma(9) interface using
76  * IOMMU units from Intel VT-d.
77  */
78
79 static bool
80 iommu_bus_dma_is_dev_disabled(int domain, int bus, int slot, int func)
81 {
82         char str[128], *env;
83         int default_bounce;
84         bool ret;
85         static const char bounce_str[] = "bounce";
86         static const char iommu_str[] = "iommu";
87         static const char dmar_str[] = "dmar"; /* compatibility */
88
89         default_bounce = 0;
90         env = kern_getenv("hw.busdma.default");
91         if (env != NULL) {
92                 if (strcmp(env, bounce_str) == 0)
93                         default_bounce = 1;
94                 else if (strcmp(env, iommu_str) == 0 ||
95                     strcmp(env, dmar_str) == 0)
96                         default_bounce = 0;
97                 freeenv(env);
98         }
99
100         snprintf(str, sizeof(str), "hw.busdma.pci%d.%d.%d.%d",
101             domain, bus, slot, func);
102         env = kern_getenv(str);
103         if (env == NULL)
104                 return (default_bounce != 0);
105         if (strcmp(env, bounce_str) == 0)
106                 ret = true;
107         else if (strcmp(env, iommu_str) == 0 ||
108             strcmp(env, dmar_str) == 0)
109                 ret = false;
110         else
111                 ret = default_bounce != 0;
112         freeenv(env);
113         return (ret);
114 }
115
116 /*
117  * Given original device, find the requester ID that will be seen by
118  * the IOMMU unit and used for page table lookup.  PCI bridges may take
119  * ownership of transactions from downstream devices, so it may not be
120  * the same as the BSF of the target device.  In those cases, all
121  * devices downstream of the bridge must share a single mapping
122  * domain, and must collectively be assigned to use either IOMMU or
123  * bounce mapping.
124  */
125 device_t
126 iommu_get_requester(device_t dev, uint16_t *rid)
127 {
128         devclass_t pci_class;
129         device_t l, pci, pcib, pcip, pcibp, requester;
130         int cap_offset;
131         uint16_t pcie_flags;
132         bool bridge_is_pcie;
133
134         pci_class = devclass_find("pci");
135         l = requester = dev;
136
137         *rid = pci_get_rid(dev);
138
139         /*
140          * Walk the bridge hierarchy from the target device to the
141          * host port to find the translating bridge nearest the IOMMU
142          * unit.
143          */
144         for (;;) {
145                 pci = device_get_parent(l);
146                 KASSERT(pci != NULL, ("iommu_get_requester(%s): NULL parent "
147                     "for %s", device_get_name(dev), device_get_name(l)));
148                 KASSERT(device_get_devclass(pci) == pci_class,
149                     ("iommu_get_requester(%s): non-pci parent %s for %s",
150                     device_get_name(dev), device_get_name(pci),
151                     device_get_name(l)));
152
153                 pcib = device_get_parent(pci);
154                 KASSERT(pcib != NULL, ("iommu_get_requester(%s): NULL bridge "
155                     "for %s", device_get_name(dev), device_get_name(pci)));
156
157                 /*
158                  * The parent of our "bridge" isn't another PCI bus,
159                  * so pcib isn't a PCI->PCI bridge but rather a host
160                  * port, and the requester ID won't be translated
161                  * further.
162                  */
163                 pcip = device_get_parent(pcib);
164                 if (device_get_devclass(pcip) != pci_class)
165                         break;
166                 pcibp = device_get_parent(pcip);
167
168                 if (pci_find_cap(l, PCIY_EXPRESS, &cap_offset) == 0) {
169                         /*
170                          * Do not stop the loop even if the target
171                          * device is PCIe, because it is possible (but
172                          * unlikely) to have a PCI->PCIe bridge
173                          * somewhere in the hierarchy.
174                          */
175                         l = pcib;
176                 } else {
177                         /*
178                          * Device is not PCIe, it cannot be seen as a
179                          * requester by IOMMU unit.  Check whether the
180                          * bridge is PCIe.
181                          */
182                         bridge_is_pcie = pci_find_cap(pcib, PCIY_EXPRESS,
183                             &cap_offset) == 0;
184                         requester = pcib;
185
186                         /*
187                          * Check for a buggy PCIe/PCI bridge that
188                          * doesn't report the express capability.  If
189                          * the bridge above it is express but isn't a
190                          * PCI bridge, then we know pcib is actually a
191                          * PCIe/PCI bridge.
192                          */
193                         if (!bridge_is_pcie && pci_find_cap(pcibp,
194                             PCIY_EXPRESS, &cap_offset) == 0) {
195                                 pcie_flags = pci_read_config(pcibp,
196                                     cap_offset + PCIER_FLAGS, 2);
197                                 if ((pcie_flags & PCIEM_FLAGS_TYPE) !=
198                                     PCIEM_TYPE_PCI_BRIDGE)
199                                         bridge_is_pcie = true;
200                         }
201
202                         if (bridge_is_pcie) {
203                                 /*
204                                  * The current device is not PCIe, but
205                                  * the bridge above it is.  This is a
206                                  * PCIe->PCI bridge.  Assume that the
207                                  * requester ID will be the secondary
208                                  * bus number with slot and function
209                                  * set to zero.
210                                  *
211                                  * XXX: Doesn't handle the case where
212                                  * the bridge is PCIe->PCI-X, and the
213                                  * bridge will only take ownership of
214                                  * requests in some cases.  We should
215                                  * provide context entries with the
216                                  * same page tables for taken and
217                                  * non-taken transactions.
218                                  */
219                                 *rid = PCI_RID(pci_get_bus(l), 0, 0);
220                                 l = pcibp;
221                         } else {
222                                 /*
223                                  * Neither the device nor the bridge
224                                  * above it are PCIe.  This is a
225                                  * conventional PCI->PCI bridge, which
226                                  * will use the bridge's BSF as the
227                                  * requester ID.
228                                  */
229                                 *rid = pci_get_rid(pcib);
230                                 l = pcib;
231                         }
232                 }
233         }
234         return (requester);
235 }
236
237 struct iommu_ctx *
238 iommu_instantiate_ctx(struct iommu_unit *unit, device_t dev, bool rmrr)
239 {
240         device_t requester;
241         struct iommu_ctx *ctx;
242         bool disabled;
243         uint16_t rid;
244
245         requester = iommu_get_requester(dev, &rid);
246
247         /*
248          * If the user requested the IOMMU disabled for the device, we
249          * cannot disable the IOMMU unit, due to possibility of other
250          * devices on the same IOMMU unit still requiring translation.
251          * Instead provide the identity mapping for the device
252          * context.
253          */
254         disabled = iommu_bus_dma_is_dev_disabled(pci_get_domain(requester),
255             pci_get_bus(requester), pci_get_slot(requester), 
256             pci_get_function(requester));
257         ctx = iommu_get_ctx(unit, requester, rid, disabled, rmrr);
258         if (ctx == NULL)
259                 return (NULL);
260         if (disabled) {
261                 /*
262                  * Keep the first reference on context, release the
263                  * later refs.
264                  */
265                 IOMMU_LOCK(unit);
266                 if ((ctx->flags & IOMMU_CTX_DISABLED) == 0) {
267                         ctx->flags |= IOMMU_CTX_DISABLED;
268                         IOMMU_UNLOCK(unit);
269                 } else {
270                         iommu_free_ctx_locked(unit, ctx);
271                 }
272                 ctx = NULL;
273         }
274         return (ctx);
275 }
276
277 bus_dma_tag_t
278 acpi_iommu_get_dma_tag(device_t dev, device_t child)
279 {
280         struct iommu_unit *unit;
281         struct iommu_ctx *ctx;
282         bus_dma_tag_t res;
283
284         unit = iommu_find(child, bootverbose);
285         /* Not in scope of any IOMMU ? */
286         if (unit == NULL)
287                 return (NULL);
288         if (!unit->dma_enabled)
289                 return (NULL);
290
291 #if defined(__amd64__) || defined(__i386__)
292         dmar_quirks_pre_use(unit);
293         dmar_instantiate_rmrr_ctxs(unit);
294 #endif
295
296         ctx = iommu_instantiate_ctx(unit, child, false);
297         res = ctx == NULL ? NULL : (bus_dma_tag_t)ctx->tag;
298         return (res);
299 }
300
301 bool
302 bus_dma_iommu_set_buswide(device_t dev)
303 {
304         struct iommu_unit *unit;
305         device_t parent;
306         u_int busno, slot, func;
307
308         parent = device_get_parent(dev);
309         if (device_get_devclass(parent) != devclass_find("pci"))
310                 return (false);
311         unit = iommu_find(dev, bootverbose);
312         if (unit == NULL)
313                 return (false);
314         busno = pci_get_bus(dev);
315         slot = pci_get_slot(dev);
316         func = pci_get_function(dev);
317         if (slot != 0 || func != 0) {
318                 if (bootverbose) {
319                         device_printf(dev,
320                             "iommu%d pci%d:%d:%d requested buswide busdma\n",
321                             unit->unit, busno, slot, func);
322                 }
323                 return (false);
324         }
325         iommu_set_buswide_ctx(unit, busno);
326         return (true);
327 }
328
329 static MALLOC_DEFINE(M_IOMMU_DMAMAP, "iommu_dmamap", "IOMMU DMA Map");
330
331 static void iommu_bus_schedule_dmamap(struct iommu_unit *unit,
332     struct bus_dmamap_iommu *map);
333
334 static int
335 iommu_bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
336     bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
337     bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
338     int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
339     void *lockfuncarg, bus_dma_tag_t *dmat)
340 {
341         struct bus_dma_tag_iommu *newtag, *oldtag;
342         int error;
343
344         *dmat = NULL;
345         error = common_bus_dma_tag_create(parent != NULL ?
346             &((struct bus_dma_tag_iommu *)parent)->common : NULL, alignment,
347             boundary, lowaddr, highaddr, filter, filterarg, maxsize,
348             nsegments, maxsegsz, flags, lockfunc, lockfuncarg,
349             sizeof(struct bus_dma_tag_iommu), (void **)&newtag);
350         if (error != 0)
351                 goto out;
352
353         oldtag = (struct bus_dma_tag_iommu *)parent;
354         newtag->common.impl = &bus_dma_iommu_impl;
355         newtag->ctx = oldtag->ctx;
356         newtag->owner = oldtag->owner;
357
358         *dmat = (bus_dma_tag_t)newtag;
359 out:
360         CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
361             __func__, newtag, (newtag != NULL ? newtag->common.flags : 0),
362             error);
363         return (error);
364 }
365
366 static int
367 iommu_bus_dma_tag_set_domain(bus_dma_tag_t dmat)
368 {
369
370         return (0);
371 }
372
373 static int
374 iommu_bus_dma_tag_destroy(bus_dma_tag_t dmat1)
375 {
376         struct bus_dma_tag_iommu *dmat, *dmat_copy, *parent;
377         int error;
378
379         error = 0;
380         dmat_copy = dmat = (struct bus_dma_tag_iommu *)dmat1;
381
382         if (dmat != NULL) {
383                 if (dmat->map_count != 0) {
384                         error = EBUSY;
385                         goto out;
386                 }
387                 while (dmat != NULL) {
388                         parent = (struct bus_dma_tag_iommu *)dmat->common.parent;
389                         if (atomic_fetchadd_int(&dmat->common.ref_count, -1) ==
390                             1) {
391                                 if (dmat == dmat->ctx->tag)
392                                         iommu_free_ctx(dmat->ctx);
393                                 free_domain(dmat->segments, M_IOMMU_DMAMAP);
394                                 free(dmat, M_DEVBUF);
395                                 dmat = parent;
396                         } else
397                                 dmat = NULL;
398                 }
399         }
400 out:
401         CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
402         return (error);
403 }
404
405 static bool
406 iommu_bus_dma_id_mapped(bus_dma_tag_t dmat, vm_paddr_t buf, bus_size_t buflen)
407 {
408
409         return (false);
410 }
411
412 static int
413 iommu_bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
414 {
415         struct bus_dma_tag_iommu *tag;
416         struct bus_dmamap_iommu *map;
417
418         tag = (struct bus_dma_tag_iommu *)dmat;
419         map = malloc_domainset(sizeof(*map), M_IOMMU_DMAMAP,
420             DOMAINSET_PREF(tag->common.domain), M_NOWAIT | M_ZERO);
421         if (map == NULL) {
422                 *mapp = NULL;
423                 return (ENOMEM);
424         }
425         if (tag->segments == NULL) {
426                 tag->segments = malloc_domainset(sizeof(bus_dma_segment_t) *
427                     tag->common.nsegments, M_IOMMU_DMAMAP,
428                     DOMAINSET_PREF(tag->common.domain), M_NOWAIT);
429                 if (tag->segments == NULL) {
430                         free_domain(map, M_IOMMU_DMAMAP);
431                         *mapp = NULL;
432                         return (ENOMEM);
433                 }
434         }
435         TAILQ_INIT(&map->map_entries);
436         map->tag = tag;
437         map->locked = true;
438         map->cansleep = false;
439         tag->map_count++;
440         *mapp = (bus_dmamap_t)map;
441
442         return (0);
443 }
444
445 static int
446 iommu_bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map1)
447 {
448         struct bus_dma_tag_iommu *tag;
449         struct bus_dmamap_iommu *map;
450         struct iommu_domain *domain;
451
452         tag = (struct bus_dma_tag_iommu *)dmat;
453         map = (struct bus_dmamap_iommu *)map1;
454         if (map != NULL) {
455                 domain = tag->ctx->domain;
456                 IOMMU_DOMAIN_LOCK(domain);
457                 if (!TAILQ_EMPTY(&map->map_entries)) {
458                         IOMMU_DOMAIN_UNLOCK(domain);
459                         return (EBUSY);
460                 }
461                 IOMMU_DOMAIN_UNLOCK(domain);
462                 free_domain(map, M_IOMMU_DMAMAP);
463         }
464         tag->map_count--;
465         return (0);
466 }
467
468
469 static int
470 iommu_bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
471     bus_dmamap_t *mapp)
472 {
473         struct bus_dma_tag_iommu *tag;
474         struct bus_dmamap_iommu *map;
475         int error, mflags;
476         vm_memattr_t attr;
477
478         error = iommu_bus_dmamap_create(dmat, flags, mapp);
479         if (error != 0)
480                 return (error);
481
482         mflags = (flags & BUS_DMA_NOWAIT) != 0 ? M_NOWAIT : M_WAITOK;
483         mflags |= (flags & BUS_DMA_ZERO) != 0 ? M_ZERO : 0;
484         attr = (flags & BUS_DMA_NOCACHE) != 0 ? VM_MEMATTR_UNCACHEABLE :
485             VM_MEMATTR_DEFAULT;
486
487         tag = (struct bus_dma_tag_iommu *)dmat;
488         map = (struct bus_dmamap_iommu *)*mapp;
489
490         if (tag->common.maxsize < PAGE_SIZE &&
491             tag->common.alignment <= tag->common.maxsize &&
492             attr == VM_MEMATTR_DEFAULT) {
493                 *vaddr = malloc_domainset(tag->common.maxsize, M_DEVBUF,
494                     DOMAINSET_PREF(tag->common.domain), mflags);
495                 map->flags |= BUS_DMAMAP_IOMMU_MALLOC;
496         } else {
497                 *vaddr = (void *)kmem_alloc_attr_domainset(
498                     DOMAINSET_PREF(tag->common.domain), tag->common.maxsize,
499                     mflags, 0ul, BUS_SPACE_MAXADDR, attr);
500                 map->flags |= BUS_DMAMAP_IOMMU_KMEM_ALLOC;
501         }
502         if (*vaddr == NULL) {
503                 iommu_bus_dmamap_destroy(dmat, *mapp);
504                 *mapp = NULL;
505                 return (ENOMEM);
506         }
507         return (0);
508 }
509
510 static void
511 iommu_bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map1)
512 {
513         struct bus_dma_tag_iommu *tag;
514         struct bus_dmamap_iommu *map;
515
516         tag = (struct bus_dma_tag_iommu *)dmat;
517         map = (struct bus_dmamap_iommu *)map1;
518
519         if ((map->flags & BUS_DMAMAP_IOMMU_MALLOC) != 0) {
520                 free_domain(vaddr, M_DEVBUF);
521                 map->flags &= ~BUS_DMAMAP_IOMMU_MALLOC;
522         } else {
523                 KASSERT((map->flags & BUS_DMAMAP_IOMMU_KMEM_ALLOC) != 0,
524                     ("iommu_bus_dmamem_free for non alloced map %p", map));
525                 kmem_free((vm_offset_t)vaddr, tag->common.maxsize);
526                 map->flags &= ~BUS_DMAMAP_IOMMU_KMEM_ALLOC;
527         }
528
529         iommu_bus_dmamap_destroy(dmat, map1);
530 }
531
532 static int
533 iommu_bus_dmamap_load_something1(struct bus_dma_tag_iommu *tag,
534     struct bus_dmamap_iommu *map, vm_page_t *ma, int offset, bus_size_t buflen,
535     int flags, bus_dma_segment_t *segs, int *segp,
536     struct iommu_map_entries_tailq *unroll_list)
537 {
538         struct iommu_ctx *ctx;
539         struct iommu_domain *domain;
540         struct iommu_map_entry *entry;
541         iommu_gaddr_t size;
542         bus_size_t buflen1;
543         int error, idx, gas_flags, seg;
544
545         KASSERT(offset < IOMMU_PAGE_SIZE, ("offset %d", offset));
546         if (segs == NULL)
547                 segs = tag->segments;
548         ctx = tag->ctx;
549         domain = ctx->domain;
550         seg = *segp;
551         error = 0;
552         idx = 0;
553         while (buflen > 0) {
554                 seg++;
555                 if (seg >= tag->common.nsegments) {
556                         error = EFBIG;
557                         break;
558                 }
559                 buflen1 = buflen > tag->common.maxsegsz ?
560                     tag->common.maxsegsz : buflen;
561                 size = round_page(offset + buflen1);
562
563                 /*
564                  * (Too) optimistically allow split if there are more
565                  * then one segments left.
566                  */
567                 gas_flags = map->cansleep ? IOMMU_MF_CANWAIT : 0;
568                 if (seg + 1 < tag->common.nsegments)
569                         gas_flags |= IOMMU_MF_CANSPLIT;
570
571                 error = iommu_map(domain, &tag->common, size, offset,
572                     IOMMU_MAP_ENTRY_READ |
573                     ((flags & BUS_DMA_NOWRITE) == 0 ? IOMMU_MAP_ENTRY_WRITE : 0),
574                     gas_flags, ma + idx, &entry);
575                 if (error != 0)
576                         break;
577                 if ((gas_flags & IOMMU_MF_CANSPLIT) != 0) {
578                         KASSERT(size >= entry->end - entry->start,
579                             ("split increased entry size %jx %jx %jx",
580                             (uintmax_t)size, (uintmax_t)entry->start,
581                             (uintmax_t)entry->end));
582                         size = entry->end - entry->start;
583                         if (buflen1 > size)
584                                 buflen1 = size;
585                 } else {
586                         KASSERT(entry->end - entry->start == size,
587                             ("no split allowed %jx %jx %jx",
588                             (uintmax_t)size, (uintmax_t)entry->start,
589                             (uintmax_t)entry->end));
590                 }
591                 if (offset + buflen1 > size)
592                         buflen1 = size - offset;
593                 if (buflen1 > tag->common.maxsegsz)
594                         buflen1 = tag->common.maxsegsz;
595
596                 KASSERT(((entry->start + offset) & (tag->common.alignment - 1))
597                     == 0,
598                     ("alignment failed: ctx %p start 0x%jx offset %x "
599                     "align 0x%jx", ctx, (uintmax_t)entry->start, offset,
600                     (uintmax_t)tag->common.alignment));
601                 KASSERT(entry->end <= tag->common.lowaddr ||
602                     entry->start >= tag->common.highaddr,
603                     ("entry placement failed: ctx %p start 0x%jx end 0x%jx "
604                     "lowaddr 0x%jx highaddr 0x%jx", ctx,
605                     (uintmax_t)entry->start, (uintmax_t)entry->end,
606                     (uintmax_t)tag->common.lowaddr,
607                     (uintmax_t)tag->common.highaddr));
608                 KASSERT(iommu_test_boundary(entry->start + offset, buflen1,
609                     tag->common.boundary),
610                     ("boundary failed: ctx %p start 0x%jx end 0x%jx "
611                     "boundary 0x%jx", ctx, (uintmax_t)entry->start,
612                     (uintmax_t)entry->end, (uintmax_t)tag->common.boundary));
613                 KASSERT(buflen1 <= tag->common.maxsegsz,
614                     ("segment too large: ctx %p start 0x%jx end 0x%jx "
615                     "buflen1 0x%jx maxsegsz 0x%jx", ctx,
616                     (uintmax_t)entry->start, (uintmax_t)entry->end,
617                     (uintmax_t)buflen1, (uintmax_t)tag->common.maxsegsz));
618
619                 IOMMU_DOMAIN_LOCK(domain);
620                 TAILQ_INSERT_TAIL(&map->map_entries, entry, dmamap_link);
621                 entry->flags |= IOMMU_MAP_ENTRY_MAP;
622                 IOMMU_DOMAIN_UNLOCK(domain);
623                 TAILQ_INSERT_TAIL(unroll_list, entry, unroll_link);
624
625                 segs[seg].ds_addr = entry->start + offset;
626                 segs[seg].ds_len = buflen1;
627
628                 idx += OFF_TO_IDX(trunc_page(offset + buflen1));
629                 offset += buflen1;
630                 offset &= IOMMU_PAGE_MASK;
631                 buflen -= buflen1;
632         }
633         if (error == 0)
634                 *segp = seg;
635         return (error);
636 }
637
638 static int
639 iommu_bus_dmamap_load_something(struct bus_dma_tag_iommu *tag,
640     struct bus_dmamap_iommu *map, vm_page_t *ma, int offset, bus_size_t buflen,
641     int flags, bus_dma_segment_t *segs, int *segp)
642 {
643         struct iommu_ctx *ctx;
644         struct iommu_domain *domain;
645         struct iommu_map_entry *entry, *entry1;
646         struct iommu_map_entries_tailq unroll_list;
647         int error;
648
649         ctx = tag->ctx;
650         domain = ctx->domain;
651         atomic_add_long(&ctx->loads, 1);
652
653         TAILQ_INIT(&unroll_list);
654         error = iommu_bus_dmamap_load_something1(tag, map, ma, offset,
655             buflen, flags, segs, segp, &unroll_list);
656         if (error != 0) {
657                 /*
658                  * The busdma interface does not allow us to report
659                  * partial buffer load, so unfortunately we have to
660                  * revert all work done.
661                  */
662                 IOMMU_DOMAIN_LOCK(domain);
663                 TAILQ_FOREACH_SAFE(entry, &unroll_list, unroll_link,
664                     entry1) {
665                         /*
666                          * No entries other than what we have created
667                          * during the failed run might have been
668                          * inserted there in between, since we own ctx
669                          * pglock.
670                          */
671                         TAILQ_REMOVE(&map->map_entries, entry, dmamap_link);
672                         TAILQ_REMOVE(&unroll_list, entry, unroll_link);
673                         TAILQ_INSERT_TAIL(&domain->unload_entries, entry,
674                             dmamap_link);
675                 }
676                 IOMMU_DOMAIN_UNLOCK(domain);
677                 taskqueue_enqueue(domain->iommu->delayed_taskqueue,
678                     &domain->unload_task);
679         }
680
681         if (error == ENOMEM && (flags & BUS_DMA_NOWAIT) == 0 &&
682             !map->cansleep)
683                 error = EINPROGRESS;
684         if (error == EINPROGRESS)
685                 iommu_bus_schedule_dmamap(domain->iommu, map);
686         return (error);
687 }
688
689 static int
690 iommu_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map1,
691     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
692     bus_dma_segment_t *segs, int *segp)
693 {
694         struct bus_dma_tag_iommu *tag;
695         struct bus_dmamap_iommu *map;
696
697         tag = (struct bus_dma_tag_iommu *)dmat;
698         map = (struct bus_dmamap_iommu *)map1;
699         return (iommu_bus_dmamap_load_something(tag, map, ma, ma_offs, tlen,
700             flags, segs, segp));
701 }
702
703 static int
704 iommu_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map1,
705     vm_paddr_t buf, bus_size_t buflen, int flags, bus_dma_segment_t *segs,
706     int *segp)
707 {
708         struct bus_dma_tag_iommu *tag;
709         struct bus_dmamap_iommu *map;
710         vm_page_t *ma, fma;
711         vm_paddr_t pstart, pend, paddr;
712         int error, i, ma_cnt, mflags, offset;
713
714         tag = (struct bus_dma_tag_iommu *)dmat;
715         map = (struct bus_dmamap_iommu *)map1;
716         pstart = trunc_page(buf);
717         pend = round_page(buf + buflen);
718         offset = buf & PAGE_MASK;
719         ma_cnt = OFF_TO_IDX(pend - pstart);
720         mflags = map->cansleep ? M_WAITOK : M_NOWAIT;
721         ma = malloc(sizeof(vm_page_t) * ma_cnt, M_DEVBUF, mflags);
722         if (ma == NULL)
723                 return (ENOMEM);
724         fma = NULL;
725         for (i = 0; i < ma_cnt; i++) {
726                 paddr = pstart + ptoa(i);
727                 ma[i] = PHYS_TO_VM_PAGE(paddr);
728                 if (ma[i] == NULL || VM_PAGE_TO_PHYS(ma[i]) != paddr) {
729                         /*
730                          * If PHYS_TO_VM_PAGE() returned NULL or the
731                          * vm_page was not initialized we'll use a
732                          * fake page.
733                          */
734                         if (fma == NULL) {
735                                 fma = malloc(sizeof(struct vm_page) * ma_cnt,
736                                     M_DEVBUF, M_ZERO | mflags);
737                                 if (fma == NULL) {
738                                         free(ma, M_DEVBUF);
739                                         return (ENOMEM);
740                                 }
741                         }
742                         vm_page_initfake(&fma[i], pstart + ptoa(i),
743                             VM_MEMATTR_DEFAULT);
744                         ma[i] = &fma[i];
745                 }
746         }
747         error = iommu_bus_dmamap_load_something(tag, map, ma, offset, buflen,
748             flags, segs, segp);
749         free(fma, M_DEVBUF);
750         free(ma, M_DEVBUF);
751         return (error);
752 }
753
754 static int
755 iommu_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map1, void *buf,
756     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
757     int *segp)
758 {
759         struct bus_dma_tag_iommu *tag;
760         struct bus_dmamap_iommu *map;
761         vm_page_t *ma, fma;
762         vm_paddr_t pstart, pend, paddr;
763         int error, i, ma_cnt, mflags, offset;
764
765         tag = (struct bus_dma_tag_iommu *)dmat;
766         map = (struct bus_dmamap_iommu *)map1;
767         pstart = trunc_page((vm_offset_t)buf);
768         pend = round_page((vm_offset_t)buf + buflen);
769         offset = (vm_offset_t)buf & PAGE_MASK;
770         ma_cnt = OFF_TO_IDX(pend - pstart);
771         mflags = map->cansleep ? M_WAITOK : M_NOWAIT;
772         ma = malloc(sizeof(vm_page_t) * ma_cnt, M_DEVBUF, mflags);
773         if (ma == NULL)
774                 return (ENOMEM);
775         fma = NULL;
776         for (i = 0; i < ma_cnt; i++, pstart += PAGE_SIZE) {
777                 if (pmap == kernel_pmap)
778                         paddr = pmap_kextract(pstart);
779                 else
780                         paddr = pmap_extract(pmap, pstart);
781                 ma[i] = PHYS_TO_VM_PAGE(paddr);
782                 if (ma[i] == NULL || VM_PAGE_TO_PHYS(ma[i]) != paddr) {
783                         /*
784                          * If PHYS_TO_VM_PAGE() returned NULL or the
785                          * vm_page was not initialized we'll use a
786                          * fake page.
787                          */
788                         if (fma == NULL) {
789                                 fma = malloc(sizeof(struct vm_page) * ma_cnt,
790                                     M_DEVBUF, M_ZERO | mflags);
791                                 if (fma == NULL) {
792                                         free(ma, M_DEVBUF);
793                                         return (ENOMEM);
794                                 }
795                         }
796                         vm_page_initfake(&fma[i], paddr, VM_MEMATTR_DEFAULT);
797                         ma[i] = &fma[i];
798                 }
799         }
800         error = iommu_bus_dmamap_load_something(tag, map, ma, offset, buflen,
801             flags, segs, segp);
802         free(ma, M_DEVBUF);
803         free(fma, M_DEVBUF);
804         return (error);
805 }
806
807 static void
808 iommu_bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map1,
809     struct memdesc *mem, bus_dmamap_callback_t *callback, void *callback_arg)
810 {
811         struct bus_dmamap_iommu *map;
812
813         if (map1 == NULL)
814                 return;
815         map = (struct bus_dmamap_iommu *)map1;
816         map->mem = *mem;
817         map->tag = (struct bus_dma_tag_iommu *)dmat;
818         map->callback = callback;
819         map->callback_arg = callback_arg;
820 }
821
822 static bus_dma_segment_t *
823 iommu_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map1,
824     bus_dma_segment_t *segs, int nsegs, int error)
825 {
826         struct bus_dma_tag_iommu *tag;
827         struct bus_dmamap_iommu *map;
828
829         tag = (struct bus_dma_tag_iommu *)dmat;
830         map = (struct bus_dmamap_iommu *)map1;
831
832         if (!map->locked) {
833                 KASSERT(map->cansleep,
834                     ("map not locked and not sleepable context %p", map));
835
836                 /*
837                  * We are called from the delayed context.  Relock the
838                  * driver.
839                  */
840                 (tag->common.lockfunc)(tag->common.lockfuncarg, BUS_DMA_LOCK);
841                 map->locked = true;
842         }
843
844         if (segs == NULL)
845                 segs = tag->segments;
846         return (segs);
847 }
848
849 /*
850  * The limitations of busdma KPI forces the iommu to perform the actual
851  * unload, consisting of the unmapping of the map entries page tables,
852  * from the delayed context on i386, since page table page mapping
853  * might require a sleep to be successfull.  The unfortunate
854  * consequence is that the DMA requests can be served some time after
855  * the bus_dmamap_unload() call returned.
856  *
857  * On amd64, we assume that sf allocation cannot fail.
858  */
859 static void
860 iommu_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map1)
861 {
862         struct bus_dma_tag_iommu *tag;
863         struct bus_dmamap_iommu *map;
864         struct iommu_ctx *ctx;
865         struct iommu_domain *domain;
866 #if defined(__amd64__)
867         struct iommu_map_entries_tailq entries;
868 #endif
869
870         tag = (struct bus_dma_tag_iommu *)dmat;
871         map = (struct bus_dmamap_iommu *)map1;
872         ctx = tag->ctx;
873         domain = ctx->domain;
874         atomic_add_long(&ctx->unloads, 1);
875
876 #if defined(__i386__)
877         IOMMU_DOMAIN_LOCK(domain);
878         TAILQ_CONCAT(&domain->unload_entries, &map->map_entries, dmamap_link);
879         IOMMU_DOMAIN_UNLOCK(domain);
880         taskqueue_enqueue(domain->iommu->delayed_taskqueue,
881             &domain->unload_task);
882 #else /* defined(__amd64__) */
883         TAILQ_INIT(&entries);
884         IOMMU_DOMAIN_LOCK(domain);
885         TAILQ_CONCAT(&entries, &map->map_entries, dmamap_link);
886         IOMMU_DOMAIN_UNLOCK(domain);
887         THREAD_NO_SLEEPING();
888         iommu_domain_unload(domain, &entries, false);
889         THREAD_SLEEPING_OK();
890         KASSERT(TAILQ_EMPTY(&entries), ("lazy iommu_ctx_unload %p", ctx));
891 #endif
892 }
893
894 static void
895 iommu_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map,
896     bus_dmasync_op_t op)
897 {
898 }
899
900 struct bus_dma_impl bus_dma_iommu_impl = {
901         .tag_create = iommu_bus_dma_tag_create,
902         .tag_destroy = iommu_bus_dma_tag_destroy,
903         .tag_set_domain = iommu_bus_dma_tag_set_domain,
904         .id_mapped = iommu_bus_dma_id_mapped,
905         .map_create = iommu_bus_dmamap_create,
906         .map_destroy = iommu_bus_dmamap_destroy,
907         .mem_alloc = iommu_bus_dmamem_alloc,
908         .mem_free = iommu_bus_dmamem_free,
909         .load_phys = iommu_bus_dmamap_load_phys,
910         .load_buffer = iommu_bus_dmamap_load_buffer,
911         .load_ma = iommu_bus_dmamap_load_ma,
912         .map_waitok = iommu_bus_dmamap_waitok,
913         .map_complete = iommu_bus_dmamap_complete,
914         .map_unload = iommu_bus_dmamap_unload,
915         .map_sync = iommu_bus_dmamap_sync,
916 };
917
918 static void
919 iommu_bus_task_dmamap(void *arg, int pending)
920 {
921         struct bus_dma_tag_iommu *tag;
922         struct bus_dmamap_iommu *map;
923         struct iommu_unit *unit;
924
925         unit = arg;
926         IOMMU_LOCK(unit);
927         while ((map = TAILQ_FIRST(&unit->delayed_maps)) != NULL) {
928                 TAILQ_REMOVE(&unit->delayed_maps, map, delay_link);
929                 IOMMU_UNLOCK(unit);
930                 tag = map->tag;
931                 map->cansleep = true;
932                 map->locked = false;
933                 bus_dmamap_load_mem((bus_dma_tag_t)tag, (bus_dmamap_t)map,
934                     &map->mem, map->callback, map->callback_arg,
935                     BUS_DMA_WAITOK);
936                 map->cansleep = false;
937                 if (map->locked) {
938                         (tag->common.lockfunc)(tag->common.lockfuncarg,
939                             BUS_DMA_UNLOCK);
940                 } else
941                         map->locked = true;
942                 map->cansleep = false;
943                 IOMMU_LOCK(unit);
944         }
945         IOMMU_UNLOCK(unit);
946 }
947
948 static void
949 iommu_bus_schedule_dmamap(struct iommu_unit *unit, struct bus_dmamap_iommu *map)
950 {
951
952         map->locked = false;
953         IOMMU_LOCK(unit);
954         TAILQ_INSERT_TAIL(&unit->delayed_maps, map, delay_link);
955         IOMMU_UNLOCK(unit);
956         taskqueue_enqueue(unit->delayed_taskqueue, &unit->dmamap_load_task);
957 }
958
959 int
960 iommu_init_busdma(struct iommu_unit *unit)
961 {
962         int error;
963
964         unit->dma_enabled = 1;
965         error = TUNABLE_INT_FETCH("hw.iommu.dma", &unit->dma_enabled);
966         if (error == 0) /* compatibility */
967                 TUNABLE_INT_FETCH("hw.dmar.dma", &unit->dma_enabled);
968         TAILQ_INIT(&unit->delayed_maps);
969         TASK_INIT(&unit->dmamap_load_task, 0, iommu_bus_task_dmamap, unit);
970         unit->delayed_taskqueue = taskqueue_create("iommu", M_WAITOK,
971             taskqueue_thread_enqueue, &unit->delayed_taskqueue);
972         taskqueue_start_threads(&unit->delayed_taskqueue, 1, PI_DISK,
973             "iommu%d busdma taskq", unit->unit);
974         return (0);
975 }
976
977 void
978 iommu_fini_busdma(struct iommu_unit *unit)
979 {
980
981         if (unit->delayed_taskqueue == NULL)
982                 return;
983
984         taskqueue_drain(unit->delayed_taskqueue, &unit->dmamap_load_task);
985         taskqueue_free(unit->delayed_taskqueue);
986         unit->delayed_taskqueue = NULL;
987 }
988
989 int
990 bus_dma_iommu_load_ident(bus_dma_tag_t dmat, bus_dmamap_t map1,
991     vm_paddr_t start, vm_size_t length, int flags)
992 {
993         struct bus_dma_tag_common *tc;
994         struct bus_dma_tag_iommu *tag;
995         struct bus_dmamap_iommu *map;
996         struct iommu_ctx *ctx;
997         struct iommu_domain *domain;
998         struct iommu_map_entry *entry;
999         vm_page_t *ma;
1000         vm_size_t i;
1001         int error;
1002         bool waitok;
1003
1004         MPASS((start & PAGE_MASK) == 0);
1005         MPASS((length & PAGE_MASK) == 0);
1006         MPASS(length > 0);
1007         MPASS(start + length >= start);
1008         MPASS((flags & ~(BUS_DMA_NOWAIT | BUS_DMA_NOWRITE)) == 0);
1009
1010         tc = (struct bus_dma_tag_common *)dmat;
1011         if (tc->impl != &bus_dma_iommu_impl)
1012                 return (0);
1013
1014         tag = (struct bus_dma_tag_iommu *)dmat;
1015         ctx = tag->ctx;
1016         domain = ctx->domain;
1017         map = (struct bus_dmamap_iommu *)map1;
1018         waitok = (flags & BUS_DMA_NOWAIT) != 0;
1019
1020         entry = iommu_map_alloc_entry(domain, waitok ? 0 : IOMMU_PGF_WAITOK);
1021         if (entry == NULL)
1022                 return (ENOMEM);
1023         entry->start = start;
1024         entry->end = start + length;
1025         ma = malloc(sizeof(vm_page_t) * atop(length), M_TEMP, waitok ?
1026             M_WAITOK : M_NOWAIT);
1027         if (ma == NULL) {
1028                 iommu_map_free_entry(domain, entry);
1029                 return (ENOMEM);
1030         }
1031         for (i = 0; i < atop(length); i++) {
1032                 ma[i] = vm_page_getfake(entry->start + PAGE_SIZE * i,
1033                     VM_MEMATTR_DEFAULT);
1034         }
1035         error = iommu_map_region(domain, entry, IOMMU_MAP_ENTRY_READ |
1036             ((flags & BUS_DMA_NOWRITE) ? 0 : IOMMU_MAP_ENTRY_WRITE),
1037             waitok ? IOMMU_MF_CANWAIT : 0, ma);
1038         if (error == 0) {
1039                 IOMMU_DOMAIN_LOCK(domain);
1040                 TAILQ_INSERT_TAIL(&map->map_entries, entry, dmamap_link);
1041                 entry->flags |= IOMMU_MAP_ENTRY_MAP;
1042                 IOMMU_DOMAIN_UNLOCK(domain);
1043         } else {
1044                 iommu_domain_unload_entry(entry, true);
1045         }
1046         for (i = 0; i < atop(length); i++)
1047                 vm_page_putfake(ma[i]);
1048         free(ma, M_TEMP);
1049         return (error);
1050 }