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