]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/busdma_machdep.c
Merge ^/head r357389 through r357407.
[FreeBSD/FreeBSD.git] / sys / arm / arm / busdma_machdep.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012-2015 Ian Lepore
5  * Copyright (c) 2010 Mark Tinguely
6  * Copyright (c) 2004 Olivier Houchard
7  * Copyright (c) 2002 Peter Grehan
8  * Copyright (c) 1997, 1998 Justin T. Gibbs.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions, and the following disclaimer,
16  *    without modification, immediately at the beginning of the file.
17  * 2. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
24  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *  From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/bus.h>
42 #include <sys/busdma_bufalloc.h>
43 #include <sys/counter.h>
44 #include <sys/interrupt.h>
45 #include <sys/kernel.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/memdesc.h>
49 #include <sys/proc.h>
50 #include <sys/mutex.h>
51 #include <sys/sysctl.h>
52 #include <sys/uio.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_param.h>
56 #include <vm/vm_page.h>
57 #include <vm/vm_phys.h>
58 #include <vm/vm_map.h>
59 #include <vm/vm_extern.h>
60 #include <vm/vm_kern.h>
61
62 #include <machine/atomic.h>
63 #include <machine/bus.h>
64 #include <machine/cpu.h>
65 #include <machine/md_var.h>
66
67 #define BUSDMA_DCACHE_ALIGN     cpuinfo.dcache_line_size
68 #define BUSDMA_DCACHE_MASK      cpuinfo.dcache_line_mask
69
70 #define MAX_BPAGES              64
71 #define MAX_DMA_SEGMENTS        4096
72 #define BUS_DMA_EXCL_BOUNCE     BUS_DMA_BUS2
73 #define BUS_DMA_ALIGN_BOUNCE    BUS_DMA_BUS3
74 #define BUS_DMA_COULD_BOUNCE    (BUS_DMA_EXCL_BOUNCE | BUS_DMA_ALIGN_BOUNCE)
75 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
76
77 struct bounce_zone;
78
79 struct bus_dma_tag {
80         bus_dma_tag_t           parent;
81         bus_size_t              alignment;
82         bus_addr_t              boundary;
83         bus_addr_t              lowaddr;
84         bus_addr_t              highaddr;
85         bus_dma_filter_t        *filter;
86         void                    *filterarg;
87         bus_size_t              maxsize;
88         u_int                   nsegments;
89         bus_size_t              maxsegsz;
90         int                     flags;
91         int                     ref_count;
92         int                     map_count;
93         bus_dma_lock_t          *lockfunc;
94         void                    *lockfuncarg;
95         struct bounce_zone      *bounce_zone;
96 };
97
98 struct bounce_page {
99         vm_offset_t     vaddr;          /* kva of bounce buffer */
100         bus_addr_t      busaddr;        /* Physical address */
101         vm_offset_t     datavaddr;      /* kva of client data */
102         vm_page_t       datapage;       /* physical page of client data */
103         vm_offset_t     dataoffs;       /* page offset of client data */
104         bus_size_t      datacount;      /* client data count */
105         STAILQ_ENTRY(bounce_page) links;
106 };
107
108 struct sync_list {
109         vm_offset_t     vaddr;          /* kva of client data */
110         bus_addr_t      paddr;          /* physical address */
111         vm_page_t       pages;          /* starting page of client data */
112         bus_size_t      datacount;      /* client data count */
113 };
114
115 int busdma_swi_pending;
116
117 struct bounce_zone {
118         STAILQ_ENTRY(bounce_zone) links;
119         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
120         int             total_bpages;
121         int             free_bpages;
122         int             reserved_bpages;
123         int             active_bpages;
124         int             total_bounced;
125         int             total_deferred;
126         int             map_count;
127         bus_size_t      alignment;
128         bus_addr_t      lowaddr;
129         char            zoneid[8];
130         char            lowaddrid[20];
131         struct sysctl_ctx_list sysctl_tree;
132         struct sysctl_oid *sysctl_tree_top;
133 };
134
135 static struct mtx bounce_lock;
136 static int total_bpages;
137 static int busdma_zonecount;
138 static uint32_t tags_total;
139 static uint32_t maps_total;
140 static uint32_t maps_dmamem;
141 static uint32_t maps_coherent;
142 static counter_u64_t maploads_total;
143 static counter_u64_t maploads_bounced;
144 static counter_u64_t maploads_coherent;
145 static counter_u64_t maploads_dmamem;
146 static counter_u64_t maploads_mbuf;
147 static counter_u64_t maploads_physmem;
148
149 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
150
151 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
152 SYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
153    "Number of active tags");
154 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
155    "Number of active maps");
156 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
157    "Number of active maps for bus_dmamem_alloc buffers");
158 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
159    "Number of active maps with BUS_DMA_COHERENT flag set");
160 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
161     &maploads_total, "Number of load operations performed");
162 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
163     &maploads_bounced, "Number of load operations that used bounce buffers");
164 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
165     &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
166 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
167     &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
168 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
169     &maploads_mbuf, "Number of load operations for mbufs");
170 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
171     &maploads_physmem, "Number of load operations on physical buffers");
172 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
173    "Total bounce pages");
174
175 struct bus_dmamap {
176         struct bp_list          bpages;
177         int                     pagesneeded;
178         int                     pagesreserved;
179         bus_dma_tag_t           dmat;
180         struct memdesc          mem;
181         bus_dmamap_callback_t   *callback;
182         void                    *callback_arg;
183         int                     flags;
184 #define DMAMAP_COHERENT         (1 << 0)
185 #define DMAMAP_DMAMEM_ALLOC     (1 << 1)
186 #define DMAMAP_MBUF             (1 << 2)
187         STAILQ_ENTRY(bus_dmamap) links;
188         bus_dma_segment_t       *segments;
189         int                     sync_count;
190         struct sync_list        slist[];
191 };
192
193 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
194 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
195
196 static void init_bounce_pages(void *dummy);
197 static int alloc_bounce_zone(bus_dma_tag_t dmat);
198 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
199 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
200     int commit);
201 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
202     vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
203 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
204 static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap,
205     bus_dmamap_t map, void *buf, bus_size_t buflen, int flags);
206 static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
207     vm_paddr_t buf, bus_size_t buflen, int flags);
208 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
209     int flags);
210 static void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
211 static void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
212
213 static busdma_bufalloc_t coherent_allocator;    /* Cache of coherent buffers */
214 static busdma_bufalloc_t standard_allocator;    /* Cache of standard buffers */
215
216 MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
217 MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
218
219 static void
220 busdma_init(void *dummy)
221 {
222         int uma_flags;
223
224         maploads_total    = counter_u64_alloc(M_WAITOK);
225         maploads_bounced  = counter_u64_alloc(M_WAITOK);
226         maploads_coherent = counter_u64_alloc(M_WAITOK);
227         maploads_dmamem   = counter_u64_alloc(M_WAITOK);
228         maploads_mbuf     = counter_u64_alloc(M_WAITOK);
229         maploads_physmem  = counter_u64_alloc(M_WAITOK);
230
231         uma_flags = 0;
232
233         /* Create a cache of buffers in standard (cacheable) memory. */
234         standard_allocator = busdma_bufalloc_create("buffer",
235             BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
236             NULL,               /* uma_alloc func */
237             NULL,               /* uma_free func */
238             uma_flags);         /* uma_zcreate_flags */
239
240 #ifdef INVARIANTS
241         /*
242          * Force UMA zone to allocate service structures like
243          * slabs using own allocator. uma_debug code performs
244          * atomic ops on uma_slab_t fields and safety of this
245          * operation is not guaranteed for write-back caches
246          */
247         uma_flags = UMA_ZONE_NOTOUCH;
248 #endif
249         /*
250          * Create a cache of buffers in uncacheable memory, to implement the
251          * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
252          */
253         coherent_allocator = busdma_bufalloc_create("coherent",
254             BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
255             busdma_bufalloc_alloc_uncacheable,
256             busdma_bufalloc_free_uncacheable,
257             uma_flags); /* uma_zcreate_flags */
258 }
259
260 /*
261  * This init historically used SI_SUB_VM, but now the init code requires
262  * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
263  * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
264  * using SI_SUB_KMEM+1.
265  */
266 SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
267
268 /*
269  * This routine checks the exclusion zone constraints from a tag against the
270  * physical RAM available on the machine.  If a tag specifies an exclusion zone
271  * but there's no RAM in that zone, then we avoid allocating resources to bounce
272  * a request, and we can use any memory allocator (as opposed to needing
273  * kmem_alloc_contig() just because it can allocate pages in an address range).
274  *
275  * Most tags have BUS_SPACE_MAXADDR or BUS_SPACE_MAXADDR_32BIT (they are the
276  * same value on 32-bit architectures) as their lowaddr constraint, and we can't
277  * possibly have RAM at an address higher than the highest address we can
278  * express, so we take a fast out.
279  */
280 static int
281 exclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
282 {
283         int i;
284
285         if (lowaddr >= BUS_SPACE_MAXADDR)
286                 return (0);
287
288         for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
289                 if ((lowaddr >= phys_avail[i] && lowaddr < phys_avail[i + 1]) ||
290                     (lowaddr < phys_avail[i] && highaddr >= phys_avail[i]))
291                         return (1);
292         }
293         return (0);
294 }
295
296 /*
297  * Return true if the tag has an exclusion zone that could lead to bouncing.
298  */
299 static __inline int
300 exclusion_bounce(bus_dma_tag_t dmat)
301 {
302
303         return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
304 }
305
306 /*
307  * Return true if the given address does not fall on the alignment boundary.
308  */
309 static __inline int
310 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
311 {
312
313         return (addr & (dmat->alignment - 1));
314 }
315
316 /*
317  * Return true if the DMA should bounce because the start or end does not fall
318  * on a cacheline boundary (which would require a partial cacheline flush).
319  * COHERENT memory doesn't trigger cacheline flushes.  Memory allocated by
320  * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
321  * strict rule that such memory cannot be accessed by the CPU while DMA is in
322  * progress (or by multiple DMA engines at once), so that it's always safe to do
323  * full cacheline flushes even if that affects memory outside the range of a
324  * given DMA operation that doesn't involve the full allocated buffer.  If we're
325  * mapping an mbuf, that follows the same rules as a buffer we allocated.
326  */
327 static __inline int
328 cacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
329 {
330
331         if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
332                 return (0);
333         return ((addr | size) & BUSDMA_DCACHE_MASK);
334 }
335
336 /*
337  * Return true if we might need to bounce the DMA described by addr and size.
338  *
339  * This is used to quick-check whether we need to do the more expensive work of
340  * checking the DMA page-by-page looking for alignment and exclusion bounces.
341  *
342  * Note that the addr argument might be either virtual or physical.  It doesn't
343  * matter because we only look at the low-order bits, which are the same in both
344  * address spaces and maximum alignment of generic buffer is limited up to page
345  * size.
346  * Bouncing of buffers allocated by bus_dmamem_alloc()is not necessary, these
347  * always comply with the required rules (alignment, boundary, and address
348  * range).
349  */
350 static __inline int
351 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
352     bus_size_t size)
353 {
354
355         KASSERT(map->flags & DMAMAP_DMAMEM_ALLOC ||
356             dmat->alignment <= PAGE_SIZE,
357             ("%s: unsupported alignment (0x%08lx) for buffer not "
358             "allocated by bus_dmamem_alloc()",
359             __func__, dmat->alignment));
360
361         return (!(map->flags & DMAMAP_DMAMEM_ALLOC) &&
362             ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
363             alignment_bounce(dmat, addr) ||
364             cacheline_bounce(map, addr, size)));
365 }
366
367 /*
368  * Return true if we must bounce the DMA described by paddr and size.
369  *
370  * Bouncing can be triggered by DMA that doesn't begin and end on cacheline
371  * boundaries, or doesn't begin on an alignment boundary, or falls within the
372  * exclusion zone of any tag in the ancestry chain.
373  *
374  * For exclusions, walk the chain of tags comparing paddr to the exclusion zone
375  * within each tag.  If the tag has a filter function, use it to decide whether
376  * the DMA needs to bounce, otherwise any DMA within the zone bounces.
377  */
378 static int
379 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
380     bus_size_t size)
381 {
382
383         if (cacheline_bounce(map, paddr, size))
384                 return (1);
385
386         /*
387          *  The tag already contains ancestors' alignment restrictions so this
388          *  check doesn't need to be inside the loop.
389          */
390         if (alignment_bounce(dmat, paddr))
391                 return (1);
392
393         /*
394          * Even though each tag has an exclusion zone that is a superset of its
395          * own and all its ancestors' exclusions, the exclusion zone of each tag
396          * up the chain must be checked within the loop, because the busdma
397          * rules say the filter function is called only when the address lies
398          * within the low-highaddr range of the tag that filterfunc belongs to.
399          */
400         while (dmat != NULL && exclusion_bounce(dmat)) {
401                 if ((paddr >= dmat->lowaddr && paddr <= dmat->highaddr) &&
402                     (dmat->filter == NULL ||
403                     dmat->filter(dmat->filterarg, paddr) != 0))
404                         return (1);
405                 dmat = dmat->parent;
406         }
407
408         return (0);
409 }
410
411 /*
412  * Convenience function for manipulating driver locks from busdma (during
413  * busdma_swi, for example).  Drivers that don't provide their own locks
414  * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
415  * non-mutex locking scheme don't have to use this at all.
416  */
417 void
418 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
419 {
420         struct mtx *dmtx;
421
422         dmtx = (struct mtx *)arg;
423         switch (op) {
424         case BUS_DMA_LOCK:
425                 mtx_lock(dmtx);
426                 break;
427         case BUS_DMA_UNLOCK:
428                 mtx_unlock(dmtx);
429                 break;
430         default:
431                 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
432         }
433 }
434
435 /*
436  * dflt_lock should never get called.  It gets put into the dma tag when
437  * lockfunc == NULL, which is only valid if the maps that are associated
438  * with the tag are meant to never be defered.
439  * XXX Should have a way to identify which driver is responsible here.
440  */
441 static void
442 dflt_lock(void *arg, bus_dma_lock_op_t op)
443 {
444
445         panic("driver error: busdma dflt_lock called");
446 }
447
448 /*
449  * Allocate a device specific dma_tag.
450  */
451 int
452 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
453     bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
454     bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
455     int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
456     void *lockfuncarg, bus_dma_tag_t *dmat)
457 {
458         bus_dma_tag_t newtag;
459         int error = 0;
460
461         /* Basic sanity checking. */
462         KASSERT(boundary == 0 || powerof2(boundary),
463             ("dma tag boundary %lu, must be a power of 2", boundary));
464         KASSERT(boundary == 0 || boundary >= maxsegsz,
465             ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
466         KASSERT(alignment != 0 && powerof2(alignment),
467             ("dma tag alignment %lu, must be non-zero power of 2", alignment));
468         KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
469
470         /* Return a NULL tag on failure */
471         *dmat = NULL;
472
473         newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
474             M_ZERO | M_NOWAIT);
475         if (newtag == NULL) {
476                 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
477                     __func__, newtag, 0, error);
478                 return (ENOMEM);
479         }
480
481         newtag->parent = parent;
482         newtag->alignment = alignment;
483         newtag->boundary = boundary;
484         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
485         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
486             (PAGE_SIZE - 1);
487         newtag->filter = filter;
488         newtag->filterarg = filterarg;
489         newtag->maxsize = maxsize;
490         newtag->nsegments = nsegments;
491         newtag->maxsegsz = maxsegsz;
492         newtag->flags = flags;
493         newtag->ref_count = 1; /* Count ourself */
494         newtag->map_count = 0;
495         if (lockfunc != NULL) {
496                 newtag->lockfunc = lockfunc;
497                 newtag->lockfuncarg = lockfuncarg;
498         } else {
499                 newtag->lockfunc = dflt_lock;
500                 newtag->lockfuncarg = NULL;
501         }
502
503         /* Take into account any restrictions imposed by our parent tag */
504         if (parent != NULL) {
505                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
506                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
507                 newtag->alignment = MAX(parent->alignment, newtag->alignment);
508                 newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
509                 newtag->flags |= parent->flags & BUS_DMA_COHERENT;
510                 if (newtag->boundary == 0)
511                         newtag->boundary = parent->boundary;
512                 else if (parent->boundary != 0)
513                         newtag->boundary = MIN(parent->boundary,
514                                                newtag->boundary);
515                 if (newtag->filter == NULL) {
516                         /*
517                          * Short circuit to looking at our parent directly
518                          * since we have encapsulated all of its information
519                          */
520                         newtag->filter = parent->filter;
521                         newtag->filterarg = parent->filterarg;
522                         newtag->parent = parent->parent;
523                 }
524                 if (newtag->parent != NULL)
525                         atomic_add_int(&parent->ref_count, 1);
526         }
527
528         if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
529                 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
530         if (alignment_bounce(newtag, 1))
531                 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
532
533         /*
534          * Any request can auto-bounce due to cacheline alignment, in addition
535          * to any alignment or boundary specifications in the tag, so if the
536          * ALLOCNOW flag is set, there's always work to do.
537          */
538         if ((flags & BUS_DMA_ALLOCNOW) != 0) {
539                 struct bounce_zone *bz;
540                 /*
541                  * Round size up to a full page, and add one more page because
542                  * there can always be one more boundary crossing than the
543                  * number of pages in a transfer.
544                  */
545                 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
546
547                 if ((error = alloc_bounce_zone(newtag)) != 0) {
548                         free(newtag, M_BUSDMA);
549                         return (error);
550                 }
551                 bz = newtag->bounce_zone;
552
553                 if (ptoa(bz->total_bpages) < maxsize) {
554                         int pages;
555
556                         pages = atop(maxsize) - bz->total_bpages;
557
558                         /* Add pages to our bounce pool */
559                         if (alloc_bounce_pages(newtag, pages) < pages)
560                                 error = ENOMEM;
561                 }
562                 /* Performed initial allocation */
563                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
564         } else
565                 newtag->bounce_zone = NULL;
566
567         if (error != 0) {
568                 free(newtag, M_BUSDMA);
569         } else {
570                 atomic_add_32(&tags_total, 1);
571                 *dmat = newtag;
572         }
573         CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
574             __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
575         return (error);
576 }
577
578 void
579 bus_dma_template_init(bus_dma_tag_template_t *t, bus_dma_tag_t parent)
580 {
581
582         if (t == NULL)
583                 return;
584
585         t->parent = parent;
586         t->alignment = 1;
587         t->boundary = 0;
588         t->lowaddr = t->highaddr = BUS_SPACE_MAXADDR;
589         t->maxsize = t->maxsegsize = BUS_SPACE_MAXSIZE;
590         t->nsegments = BUS_SPACE_UNRESTRICTED;
591         t->lockfunc = NULL;
592         t->lockfuncarg = NULL;
593         t->flags = 0;
594 }
595
596 int
597 bus_dma_template_tag(bus_dma_tag_template_t *t, bus_dma_tag_t *dmat)
598 {
599
600         if (t == NULL || dmat == NULL)
601                 return (EINVAL);
602
603         return (bus_dma_tag_create(t->parent, t->alignment, t->boundary,
604             t->lowaddr, t->highaddr, NULL, NULL, t->maxsize,
605             t->nsegments, t->maxsegsize, t->flags, t->lockfunc, t->lockfuncarg,
606             dmat));
607 }
608
609 void
610 bus_dma_template_clone(bus_dma_tag_template_t *t, bus_dma_tag_t dmat)
611 {
612
613         if (t == NULL || dmat == NULL)
614                 return;
615
616         t->parent = dmat->parent;
617         t->alignment = dmat->alignment;
618         t->boundary = dmat->boundary;
619         t->lowaddr = dmat->lowaddr;
620         t->highaddr = dmat->highaddr;
621         t->maxsize = dmat->maxsize;
622         t->nsegments = dmat->nsegments;
623         t->maxsegsize = dmat->maxsegsz;
624         t->flags = dmat->flags;
625         t->lockfunc = dmat->lockfunc;
626         t->lockfuncarg = dmat->lockfuncarg;
627 }
628
629 int
630 bus_dma_tag_set_domain(bus_dma_tag_t dmat, int domain)
631 {
632
633         return (0);
634 }
635
636 int
637 bus_dma_tag_destroy(bus_dma_tag_t dmat)
638 {
639         bus_dma_tag_t dmat_copy;
640         int error;
641
642         error = 0;
643         dmat_copy = dmat;
644
645         if (dmat != NULL) {
646
647                 if (dmat->map_count != 0) {
648                         error = EBUSY;
649                         goto out;
650                 }
651
652                 while (dmat != NULL) {
653                         bus_dma_tag_t parent;
654
655                         parent = dmat->parent;
656                         atomic_subtract_int(&dmat->ref_count, 1);
657                         if (dmat->ref_count == 0) {
658                                 atomic_subtract_32(&tags_total, 1);
659                                 free(dmat, M_BUSDMA);
660                                 /*
661                                  * Last reference count, so
662                                  * release our reference
663                                  * count on our parent.
664                                  */
665                                 dmat = parent;
666                         } else
667                                 dmat = NULL;
668                 }
669         }
670 out:
671         CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
672         return (error);
673 }
674
675 static int
676 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
677 {
678         struct bounce_zone *bz;
679         int maxpages;
680         int error;
681
682         if (dmat->bounce_zone == NULL)
683                 if ((error = alloc_bounce_zone(dmat)) != 0)
684                         return (error);
685         bz = dmat->bounce_zone;
686         /* Initialize the new map */
687         STAILQ_INIT(&(mapp->bpages));
688
689         /*
690          * Attempt to add pages to our pool on a per-instance basis up to a sane
691          * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
692          * alignment and boundary constraints, it could still auto-bounce due to
693          * cacheline alignment, which requires at most two bounce pages.
694          */
695         if (dmat->flags & BUS_DMA_COULD_BOUNCE)
696                 maxpages = MAX_BPAGES;
697         else
698                 maxpages = 2 * bz->map_count;
699         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
700             (bz->map_count > 0 && bz->total_bpages < maxpages)) {
701                 int pages;
702
703                 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
704                 pages = MIN(maxpages - bz->total_bpages, pages);
705                 pages = MAX(pages, 2);
706                 if (alloc_bounce_pages(dmat, pages) < pages)
707                         return (ENOMEM);
708
709                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
710                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
711         }
712         bz->map_count++;
713         return (0);
714 }
715
716 static bus_dmamap_t
717 allocate_map(bus_dma_tag_t dmat, int mflags)
718 {
719         int mapsize, segsize;
720         bus_dmamap_t map;
721
722         /*
723          * Allocate the map.  The map structure ends with an embedded
724          * variable-sized array of sync_list structures.  Following that
725          * we allocate enough extra space to hold the array of bus_dma_segments.
726          */
727         KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
728            ("cannot allocate %u dma segments (max is %u)",
729             dmat->nsegments, MAX_DMA_SEGMENTS));
730         segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
731         mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
732         map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
733         if (map == NULL) {
734                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
735                 return (NULL);
736         }
737         map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
738         STAILQ_INIT(&map->bpages);
739         return (map);
740 }
741
742 /*
743  * Allocate a handle for mapping from kva/uva/physical
744  * address space into bus device space.
745  */
746 int
747 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
748 {
749         bus_dmamap_t map;
750         int error = 0;
751
752         *mapp = map = allocate_map(dmat, M_NOWAIT);
753         if (map == NULL) {
754                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
755                 return (ENOMEM);
756         }
757
758         /*
759          * Bouncing might be required if the driver asks for an exclusion
760          * region, a data alignment that is stricter than 1, or DMA that begins
761          * or ends with a partial cacheline.  Whether bouncing will actually
762          * happen can't be known until mapping time, but we need to pre-allocate
763          * resources now because we might not be allowed to at mapping time.
764          */
765         error = allocate_bz_and_pages(dmat, map);
766         if (error != 0) {
767                 free(map, M_BUSDMA);
768                 *mapp = NULL;
769                 return (error);
770         }
771         if (map->flags & DMAMAP_COHERENT)
772                 atomic_add_32(&maps_coherent, 1);
773         atomic_add_32(&maps_total, 1);
774         dmat->map_count++;
775
776         return (0);
777 }
778
779 /*
780  * Destroy a handle for mapping from kva/uva/physical
781  * address space into bus device space.
782  */
783 int
784 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
785 {
786
787         if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
788                 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
789                     __func__, dmat, EBUSY);
790                 return (EBUSY);
791         }
792         if (dmat->bounce_zone)
793                 dmat->bounce_zone->map_count--;
794         if (map->flags & DMAMAP_COHERENT)
795                 atomic_subtract_32(&maps_coherent, 1);
796         atomic_subtract_32(&maps_total, 1);
797         free(map, M_BUSDMA);
798         dmat->map_count--;
799         CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
800         return (0);
801 }
802
803 /*
804  * Allocate a piece of memory that can be efficiently mapped into bus device
805  * space based on the constraints listed in the dma tag.  Returns a pointer to
806  * the allocated memory, and a pointer to an associated bus_dmamap.
807  */
808 int
809 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
810     bus_dmamap_t *mapp)
811 {
812         busdma_bufalloc_t ba;
813         struct busdma_bufzone *bufzone;
814         bus_dmamap_t map;
815         vm_memattr_t memattr;
816         int mflags;
817
818         if (flags & BUS_DMA_NOWAIT)
819                 mflags = M_NOWAIT;
820         else
821                 mflags = M_WAITOK;
822         if (flags & BUS_DMA_ZERO)
823                 mflags |= M_ZERO;
824
825         *mapp = map = allocate_map(dmat, mflags);
826         if (map == NULL) {
827                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
828                     __func__, dmat, dmat->flags, ENOMEM);
829                 return (ENOMEM);
830         }
831         map->flags = DMAMAP_DMAMEM_ALLOC;
832
833         /* For coherent memory, set the map flag that disables sync ops. */
834         if (flags & BUS_DMA_COHERENT)
835                 map->flags |= DMAMAP_COHERENT;
836
837         /*
838          * Choose a busdma buffer allocator based on memory type flags.
839          * If the tag's COHERENT flag is set, that means normal memory
840          * is already coherent, use the normal allocator.
841          */
842         if ((flags & BUS_DMA_COHERENT) &&
843             ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
844                 memattr = VM_MEMATTR_UNCACHEABLE;
845                 ba = coherent_allocator;
846         } else {
847                 memattr = VM_MEMATTR_DEFAULT;
848                 ba = standard_allocator;
849         }
850
851         /*
852          * Try to find a bufzone in the allocator that holds a cache of buffers
853          * of the right size for this request.  If the buffer is too big to be
854          * held in the allocator cache, this returns NULL.
855          */
856         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
857
858         /*
859          * Allocate the buffer from the uma(9) allocator if...
860          *  - It's small enough to be in the allocator (bufzone not NULL).
861          *  - The alignment constraint isn't larger than the allocation size
862          *    (the allocator aligns buffers to their size boundaries).
863          *  - There's no need to handle lowaddr/highaddr exclusion zones.
864          * else allocate non-contiguous pages if...
865          *  - The page count that could get allocated doesn't exceed
866          *    nsegments also when the maximum segment size is less
867          *    than PAGE_SIZE.
868          *  - The alignment constraint isn't larger than a page boundary.
869          *  - There are no boundary-crossing constraints.
870          * else allocate a block of contiguous pages because one or more of the
871          * constraints is something that only the contig allocator can fulfill.
872          */
873         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
874             !exclusion_bounce(dmat)) {
875                 *vaddr = uma_zalloc(bufzone->umazone, mflags);
876         } else if (dmat->nsegments >=
877             howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
878             dmat->alignment <= PAGE_SIZE &&
879             (dmat->boundary % PAGE_SIZE) == 0) {
880                 *vaddr = (void *)kmem_alloc_attr(dmat->maxsize, mflags, 0,
881                     dmat->lowaddr, memattr);
882         } else {
883                 *vaddr = (void *)kmem_alloc_contig(dmat->maxsize, mflags, 0,
884                     dmat->lowaddr, dmat->alignment, dmat->boundary, memattr);
885         }
886         if (*vaddr == NULL) {
887                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
888                     __func__, dmat, dmat->flags, ENOMEM);
889                 free(map, M_BUSDMA);
890                 *mapp = NULL;
891                 return (ENOMEM);
892         }
893         if (map->flags & DMAMAP_COHERENT)
894                 atomic_add_32(&maps_coherent, 1);
895         atomic_add_32(&maps_dmamem, 1);
896         atomic_add_32(&maps_total, 1);
897         dmat->map_count++;
898
899         CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
900             __func__, dmat, dmat->flags, 0);
901         return (0);
902 }
903
904 /*
905  * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
906  * its associated map.
907  */
908 void
909 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
910 {
911         struct busdma_bufzone *bufzone;
912         busdma_bufalloc_t ba;
913
914         if ((map->flags & DMAMAP_COHERENT) &&
915             ((dmat->flags & BUS_DMA_COHERENT) == 0))
916                 ba = coherent_allocator;
917         else
918                 ba = standard_allocator;
919
920         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
921
922         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
923             !exclusion_bounce(dmat))
924                 uma_zfree(bufzone->umazone, vaddr);
925         else
926                 kmem_free((vm_offset_t)vaddr, dmat->maxsize);
927
928         dmat->map_count--;
929         if (map->flags & DMAMAP_COHERENT)
930                 atomic_subtract_32(&maps_coherent, 1);
931         atomic_subtract_32(&maps_total, 1);
932         atomic_subtract_32(&maps_dmamem, 1);
933         free(map, M_BUSDMA);
934         CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
935 }
936
937 static void
938 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
939     bus_size_t buflen, int flags)
940 {
941         bus_addr_t curaddr;
942         bus_size_t sgsize;
943
944         if (map->pagesneeded == 0) {
945                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
946                     " map= %p, pagesneeded= %d",
947                     dmat->lowaddr, dmat->boundary, dmat->alignment,
948                     map, map->pagesneeded);
949                 /*
950                  * Count the number of bounce pages
951                  * needed in order to complete this transfer
952                  */
953                 curaddr = buf;
954                 while (buflen != 0) {
955                         sgsize = MIN(buflen, dmat->maxsegsz);
956                         if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
957                                 sgsize = MIN(sgsize,
958                                     PAGE_SIZE - (curaddr & PAGE_MASK));
959                                 map->pagesneeded++;
960                         }
961                         curaddr += sgsize;
962                         buflen -= sgsize;
963                 }
964                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
965         }
966 }
967
968 static void
969 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
970     void *buf, bus_size_t buflen, int flags)
971 {
972         vm_offset_t vaddr;
973         vm_offset_t vendaddr;
974         bus_addr_t paddr;
975
976         if (map->pagesneeded == 0) {
977                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
978                     " map= %p, pagesneeded= %d",
979                     dmat->lowaddr, dmat->boundary, dmat->alignment,
980                     map, map->pagesneeded);
981                 /*
982                  * Count the number of bounce pages
983                  * needed in order to complete this transfer
984                  */
985                 vaddr = (vm_offset_t)buf;
986                 vendaddr = (vm_offset_t)buf + buflen;
987
988                 while (vaddr < vendaddr) {
989                         if (__predict_true(pmap == kernel_pmap))
990                                 paddr = pmap_kextract(vaddr);
991                         else
992                                 paddr = pmap_extract(pmap, vaddr);
993                         if (must_bounce(dmat, map, paddr,
994                             min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
995                             PAGE_MASK)))) != 0) {
996                                 map->pagesneeded++;
997                         }
998                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
999
1000                 }
1001                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
1002         }
1003 }
1004
1005 static int
1006 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
1007 {
1008
1009         /* Reserve Necessary Bounce Pages */
1010         mtx_lock(&bounce_lock);
1011         if (flags & BUS_DMA_NOWAIT) {
1012                 if (reserve_bounce_pages(dmat, map, 0) != 0) {
1013                         map->pagesneeded = 0;
1014                         mtx_unlock(&bounce_lock);
1015                         return (ENOMEM);
1016                 }
1017         } else {
1018                 if (reserve_bounce_pages(dmat, map, 1) != 0) {
1019                         /* Queue us for resources */
1020                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
1021                         mtx_unlock(&bounce_lock);
1022                         return (EINPROGRESS);
1023                 }
1024         }
1025         mtx_unlock(&bounce_lock);
1026
1027         return (0);
1028 }
1029
1030 /*
1031  * Add a single contiguous physical range to the segment list.
1032  */
1033 static int
1034 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
1035     bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
1036 {
1037         bus_addr_t baddr, bmask;
1038         int seg;
1039
1040         /*
1041          * Make sure we don't cross any boundaries.
1042          */
1043         bmask = ~(dmat->boundary - 1);
1044         if (dmat->boundary > 0) {
1045                 baddr = (curaddr + dmat->boundary) & bmask;
1046                 if (sgsize > (baddr - curaddr))
1047                         sgsize = (baddr - curaddr);
1048         }
1049
1050         /*
1051          * Insert chunk into a segment, coalescing with
1052          * previous segment if possible.
1053          */
1054         seg = *segp;
1055         if (seg == -1) {
1056                 seg = 0;
1057                 segs[seg].ds_addr = curaddr;
1058                 segs[seg].ds_len = sgsize;
1059         } else {
1060                 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
1061                     (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
1062                     (dmat->boundary == 0 ||
1063                     (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
1064                         segs[seg].ds_len += sgsize;
1065                 else {
1066                         if (++seg >= dmat->nsegments)
1067                                 return (0);
1068                         segs[seg].ds_addr = curaddr;
1069                         segs[seg].ds_len = sgsize;
1070                 }
1071         }
1072         *segp = seg;
1073         return (sgsize);
1074 }
1075
1076 /*
1077  * Utility function to load a physical buffer.  segp contains
1078  * the starting segment on entrace, and the ending segment on exit.
1079  */
1080 int
1081 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1082     bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1083 {
1084         bus_addr_t curaddr;
1085         bus_addr_t sl_end = 0;
1086         bus_size_t sgsize;
1087         struct sync_list *sl;
1088         int error;
1089
1090         if (segs == NULL)
1091                 segs = map->segments;
1092
1093         counter_u64_add(maploads_total, 1);
1094         counter_u64_add(maploads_physmem, 1);
1095
1096         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1097                 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1098                 if (map->pagesneeded != 0) {
1099                         counter_u64_add(maploads_bounced, 1);
1100                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1101                         if (error)
1102                                 return (error);
1103                 }
1104         }
1105
1106         sl = map->slist + map->sync_count - 1;
1107
1108         while (buflen > 0) {
1109                 curaddr = buf;
1110                 sgsize = MIN(buflen, dmat->maxsegsz);
1111                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1112                     sgsize)) {
1113                         sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1114                         curaddr = add_bounce_page(dmat, map, 0, curaddr,
1115                             sgsize);
1116                 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1117                         if (map->sync_count > 0)
1118                                 sl_end = sl->paddr + sl->datacount;
1119
1120                         if (map->sync_count == 0 || curaddr != sl_end) {
1121                                 if (++map->sync_count > dmat->nsegments)
1122                                         break;
1123                                 sl++;
1124                                 sl->vaddr = 0;
1125                                 sl->paddr = curaddr;
1126                                 sl->datacount = sgsize;
1127                                 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1128                                 KASSERT(sl->pages != NULL,
1129                                     ("%s: page at PA:0x%08lx is not in "
1130                                     "vm_page_array", __func__, curaddr));
1131                         } else
1132                                 sl->datacount += sgsize;
1133                 }
1134                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1135                     segp);
1136                 if (sgsize == 0)
1137                         break;
1138                 buf += sgsize;
1139                 buflen -= sgsize;
1140         }
1141
1142         /*
1143          * Did we fit?
1144          */
1145         if (buflen != 0) {
1146                 bus_dmamap_unload(dmat, map);
1147                 return (EFBIG); /* XXX better return value here? */
1148         }
1149         return (0);
1150 }
1151
1152 int
1153 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1154     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1155     bus_dma_segment_t *segs, int *segp)
1156 {
1157
1158         return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1159             segs, segp));
1160 }
1161
1162 /*
1163  * Utility function to load a linear buffer.  segp contains
1164  * the starting segment on entrance, and the ending segment on exit.
1165  */
1166 int
1167 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1168     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1169     int *segp)
1170 {
1171         bus_size_t sgsize;
1172         bus_addr_t curaddr;
1173         bus_addr_t sl_pend = 0;
1174         vm_offset_t kvaddr, vaddr, sl_vend = 0;
1175         struct sync_list *sl;
1176         int error;
1177
1178         counter_u64_add(maploads_total, 1);
1179         if (map->flags & DMAMAP_COHERENT)
1180                 counter_u64_add(maploads_coherent, 1);
1181         if (map->flags & DMAMAP_DMAMEM_ALLOC)
1182                 counter_u64_add(maploads_dmamem, 1);
1183
1184         if (segs == NULL)
1185                 segs = map->segments;
1186
1187         if (flags & BUS_DMA_LOAD_MBUF) {
1188                 counter_u64_add(maploads_mbuf, 1);
1189                 map->flags |= DMAMAP_MBUF;
1190         }
1191
1192         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1193                 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1194                 if (map->pagesneeded != 0) {
1195                         counter_u64_add(maploads_bounced, 1);
1196                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1197                         if (error)
1198                                 return (error);
1199                 }
1200         }
1201
1202         sl = map->slist + map->sync_count - 1;
1203         vaddr = (vm_offset_t)buf;
1204
1205         while (buflen > 0) {
1206                 /*
1207                  * Get the physical address for this segment.
1208                  */
1209                 if (__predict_true(pmap == kernel_pmap)) {
1210                         curaddr = pmap_kextract(vaddr);
1211                         kvaddr = vaddr;
1212                 } else {
1213                         curaddr = pmap_extract(pmap, vaddr);
1214                         kvaddr = 0;
1215                 }
1216
1217                 /*
1218                  * Compute the segment size, and adjust counts.
1219                  */
1220                 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1221                 if (sgsize > dmat->maxsegsz)
1222                         sgsize = dmat->maxsegsz;
1223                 if (buflen < sgsize)
1224                         sgsize = buflen;
1225
1226                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1227                     sgsize)) {
1228                         curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1229                             sgsize);
1230                 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1231                         if (map->sync_count > 0) {
1232                                 sl_pend = sl->paddr + sl->datacount;
1233                                 sl_vend = sl->vaddr + sl->datacount;
1234                         }
1235
1236                         if (map->sync_count == 0 ||
1237                             (kvaddr != 0 && kvaddr != sl_vend) ||
1238                             (curaddr != sl_pend)) {
1239
1240                                 if (++map->sync_count > dmat->nsegments)
1241                                         goto cleanup;
1242                                 sl++;
1243                                 sl->vaddr = kvaddr;
1244                                 sl->paddr = curaddr;
1245                                 if (kvaddr != 0) {
1246                                         sl->pages = NULL;
1247                                 } else {
1248                                         sl->pages = PHYS_TO_VM_PAGE(curaddr);
1249                                         KASSERT(sl->pages != NULL,
1250                                             ("%s: page at PA:0x%08lx is not "
1251                                             "in vm_page_array", __func__,
1252                                             curaddr));
1253                                 }
1254                                 sl->datacount = sgsize;
1255                         } else
1256                                 sl->datacount += sgsize;
1257                 }
1258                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1259                     segp);
1260                 if (sgsize == 0)
1261                         break;
1262                 vaddr += sgsize;
1263                 buflen -= sgsize;
1264         }
1265
1266 cleanup:
1267         /*
1268          * Did we fit?
1269          */
1270         if (buflen != 0) {
1271                 bus_dmamap_unload(dmat, map);
1272                 return (EFBIG); /* XXX better return value here? */
1273         }
1274         return (0);
1275 }
1276
1277 void
1278 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1279     bus_dmamap_callback_t *callback, void *callback_arg)
1280 {
1281
1282         map->mem = *mem;
1283         map->dmat = dmat;
1284         map->callback = callback;
1285         map->callback_arg = callback_arg;
1286 }
1287
1288 bus_dma_segment_t *
1289 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1290     bus_dma_segment_t *segs, int nsegs, int error)
1291 {
1292
1293         if (segs == NULL)
1294                 segs = map->segments;
1295         return (segs);
1296 }
1297
1298 /*
1299  * Release the mapping held by map.
1300  */
1301 void
1302 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1303 {
1304         struct bounce_page *bpage;
1305         struct bounce_zone *bz;
1306
1307         if ((bz = dmat->bounce_zone) != NULL) {
1308                 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1309                         STAILQ_REMOVE_HEAD(&map->bpages, links);
1310                         free_bounce_page(dmat, bpage);
1311                 }
1312
1313                 bz = dmat->bounce_zone;
1314                 bz->free_bpages += map->pagesreserved;
1315                 bz->reserved_bpages -= map->pagesreserved;
1316                 map->pagesreserved = 0;
1317                 map->pagesneeded = 0;
1318         }
1319         map->sync_count = 0;
1320         map->flags &= ~DMAMAP_MBUF;
1321 }
1322
1323 static void
1324 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1325 {
1326         /*
1327          * Write back any partial cachelines immediately before and
1328          * after the DMA region.  We don't need to round the address
1329          * down to the nearest cacheline or specify the exact size,
1330          * as dcache_wb_poc() will do the rounding for us and works
1331          * at cacheline granularity.
1332          */
1333         if (va & BUSDMA_DCACHE_MASK)
1334                 dcache_wb_poc(va, pa, 1);
1335         if ((va + size) & BUSDMA_DCACHE_MASK)
1336                 dcache_wb_poc(va + size, pa + size, 1);
1337
1338         dcache_inv_poc_dma(va, pa, size);
1339 }
1340
1341 static void
1342 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1343 {
1344         uint32_t len, offset;
1345         vm_page_t m;
1346         vm_paddr_t pa;
1347         vm_offset_t va, tempva;
1348         bus_size_t size;
1349
1350         offset = sl->paddr & PAGE_MASK;
1351         m = sl->pages;
1352         size = sl->datacount;
1353         pa = sl->paddr;
1354
1355         for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1356                 tempva = 0;
1357                 if (sl->vaddr == 0) {
1358                         len = min(PAGE_SIZE - offset, size);
1359                         tempva = pmap_quick_enter_page(m);
1360                         va = tempva | offset;
1361                         KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1362                             ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1363                             VM_PAGE_TO_PHYS(m) | offset, pa));
1364                 } else {
1365                         len = sl->datacount;
1366                         va = sl->vaddr;
1367                 }
1368
1369                 switch (op) {
1370                 case BUS_DMASYNC_PREWRITE:
1371                 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1372                         dcache_wb_poc(va, pa, len);
1373                         break;
1374                 case BUS_DMASYNC_PREREAD:
1375                         /*
1376                          * An mbuf may start in the middle of a cacheline. There
1377                          * will be no cpu writes to the beginning of that line
1378                          * (which contains the mbuf header) while dma is in
1379                          * progress.  Handle that case by doing a writeback of
1380                          * just the first cacheline before invalidating the
1381                          * overall buffer.  Any mbuf in a chain may have this
1382                          * misalignment.  Buffers which are not mbufs bounce if
1383                          * they are not aligned to a cacheline.
1384                          */
1385                         dma_preread_safe(va, pa, len);
1386                         break;
1387                 case BUS_DMASYNC_POSTREAD:
1388                 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1389                         dcache_inv_poc(va, pa, len);
1390                         break;
1391                 default:
1392                         panic("unsupported combination of sync operations: "
1393                               "0x%08x\n", op);
1394                 }
1395
1396                 if (tempva != 0)
1397                         pmap_quick_remove_page(tempva);
1398         }
1399 }
1400
1401 void
1402 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1403 {
1404         struct bounce_page *bpage;
1405         struct sync_list *sl, *end;
1406         vm_offset_t datavaddr, tempvaddr;
1407
1408         if (op == BUS_DMASYNC_POSTWRITE)
1409                 return;
1410
1411         /*
1412          * If the buffer was from user space, it is possible that this is not
1413          * the same vm map, especially on a POST operation.  It's not clear that
1414          * dma on userland buffers can work at all right now.  To be safe, until
1415          * we're able to test direct userland dma, panic on a map mismatch.
1416          */
1417         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1418
1419                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1420                     "performing bounce", __func__, dmat, dmat->flags, op);
1421
1422                 /*
1423                  * For PREWRITE do a writeback.  Clean the caches from the
1424                  * innermost to the outermost levels.
1425                  */
1426                 if (op & BUS_DMASYNC_PREWRITE) {
1427                         while (bpage != NULL) {
1428                                 tempvaddr = 0;
1429                                 datavaddr = bpage->datavaddr;
1430                                 if (datavaddr == 0) {
1431                                         tempvaddr = pmap_quick_enter_page(
1432                                             bpage->datapage);
1433                                         datavaddr = tempvaddr | bpage->dataoffs;
1434                                 }
1435                                 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1436                                     bpage->datacount);
1437                                 if (tempvaddr != 0)
1438                                         pmap_quick_remove_page(tempvaddr);
1439                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1440                                         dcache_wb_poc(bpage->vaddr,
1441                                             bpage->busaddr, bpage->datacount);
1442                                 bpage = STAILQ_NEXT(bpage, links);
1443                         }
1444                         dmat->bounce_zone->total_bounced++;
1445                 }
1446
1447                 /*
1448                  * Do an invalidate for PREREAD unless a writeback was already
1449                  * done above due to PREWRITE also being set.  The reason for a
1450                  * PREREAD invalidate is to prevent dirty lines currently in the
1451                  * cache from being evicted during the DMA.  If a writeback was
1452                  * done due to PREWRITE also being set there will be no dirty
1453                  * lines and the POSTREAD invalidate handles the rest. The
1454                  * invalidate is done from the innermost to outermost level. If
1455                  * L2 were done first, a dirty cacheline could be automatically
1456                  * evicted from L1 before we invalidated it, re-dirtying the L2.
1457                  */
1458                 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1459                         bpage = STAILQ_FIRST(&map->bpages);
1460                         while (bpage != NULL) {
1461                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1462                                         dcache_inv_poc_dma(bpage->vaddr,
1463                                             bpage->busaddr, bpage->datacount);
1464                                 bpage = STAILQ_NEXT(bpage, links);
1465                         }
1466                 }
1467
1468                 /*
1469                  * Re-invalidate the caches on a POSTREAD, even though they were
1470                  * already invalidated at PREREAD time.  Aggressive prefetching
1471                  * due to accesses to other data near the dma buffer could have
1472                  * brought buffer data into the caches which is now stale.  The
1473                  * caches are invalidated from the outermost to innermost; the
1474                  * prefetches could be happening right now, and if L1 were
1475                  * invalidated first, stale L2 data could be prefetched into L1.
1476                  */
1477                 if (op & BUS_DMASYNC_POSTREAD) {
1478                         while (bpage != NULL) {
1479                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1480                                         dcache_inv_poc(bpage->vaddr,
1481                                             bpage->busaddr, bpage->datacount);
1482                                 tempvaddr = 0;
1483                                 datavaddr = bpage->datavaddr;
1484                                 if (datavaddr == 0) {
1485                                         tempvaddr = pmap_quick_enter_page(
1486                                             bpage->datapage);
1487                                         datavaddr = tempvaddr | bpage->dataoffs;
1488                                 }
1489                                 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1490                                     bpage->datacount);
1491                                 if (tempvaddr != 0)
1492                                         pmap_quick_remove_page(tempvaddr);
1493                                 bpage = STAILQ_NEXT(bpage, links);
1494                         }
1495                         dmat->bounce_zone->total_bounced++;
1496                 }
1497         }
1498
1499         /*
1500          * For COHERENT memory no cache maintenance is necessary, but ensure all
1501          * writes have reached memory for the PREWRITE case.  No action is
1502          * needed for a PREREAD without PREWRITE also set, because that would
1503          * imply that the cpu had written to the COHERENT buffer and expected
1504          * the dma device to see that change, and by definition a PREWRITE sync
1505          * is required to make that happen.
1506          */
1507         if (map->flags & DMAMAP_COHERENT) {
1508                 if (op & BUS_DMASYNC_PREWRITE) {
1509                         dsb();
1510                         if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1511                                 cpu_l2cache_drain_writebuf();
1512                 }
1513                 return;
1514         }
1515
1516         /*
1517          * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1518          * the comments about the sequences for flushing cache levels in the
1519          * bounce buffer code above apply here as well.  In particular, the fact
1520          * that the sequence is inner-to-outer for PREREAD invalidation and
1521          * outer-to-inner for POSTREAD invalidation is not a mistake.
1522          */
1523         if (map->sync_count != 0) {
1524                 sl = &map->slist[0];
1525                 end = &map->slist[map->sync_count];
1526                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1527                     "performing sync", __func__, dmat, dmat->flags, op);
1528
1529                 for ( ; sl != end; ++sl)
1530                         dma_dcache_sync(sl, op);
1531         }
1532 }
1533
1534 static void
1535 init_bounce_pages(void *dummy __unused)
1536 {
1537
1538         total_bpages = 0;
1539         STAILQ_INIT(&bounce_zone_list);
1540         STAILQ_INIT(&bounce_map_waitinglist);
1541         STAILQ_INIT(&bounce_map_callbacklist);
1542         mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1543 }
1544 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1545
1546 static struct sysctl_ctx_list *
1547 busdma_sysctl_tree(struct bounce_zone *bz)
1548 {
1549
1550         return (&bz->sysctl_tree);
1551 }
1552
1553 static struct sysctl_oid *
1554 busdma_sysctl_tree_top(struct bounce_zone *bz)
1555 {
1556
1557         return (bz->sysctl_tree_top);
1558 }
1559
1560 static int
1561 alloc_bounce_zone(bus_dma_tag_t dmat)
1562 {
1563         struct bounce_zone *bz;
1564
1565         /* Check to see if we already have a suitable zone */
1566         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1567                 if ((dmat->alignment <= bz->alignment) &&
1568                     (dmat->lowaddr >= bz->lowaddr)) {
1569                         dmat->bounce_zone = bz;
1570                         return (0);
1571                 }
1572         }
1573
1574         if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1575             M_NOWAIT | M_ZERO)) == NULL)
1576                 return (ENOMEM);
1577
1578         STAILQ_INIT(&bz->bounce_page_list);
1579         bz->free_bpages = 0;
1580         bz->reserved_bpages = 0;
1581         bz->active_bpages = 0;
1582         bz->lowaddr = dmat->lowaddr;
1583         bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1584         bz->map_count = 0;
1585         snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1586         busdma_zonecount++;
1587         snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1588         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1589         dmat->bounce_zone = bz;
1590
1591         sysctl_ctx_init(&bz->sysctl_tree);
1592         bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1593             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1594             CTLFLAG_RD, 0, "");
1595         if (bz->sysctl_tree_top == NULL) {
1596                 sysctl_ctx_free(&bz->sysctl_tree);
1597                 return (0);     /* XXX error code? */
1598         }
1599
1600         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1601             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1602             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1603             "Total bounce pages");
1604         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1605             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1606             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1607             "Free bounce pages");
1608         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1609             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1610             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1611             "Reserved bounce pages");
1612         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1613             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1614             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1615             "Active bounce pages");
1616         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1617             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1618             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1619             "Total bounce requests (pages bounced)");
1620         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1621             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1622             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1623             "Total bounce requests that were deferred");
1624         SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1625             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1626             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1627         SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1628             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1629             "alignment", CTLFLAG_RD, &bz->alignment, "");
1630
1631         return (0);
1632 }
1633
1634 static int
1635 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1636 {
1637         struct bounce_zone *bz;
1638         int count;
1639
1640         bz = dmat->bounce_zone;
1641         count = 0;
1642         while (numpages > 0) {
1643                 struct bounce_page *bpage;
1644
1645                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1646                     M_NOWAIT | M_ZERO);
1647
1648                 if (bpage == NULL)
1649                         break;
1650                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1651                     M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1652                 if (bpage->vaddr == 0) {
1653                         free(bpage, M_BUSDMA);
1654                         break;
1655                 }
1656                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1657                 mtx_lock(&bounce_lock);
1658                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1659                 total_bpages++;
1660                 bz->total_bpages++;
1661                 bz->free_bpages++;
1662                 mtx_unlock(&bounce_lock);
1663                 count++;
1664                 numpages--;
1665         }
1666         return (count);
1667 }
1668
1669 static int
1670 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1671 {
1672         struct bounce_zone *bz;
1673         int pages;
1674
1675         mtx_assert(&bounce_lock, MA_OWNED);
1676         bz = dmat->bounce_zone;
1677         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1678         if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1679                 return (map->pagesneeded - (map->pagesreserved + pages));
1680         bz->free_bpages -= pages;
1681         bz->reserved_bpages += pages;
1682         map->pagesreserved += pages;
1683         pages = map->pagesneeded - map->pagesreserved;
1684
1685         return (pages);
1686 }
1687
1688 static bus_addr_t
1689 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1690     bus_addr_t addr, bus_size_t size)
1691 {
1692         struct bounce_zone *bz;
1693         struct bounce_page *bpage;
1694
1695         KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1696         KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1697
1698         bz = dmat->bounce_zone;
1699         if (map->pagesneeded == 0)
1700                 panic("add_bounce_page: map doesn't need any pages");
1701         map->pagesneeded--;
1702
1703         if (map->pagesreserved == 0)
1704                 panic("add_bounce_page: map doesn't need any pages");
1705         map->pagesreserved--;
1706
1707         mtx_lock(&bounce_lock);
1708         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1709         if (bpage == NULL)
1710                 panic("add_bounce_page: free page list is empty");
1711
1712         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1713         bz->reserved_bpages--;
1714         bz->active_bpages++;
1715         mtx_unlock(&bounce_lock);
1716
1717         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1718                 /* Page offset needs to be preserved. */
1719                 bpage->vaddr |= addr & PAGE_MASK;
1720                 bpage->busaddr |= addr & PAGE_MASK;
1721         }
1722         bpage->datavaddr = vaddr;
1723         bpage->datapage = PHYS_TO_VM_PAGE(addr);
1724         bpage->dataoffs = addr & PAGE_MASK;
1725         bpage->datacount = size;
1726         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1727         return (bpage->busaddr);
1728 }
1729
1730 static void
1731 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1732 {
1733         struct bus_dmamap *map;
1734         struct bounce_zone *bz;
1735
1736         bz = dmat->bounce_zone;
1737         bpage->datavaddr = 0;
1738         bpage->datacount = 0;
1739         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1740                 /*
1741                  * Reset the bounce page to start at offset 0.  Other uses
1742                  * of this bounce page may need to store a full page of
1743                  * data and/or assume it starts on a page boundary.
1744                  */
1745                 bpage->vaddr &= ~PAGE_MASK;
1746                 bpage->busaddr &= ~PAGE_MASK;
1747         }
1748
1749         mtx_lock(&bounce_lock);
1750         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1751         bz->free_bpages++;
1752         bz->active_bpages--;
1753         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1754                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1755                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1756                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1757                             map, links);
1758                         busdma_swi_pending = 1;
1759                         bz->total_deferred++;
1760                         swi_sched(vm_ih, 0);
1761                 }
1762         }
1763         mtx_unlock(&bounce_lock);
1764 }
1765
1766 void
1767 busdma_swi(void)
1768 {
1769         bus_dma_tag_t dmat;
1770         struct bus_dmamap *map;
1771
1772         mtx_lock(&bounce_lock);
1773         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1774                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1775                 mtx_unlock(&bounce_lock);
1776                 dmat = map->dmat;
1777                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1778                 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1779                     map->callback_arg, BUS_DMA_WAITOK);
1780                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1781                 mtx_lock(&bounce_lock);
1782         }
1783         mtx_unlock(&bounce_lock);
1784 }