]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/iommu/busdma_dmar.c
MFH: r281668 through r281783
[FreeBSD/FreeBSD.git] / sys / x86 / iommu / busdma_dmar.c
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$");
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/bus.h>
37 #include <sys/conf.h>
38 #include <sys/interrupt.h>
39 #include <sys/kernel.h>
40 #include <sys/ktr.h>
41 #include <sys/lock.h>
42 #include <sys/proc.h>
43 #include <sys/memdesc.h>
44 #include <sys/mutex.h>
45 #include <sys/sysctl.h>
46 #include <sys/rman.h>
47 #include <sys/taskqueue.h>
48 #include <sys/tree.h>
49 #include <sys/uio.h>
50 #include <sys/vmem.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <vm/vm.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_kern.h>
56 #include <vm/vm_object.h>
57 #include <vm/vm_page.h>
58 #include <vm/vm_map.h>
59 #include <machine/atomic.h>
60 #include <machine/bus.h>
61 #include <machine/md_var.h>
62 #include <machine/specialreg.h>
63 #include <x86/include/busdma_impl.h>
64 #include <x86/iommu/intel_reg.h>
65 #include <x86/iommu/busdma_dmar.h>
66 #include <x86/iommu/intel_dmar.h>
67
68 /*
69  * busdma_dmar.c, the implementation of the busdma(9) interface using
70  * DMAR units from Intel VT-d.
71  */
72
73 static bool
74 dmar_bus_dma_is_dev_disabled(int domain, int bus, int slot, int func)
75 {
76         char str[128], *env;
77
78         snprintf(str, sizeof(str), "hw.busdma.pci%d.%d.%d.%d.bounce",
79             domain, bus, slot, func);
80         env = kern_getenv(str);
81         if (env == NULL)
82                 return (false);
83         freeenv(env);
84         return (true);
85 }
86
87 /*
88  * Given original device, find the requester ID that will be seen by
89  * the DMAR unit and used for page table lookup.  PCI bridges may take
90  * ownership of transactions from downstream devices, so it may not be
91  * the same as the BSF of the target device.  In those cases, all
92  * devices downstream of the bridge must share a single mapping
93  * domain, and must collectively be assigned to use either DMAR or
94  * bounce mapping.
95  */
96 device_t
97 dmar_get_requester(device_t dev, uint16_t *rid)
98 {
99         devclass_t pci_class;
100         device_t l, pci, pcib, pcip, pcibp, requester;
101         int cap_offset;
102         uint16_t pcie_flags;
103         bool bridge_is_pcie;
104
105         pci_class = devclass_find("pci");
106         l = requester = dev;
107
108         *rid = pci_get_rid(dev);
109
110         /*
111          * Walk the bridge hierarchy from the target device to the
112          * host port to find the translating bridge nearest the DMAR
113          * unit.
114          */
115         for (;;) {
116                 pci = device_get_parent(l);
117                 KASSERT(pci != NULL, ("dmar_get_requester(%s): NULL parent "
118                     "for %s", device_get_name(dev), device_get_name(l)));
119                 KASSERT(device_get_devclass(pci) == pci_class,
120                     ("dmar_get_requester(%s): non-pci parent %s for %s",
121                     device_get_name(dev), device_get_name(pci),
122                     device_get_name(l)));
123
124                 pcib = device_get_parent(pci);
125                 KASSERT(pcib != NULL, ("dmar_get_requester(%s): NULL bridge "
126                     "for %s", device_get_name(dev), device_get_name(pci)));
127
128                 /*
129                  * The parent of our "bridge" isn't another PCI bus,
130                  * so pcib isn't a PCI->PCI bridge but rather a host
131                  * port, and the requester ID won't be translated
132                  * further.
133                  */
134                 pcip = device_get_parent(pcib);
135                 if (device_get_devclass(pcip) != pci_class)
136                         break;
137                 pcibp = device_get_parent(pcip);
138
139                 if (pci_find_cap(l, PCIY_EXPRESS, &cap_offset) == 0) {
140                         /*
141                          * Do not stop the loop even if the target
142                          * device is PCIe, because it is possible (but
143                          * unlikely) to have a PCI->PCIe bridge
144                          * somewhere in the hierarchy.
145                          */
146                         l = pcib;
147                 } else {
148                         /*
149                          * Device is not PCIe, it cannot be seen as a
150                          * requester by DMAR unit.  Check whether the
151                          * bridge is PCIe.
152                          */
153                         bridge_is_pcie = pci_find_cap(pcib, PCIY_EXPRESS,
154                             &cap_offset) == 0;
155                         requester = pcib;
156
157                         /*
158                          * Check for a buggy PCIe/PCI bridge that
159                          * doesn't report the express capability.  If
160                          * the bridge above it is express but isn't a
161                          * PCI bridge, then we know pcib is actually a
162                          * PCIe/PCI bridge.
163                          */
164                         if (!bridge_is_pcie && pci_find_cap(pcibp,
165                             PCIY_EXPRESS, &cap_offset) == 0) {
166                                 pcie_flags = pci_read_config(pcibp,
167                                     cap_offset + PCIER_FLAGS, 2);
168                                 if ((pcie_flags & PCIEM_FLAGS_TYPE) !=
169                                     PCIEM_TYPE_PCI_BRIDGE)
170                                         bridge_is_pcie = true;
171                         }
172
173                         if (bridge_is_pcie) {
174                                 /*
175                                  * The current device is not PCIe, but
176                                  * the bridge above it is.  This is a
177                                  * PCIe->PCI bridge.  Assume that the
178                                  * requester ID will be the secondary
179                                  * bus number with slot and function
180                                  * set to zero.
181                                  *
182                                  * XXX: Doesn't handle the case where
183                                  * the bridge is PCIe->PCI-X, and the
184                                  * bridge will only take ownership of
185                                  * requests in some cases.  We should
186                                  * provide context entries with the
187                                  * same page tables for taken and
188                                  * non-taken transactions.
189                                  */
190                                 *rid = PCI_RID(pci_get_bus(l), 0, 0);
191                                 l = pcibp;
192                         } else {
193                                 /*
194                                  * Neither the device nor the bridge
195                                  * above it are PCIe.  This is a
196                                  * conventional PCI->PCI bridge, which
197                                  * will use the bridge's BSF as the
198                                  * requester ID.
199                                  */
200                                 *rid = pci_get_rid(pcib);
201                                 l = pcib;
202                         }
203                 }
204         }
205         return (requester);
206 }
207
208 struct dmar_ctx *
209 dmar_instantiate_ctx(struct dmar_unit *dmar, device_t dev, bool rmrr)
210 {
211         device_t requester;
212         struct dmar_ctx *ctx;
213         bool disabled;
214         uint16_t rid;
215
216         requester = dmar_get_requester(dev, &rid);
217
218         /*
219          * If the user requested the IOMMU disabled for the device, we
220          * cannot disable the DMAR, due to possibility of other
221          * devices on the same DMAR still requiring translation.
222          * Instead provide the identity mapping for the device
223          * context.
224          */
225         disabled = dmar_bus_dma_is_dev_disabled(pci_get_domain(requester), 
226             pci_get_bus(requester), pci_get_slot(requester), 
227             pci_get_function(requester));
228         ctx = dmar_get_ctx(dmar, requester, rid, disabled, rmrr);
229         if (ctx == NULL)
230                 return (NULL);
231         if (disabled) {
232                 /*
233                  * Keep the first reference on context, release the
234                  * later refs.
235                  */
236                 DMAR_LOCK(dmar);
237                 if ((ctx->flags & DMAR_CTX_DISABLED) == 0) {
238                         ctx->flags |= DMAR_CTX_DISABLED;
239                         DMAR_UNLOCK(dmar);
240                 } else {
241                         dmar_free_ctx_locked(dmar, ctx);
242                 }
243                 ctx = NULL;
244         }
245         return (ctx);
246 }
247
248 bus_dma_tag_t
249 dmar_get_dma_tag(device_t dev, device_t child)
250 {
251         struct dmar_unit *dmar;
252         struct dmar_ctx *ctx;
253         bus_dma_tag_t res;
254
255         dmar = dmar_find(child);
256         /* Not in scope of any DMAR ? */
257         if (dmar == NULL)
258                 return (NULL);
259         if (!dmar->dma_enabled)
260                 return (NULL);
261         dmar_quirks_pre_use(dmar);
262         dmar_instantiate_rmrr_ctxs(dmar);
263
264         ctx = dmar_instantiate_ctx(dmar, child, false);
265         res = ctx == NULL ? NULL : (bus_dma_tag_t)&ctx->ctx_tag;
266         return (res);
267 }
268
269 static MALLOC_DEFINE(M_DMAR_DMAMAP, "dmar_dmamap", "Intel DMAR DMA Map");
270
271 static void dmar_bus_schedule_dmamap(struct dmar_unit *unit,
272     struct bus_dmamap_dmar *map);
273
274 static int
275 dmar_bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
276     bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
277     bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
278     int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
279     void *lockfuncarg, bus_dma_tag_t *dmat)
280 {
281         struct bus_dma_tag_dmar *newtag, *oldtag;
282         int error;
283
284         *dmat = NULL;
285         error = common_bus_dma_tag_create(parent != NULL ?
286             &((struct bus_dma_tag_dmar *)parent)->common : NULL, alignment,
287             boundary, lowaddr, highaddr, filter, filterarg, maxsize,
288             nsegments, maxsegsz, flags, lockfunc, lockfuncarg,
289             sizeof(struct bus_dma_tag_dmar), (void **)&newtag);
290         if (error != 0)
291                 goto out;
292
293         oldtag = (struct bus_dma_tag_dmar *)parent;
294         newtag->common.impl = &bus_dma_dmar_impl;
295         newtag->ctx = oldtag->ctx;
296         newtag->owner = oldtag->owner;
297
298         *dmat = (bus_dma_tag_t)newtag;
299 out:
300         CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
301             __func__, newtag, (newtag != NULL ? newtag->common.flags : 0),
302             error);
303         return (error);
304 }
305
306 static int
307 dmar_bus_dma_tag_destroy(bus_dma_tag_t dmat1)
308 {
309         struct bus_dma_tag_dmar *dmat, *dmat_copy, *parent;
310         int error;
311
312         error = 0;
313         dmat_copy = dmat = (struct bus_dma_tag_dmar *)dmat1;
314
315         if (dmat != NULL) {
316                 if (dmat->map_count != 0) {
317                         error = EBUSY;
318                         goto out;
319                 }
320                 while (dmat != NULL) {
321                         parent = (struct bus_dma_tag_dmar *)dmat->common.parent;
322                         if (atomic_fetchadd_int(&dmat->common.ref_count, -1) ==
323                             1) {
324                                 if (dmat == &dmat->ctx->ctx_tag)
325                                         dmar_free_ctx(dmat->ctx);
326                                 free(dmat->segments, M_DMAR_DMAMAP);
327                                 free(dmat, M_DEVBUF);
328                                 dmat = parent;
329                         } else
330                                 dmat = NULL;
331                 }
332         }
333 out:
334         CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
335         return (error);
336 }
337
338 static int
339 dmar_bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
340 {
341         struct bus_dma_tag_dmar *tag;
342         struct bus_dmamap_dmar *map;
343
344         tag = (struct bus_dma_tag_dmar *)dmat;
345         map = malloc(sizeof(*map), M_DMAR_DMAMAP, M_NOWAIT | M_ZERO);
346         if (map == NULL) {
347                 *mapp = NULL;
348                 return (ENOMEM);
349         }
350         if (tag->segments == NULL) {
351                 tag->segments = malloc(sizeof(bus_dma_segment_t) *
352                     tag->common.nsegments, M_DMAR_DMAMAP, M_NOWAIT);
353                 if (tag->segments == NULL) {
354                         free(map, M_DMAR_DMAMAP);
355                         *mapp = NULL;
356                         return (ENOMEM);
357                 }
358         }
359         TAILQ_INIT(&map->map_entries);
360         map->tag = tag;
361         map->locked = true;
362         map->cansleep = false;
363         tag->map_count++;
364         *mapp = (bus_dmamap_t)map;
365
366         return (0);
367 }
368
369 static int
370 dmar_bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map1)
371 {
372         struct bus_dma_tag_dmar *tag;
373         struct bus_dmamap_dmar *map;
374
375         tag = (struct bus_dma_tag_dmar *)dmat;
376         map = (struct bus_dmamap_dmar *)map1;
377         if (map != NULL) {
378                 DMAR_CTX_LOCK(tag->ctx);
379                 if (!TAILQ_EMPTY(&map->map_entries)) {
380                         DMAR_CTX_UNLOCK(tag->ctx);
381                         return (EBUSY);
382                 }
383                 DMAR_CTX_UNLOCK(tag->ctx);
384                 free(map, M_DMAR_DMAMAP);
385         }
386         tag->map_count--;
387         return (0);
388 }
389
390
391 static int
392 dmar_bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
393     bus_dmamap_t *mapp)
394 {
395         struct bus_dma_tag_dmar *tag;
396         struct bus_dmamap_dmar *map;
397         int error, mflags;
398         vm_memattr_t attr;
399
400         error = dmar_bus_dmamap_create(dmat, flags, mapp);
401         if (error != 0)
402                 return (error);
403
404         mflags = (flags & BUS_DMA_NOWAIT) != 0 ? M_NOWAIT : M_WAITOK;
405         mflags |= (flags & BUS_DMA_ZERO) != 0 ? M_ZERO : 0;
406         attr = (flags & BUS_DMA_NOCACHE) != 0 ? VM_MEMATTR_UNCACHEABLE :
407             VM_MEMATTR_DEFAULT;
408
409         tag = (struct bus_dma_tag_dmar *)dmat;
410         map = (struct bus_dmamap_dmar *)*mapp;
411
412         if (tag->common.maxsize < PAGE_SIZE &&
413             tag->common.alignment <= tag->common.maxsize &&
414             attr == VM_MEMATTR_DEFAULT) {
415                 *vaddr = malloc(tag->common.maxsize, M_DEVBUF, mflags);
416                 map->flags |= BUS_DMAMAP_DMAR_MALLOC;
417         } else {
418                 *vaddr = (void *)kmem_alloc_attr(kernel_arena,
419                     tag->common.maxsize, mflags, 0ul, BUS_SPACE_MAXADDR,
420                     attr);
421                 map->flags |= BUS_DMAMAP_DMAR_KMEM_ALLOC;
422         }
423         if (*vaddr == NULL) {
424                 dmar_bus_dmamap_destroy(dmat, *mapp);
425                 *mapp = NULL;
426                 return (ENOMEM);
427         }
428         return (0);
429 }
430
431 static void
432 dmar_bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map1)
433 {
434         struct bus_dma_tag_dmar *tag;
435         struct bus_dmamap_dmar *map;
436
437         tag = (struct bus_dma_tag_dmar *)dmat;
438         map = (struct bus_dmamap_dmar *)map1;
439
440         if ((map->flags & BUS_DMAMAP_DMAR_MALLOC) != 0) {
441                 free(vaddr, M_DEVBUF);
442                 map->flags &= ~BUS_DMAMAP_DMAR_MALLOC;
443         } else {
444                 KASSERT((map->flags & BUS_DMAMAP_DMAR_KMEM_ALLOC) != 0,
445                     ("dmar_bus_dmamem_free for non alloced map %p", map));
446                 kmem_free(kernel_arena, (vm_offset_t)vaddr, tag->common.maxsize);
447                 map->flags &= ~BUS_DMAMAP_DMAR_KMEM_ALLOC;
448         }
449
450         dmar_bus_dmamap_destroy(dmat, map1);
451 }
452
453 static int
454 dmar_bus_dmamap_load_something1(struct bus_dma_tag_dmar *tag,
455     struct bus_dmamap_dmar *map, vm_page_t *ma, int offset, bus_size_t buflen,
456     int flags, bus_dma_segment_t *segs, int *segp,
457     struct dmar_map_entries_tailq *unroll_list)
458 {
459         struct dmar_ctx *ctx;
460         struct dmar_map_entry *entry;
461         dmar_gaddr_t size;
462         bus_size_t buflen1;
463         int error, idx, gas_flags, seg;
464
465         KASSERT(offset < DMAR_PAGE_SIZE, ("offset %d", offset));
466         if (segs == NULL)
467                 segs = tag->segments;
468         ctx = tag->ctx;
469         seg = *segp;
470         error = 0;
471         idx = 0;
472         while (buflen > 0) {
473                 seg++;
474                 if (seg >= tag->common.nsegments) {
475                         error = EFBIG;
476                         break;
477                 }
478                 buflen1 = buflen > tag->common.maxsegsz ?
479                     tag->common.maxsegsz : buflen;
480                 size = round_page(offset + buflen1);
481
482                 /*
483                  * (Too) optimistically allow split if there are more
484                  * then one segments left.
485                  */
486                 gas_flags = map->cansleep ? DMAR_GM_CANWAIT : 0;
487                 if (seg + 1 < tag->common.nsegments)
488                         gas_flags |= DMAR_GM_CANSPLIT;
489
490                 error = dmar_gas_map(ctx, &tag->common, size, offset,
491                     DMAR_MAP_ENTRY_READ | DMAR_MAP_ENTRY_WRITE,
492                     gas_flags, ma + idx, &entry);
493                 if (error != 0)
494                         break;
495                 if ((gas_flags & DMAR_GM_CANSPLIT) != 0) {
496                         KASSERT(size >= entry->end - entry->start,
497                             ("split increased entry size %jx %jx %jx",
498                             (uintmax_t)size, (uintmax_t)entry->start,
499                             (uintmax_t)entry->end));
500                         size = entry->end - entry->start;
501                         if (buflen1 > size)
502                                 buflen1 = size;
503                 } else {
504                         KASSERT(entry->end - entry->start == size,
505                             ("no split allowed %jx %jx %jx",
506                             (uintmax_t)size, (uintmax_t)entry->start,
507                             (uintmax_t)entry->end));
508                 }
509                 if (offset + buflen1 > size)
510                         buflen1 = size - offset;
511                 if (buflen1 > tag->common.maxsegsz)
512                         buflen1 = tag->common.maxsegsz;
513
514                 KASSERT(((entry->start + offset) & (tag->common.alignment - 1))
515                     == 0,
516                     ("alignment failed: ctx %p start 0x%jx offset %x "
517                     "align 0x%jx", ctx, (uintmax_t)entry->start, offset,
518                     (uintmax_t)tag->common.alignment));
519                 KASSERT(entry->end <= tag->common.lowaddr ||
520                     entry->start >= tag->common.highaddr,
521                     ("entry placement failed: ctx %p start 0x%jx end 0x%jx "
522                     "lowaddr 0x%jx highaddr 0x%jx", ctx,
523                     (uintmax_t)entry->start, (uintmax_t)entry->end,
524                     (uintmax_t)tag->common.lowaddr,
525                     (uintmax_t)tag->common.highaddr));
526                 KASSERT(dmar_test_boundary(entry->start + offset, buflen1,
527                     tag->common.boundary),
528                     ("boundary failed: ctx %p start 0x%jx end 0x%jx "
529                     "boundary 0x%jx", ctx, (uintmax_t)entry->start,
530                     (uintmax_t)entry->end, (uintmax_t)tag->common.boundary));
531                 KASSERT(buflen1 <= tag->common.maxsegsz,
532                     ("segment too large: ctx %p start 0x%jx end 0x%jx "
533                     "buflen1 0x%jx maxsegsz 0x%jx", ctx,
534                     (uintmax_t)entry->start, (uintmax_t)entry->end,
535                     (uintmax_t)buflen1, (uintmax_t)tag->common.maxsegsz));
536
537                 DMAR_CTX_LOCK(ctx);
538                 TAILQ_INSERT_TAIL(&map->map_entries, entry, dmamap_link);
539                 entry->flags |= DMAR_MAP_ENTRY_MAP;
540                 DMAR_CTX_UNLOCK(ctx);
541                 TAILQ_INSERT_TAIL(unroll_list, entry, unroll_link);
542
543                 segs[seg].ds_addr = entry->start + offset;
544                 segs[seg].ds_len = buflen1;
545
546                 idx += OFF_TO_IDX(trunc_page(offset + buflen1));
547                 offset += buflen1;
548                 offset &= DMAR_PAGE_MASK;
549                 buflen -= buflen1;
550         }
551         if (error == 0)
552                 *segp = seg;
553         return (error);
554 }
555
556 static int
557 dmar_bus_dmamap_load_something(struct bus_dma_tag_dmar *tag,
558     struct bus_dmamap_dmar *map, vm_page_t *ma, int offset, bus_size_t buflen,
559     int flags, bus_dma_segment_t *segs, int *segp)
560 {
561         struct dmar_ctx *ctx;
562         struct dmar_map_entry *entry, *entry1;
563         struct dmar_map_entries_tailq unroll_list;
564         int error;
565
566         ctx = tag->ctx;
567         atomic_add_long(&ctx->loads, 1);
568
569         TAILQ_INIT(&unroll_list);
570         error = dmar_bus_dmamap_load_something1(tag, map, ma, offset,
571             buflen, flags, segs, segp, &unroll_list);
572         if (error != 0) {
573                 /*
574                  * The busdma interface does not allow us to report
575                  * partial buffer load, so unfortunately we have to
576                  * revert all work done.
577                  */
578                 DMAR_CTX_LOCK(ctx);
579                 TAILQ_FOREACH_SAFE(entry, &unroll_list, unroll_link,
580                     entry1) {
581                         /*
582                          * No entries other than what we have created
583                          * during the failed run might have been
584                          * inserted there in between, since we own ctx
585                          * pglock.
586                          */
587                         TAILQ_REMOVE(&map->map_entries, entry, dmamap_link);
588                         TAILQ_REMOVE(&unroll_list, entry, unroll_link);
589                         TAILQ_INSERT_TAIL(&ctx->unload_entries, entry,
590                             dmamap_link);
591                 }
592                 DMAR_CTX_UNLOCK(ctx);
593                 taskqueue_enqueue(ctx->dmar->delayed_taskqueue,
594                     &ctx->unload_task);
595         }
596
597         if (error == ENOMEM && (flags & BUS_DMA_NOWAIT) == 0 &&
598             !map->cansleep)
599                 error = EINPROGRESS;
600         if (error == EINPROGRESS)
601                 dmar_bus_schedule_dmamap(ctx->dmar, map);
602         return (error);
603 }
604
605 static int
606 dmar_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map1,
607     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
608     bus_dma_segment_t *segs, int *segp)
609 {
610         struct bus_dma_tag_dmar *tag;
611         struct bus_dmamap_dmar *map;
612
613         tag = (struct bus_dma_tag_dmar *)dmat;
614         map = (struct bus_dmamap_dmar *)map1;
615         return (dmar_bus_dmamap_load_something(tag, map, ma, ma_offs, tlen,
616             flags, segs, segp));
617 }
618
619 static int
620 dmar_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map1,
621     vm_paddr_t buf, bus_size_t buflen, int flags, bus_dma_segment_t *segs,
622     int *segp)
623 {
624         struct bus_dma_tag_dmar *tag;
625         struct bus_dmamap_dmar *map;
626         vm_page_t *ma;
627         vm_paddr_t pstart, pend;
628         int error, i, ma_cnt, offset;
629
630         tag = (struct bus_dma_tag_dmar *)dmat;
631         map = (struct bus_dmamap_dmar *)map1;
632         pstart = trunc_page(buf);
633         pend = round_page(buf + buflen);
634         offset = buf & PAGE_MASK;
635         ma_cnt = OFF_TO_IDX(pend - pstart);
636         ma = malloc(sizeof(vm_page_t) * ma_cnt, M_DEVBUF, map->cansleep ?
637             M_WAITOK : M_NOWAIT);
638         if (ma == NULL)
639                 return (ENOMEM);
640         for (i = 0; i < ma_cnt; i++)
641                 ma[i] = PHYS_TO_VM_PAGE(pstart + i * PAGE_SIZE);
642         error = dmar_bus_dmamap_load_something(tag, map, ma, offset, buflen,
643             flags, segs, segp);
644         free(ma, M_DEVBUF);
645         return (error);
646 }
647
648 static int
649 dmar_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map1, void *buf,
650     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
651     int *segp)
652 {
653         struct bus_dma_tag_dmar *tag;
654         struct bus_dmamap_dmar *map;
655         vm_page_t *ma, fma;
656         vm_paddr_t pstart, pend, paddr;
657         int error, i, ma_cnt, offset;
658
659         tag = (struct bus_dma_tag_dmar *)dmat;
660         map = (struct bus_dmamap_dmar *)map1;
661         pstart = trunc_page((vm_offset_t)buf);
662         pend = round_page((vm_offset_t)buf + buflen);
663         offset = (vm_offset_t)buf & PAGE_MASK;
664         ma_cnt = OFF_TO_IDX(pend - pstart);
665         ma = malloc(sizeof(vm_page_t) * ma_cnt, M_DEVBUF, map->cansleep ?
666             M_WAITOK : M_NOWAIT);
667         if (ma == NULL)
668                 return (ENOMEM);
669         if (dumping) {
670                 /*
671                  * If dumping, do not attempt to call
672                  * PHYS_TO_VM_PAGE() at all.  It may return non-NULL
673                  * but the vm_page returned might be not initialized,
674                  * e.g. for the kernel itself.
675                  */
676                 KASSERT(pmap == kernel_pmap, ("non-kernel address write"));
677                 fma = malloc(sizeof(struct vm_page) * ma_cnt, M_DEVBUF,
678                     M_ZERO | (map->cansleep ? M_WAITOK : M_NOWAIT));
679                 if (fma == NULL) {
680                         free(ma, M_DEVBUF);
681                         return (ENOMEM);
682                 }
683                 for (i = 0; i < ma_cnt; i++, pstart += PAGE_SIZE) {
684                         paddr = pmap_kextract(pstart);
685                         vm_page_initfake(&fma[i], paddr, VM_MEMATTR_DEFAULT);
686                         ma[i] = &fma[i];
687                 }
688         } else {
689                 fma = NULL;
690                 for (i = 0; i < ma_cnt; i++, pstart += PAGE_SIZE) {
691                         if (pmap == kernel_pmap)
692                                 paddr = pmap_kextract(pstart);
693                         else
694                                 paddr = pmap_extract(pmap, pstart);
695                         ma[i] = PHYS_TO_VM_PAGE(paddr);
696                         KASSERT(VM_PAGE_TO_PHYS(ma[i]) == paddr,
697                             ("PHYS_TO_VM_PAGE failed %jx %jx m %p",
698                             (uintmax_t)paddr, (uintmax_t)VM_PAGE_TO_PHYS(ma[i]),
699                             ma[i]));
700                 }
701         }
702         error = dmar_bus_dmamap_load_something(tag, map, ma, offset, buflen,
703             flags, segs, segp);
704         free(ma, M_DEVBUF);
705         free(fma, M_DEVBUF);
706         return (error);
707 }
708
709 static void
710 dmar_bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map1,
711     struct memdesc *mem, bus_dmamap_callback_t *callback, void *callback_arg)
712 {
713         struct bus_dmamap_dmar *map;
714
715         if (map1 == NULL)
716                 return;
717         map = (struct bus_dmamap_dmar *)map1;
718         map->mem = *mem;
719         map->tag = (struct bus_dma_tag_dmar *)dmat;
720         map->callback = callback;
721         map->callback_arg = callback_arg;
722 }
723
724 static bus_dma_segment_t *
725 dmar_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map1,
726     bus_dma_segment_t *segs, int nsegs, int error)
727 {
728         struct bus_dma_tag_dmar *tag;
729         struct bus_dmamap_dmar *map;
730
731         tag = (struct bus_dma_tag_dmar *)dmat;
732         map = (struct bus_dmamap_dmar *)map1;
733
734         if (!map->locked) {
735                 KASSERT(map->cansleep,
736                     ("map not locked and not sleepable context %p", map));
737
738                 /*
739                  * We are called from the delayed context.  Relock the
740                  * driver.
741                  */
742                 (tag->common.lockfunc)(tag->common.lockfuncarg, BUS_DMA_LOCK);
743                 map->locked = true;
744         }
745
746         if (segs == NULL)
747                 segs = tag->segments;
748         return (segs);
749 }
750
751 /*
752  * The limitations of busdma KPI forces the dmar to perform the actual
753  * unload, consisting of the unmapping of the map entries page tables,
754  * from the delayed context on i386, since page table page mapping
755  * might require a sleep to be successfull.  The unfortunate
756  * consequence is that the DMA requests can be served some time after
757  * the bus_dmamap_unload() call returned.
758  *
759  * On amd64, we assume that sf allocation cannot fail.
760  */
761 static void
762 dmar_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map1)
763 {
764         struct bus_dma_tag_dmar *tag;
765         struct bus_dmamap_dmar *map;
766         struct dmar_ctx *ctx;
767 #if defined(__amd64__)
768         struct dmar_map_entries_tailq entries;
769 #endif
770
771         tag = (struct bus_dma_tag_dmar *)dmat;
772         map = (struct bus_dmamap_dmar *)map1;
773         ctx = tag->ctx;
774         atomic_add_long(&ctx->unloads, 1);
775
776 #if defined(__i386__)
777         DMAR_CTX_LOCK(ctx);
778         TAILQ_CONCAT(&ctx->unload_entries, &map->map_entries, dmamap_link);
779         DMAR_CTX_UNLOCK(ctx);
780         taskqueue_enqueue(ctx->dmar->delayed_taskqueue, &ctx->unload_task);
781 #else /* defined(__amd64__) */
782         TAILQ_INIT(&entries);
783         DMAR_CTX_LOCK(ctx);
784         TAILQ_CONCAT(&entries, &map->map_entries, dmamap_link);
785         DMAR_CTX_UNLOCK(ctx);
786         THREAD_NO_SLEEPING();
787         dmar_ctx_unload(ctx, &entries, false);
788         THREAD_SLEEPING_OK();
789         KASSERT(TAILQ_EMPTY(&entries), ("lazy dmar_ctx_unload %p", ctx));
790 #endif
791 }
792
793 static void
794 dmar_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map,
795     bus_dmasync_op_t op)
796 {
797 }
798
799 struct bus_dma_impl bus_dma_dmar_impl = {
800         .tag_create = dmar_bus_dma_tag_create,
801         .tag_destroy = dmar_bus_dma_tag_destroy,
802         .map_create = dmar_bus_dmamap_create,
803         .map_destroy = dmar_bus_dmamap_destroy,
804         .mem_alloc = dmar_bus_dmamem_alloc,
805         .mem_free = dmar_bus_dmamem_free,
806         .load_phys = dmar_bus_dmamap_load_phys,
807         .load_buffer = dmar_bus_dmamap_load_buffer,
808         .load_ma = dmar_bus_dmamap_load_ma,
809         .map_waitok = dmar_bus_dmamap_waitok,
810         .map_complete = dmar_bus_dmamap_complete,
811         .map_unload = dmar_bus_dmamap_unload,
812         .map_sync = dmar_bus_dmamap_sync
813 };
814
815 static void
816 dmar_bus_task_dmamap(void *arg, int pending)
817 {
818         struct bus_dma_tag_dmar *tag;
819         struct bus_dmamap_dmar *map;
820         struct dmar_unit *unit;
821         struct dmar_ctx *ctx;
822
823         unit = arg;
824         DMAR_LOCK(unit);
825         while ((map = TAILQ_FIRST(&unit->delayed_maps)) != NULL) {
826                 TAILQ_REMOVE(&unit->delayed_maps, map, delay_link);
827                 DMAR_UNLOCK(unit);
828                 tag = map->tag;
829                 ctx = map->tag->ctx;
830                 map->cansleep = true;
831                 map->locked = false;
832                 bus_dmamap_load_mem((bus_dma_tag_t)tag, (bus_dmamap_t)map,
833                     &map->mem, map->callback, map->callback_arg,
834                     BUS_DMA_WAITOK);
835                 map->cansleep = false;
836                 if (map->locked) {
837                         (tag->common.lockfunc)(tag->common.lockfuncarg,
838                             BUS_DMA_UNLOCK);
839                 } else
840                         map->locked = true;
841                 map->cansleep = false;
842                 DMAR_LOCK(unit);
843         }
844         DMAR_UNLOCK(unit);
845 }
846
847 static void
848 dmar_bus_schedule_dmamap(struct dmar_unit *unit, struct bus_dmamap_dmar *map)
849 {
850         struct dmar_ctx *ctx;
851
852         ctx = map->tag->ctx;
853         map->locked = false;
854         DMAR_LOCK(unit);
855         TAILQ_INSERT_TAIL(&unit->delayed_maps, map, delay_link);
856         DMAR_UNLOCK(unit);
857         taskqueue_enqueue(unit->delayed_taskqueue, &unit->dmamap_load_task);
858 }
859
860 int
861 dmar_init_busdma(struct dmar_unit *unit)
862 {
863
864         unit->dma_enabled = 1;
865         TUNABLE_INT_FETCH("hw.dmar.dma", &unit->dma_enabled);
866         TAILQ_INIT(&unit->delayed_maps);
867         TASK_INIT(&unit->dmamap_load_task, 0, dmar_bus_task_dmamap, unit);
868         unit->delayed_taskqueue = taskqueue_create("dmar", M_WAITOK,
869             taskqueue_thread_enqueue, &unit->delayed_taskqueue);
870         taskqueue_start_threads(&unit->delayed_taskqueue, 1, PI_DISK,
871             "dmar%d busdma taskq", unit->unit);
872         return (0);
873 }
874
875 void
876 dmar_fini_busdma(struct dmar_unit *unit)
877 {
878
879         if (unit->delayed_taskqueue == NULL)
880                 return;
881
882         taskqueue_drain(unit->delayed_taskqueue, &unit->dmamap_load_task);
883         taskqueue_free(unit->delayed_taskqueue);
884         unit->delayed_taskqueue = NULL;
885 }