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