]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/busdma_machdep-v6.c
Fix arm stack frame walking support:
[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-v6.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                 if (newtag->boundary == 0)
495                         newtag->boundary = parent->boundary;
496                 else if (parent->boundary != 0)
497                         newtag->boundary = MIN(parent->boundary,
498                                                newtag->boundary);
499                 if (newtag->filter == NULL) {
500                         /*
501                          * Short circuit to looking at our parent directly
502                          * since we have encapsulated all of its information
503                          */
504                         newtag->filter = parent->filter;
505                         newtag->filterarg = parent->filterarg;
506                         newtag->parent = parent->parent;
507                 }
508                 if (newtag->parent != NULL)
509                         atomic_add_int(&parent->ref_count, 1);
510         }
511
512         if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
513                 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
514         if (alignment_bounce(newtag, 1))
515                 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
516
517         /*
518          * Any request can auto-bounce due to cacheline alignment, in addition
519          * to any alignment or boundary specifications in the tag, so if the
520          * ALLOCNOW flag is set, there's always work to do.
521          */
522         if ((flags & BUS_DMA_ALLOCNOW) != 0) {
523                 struct bounce_zone *bz;
524                 /*
525                  * Round size up to a full page, and add one more page because
526                  * there can always be one more boundary crossing than the
527                  * number of pages in a transfer.
528                  */
529                 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
530
531                 if ((error = alloc_bounce_zone(newtag)) != 0) {
532                         free(newtag, M_BUSDMA);
533                         return (error);
534                 }
535                 bz = newtag->bounce_zone;
536
537                 if (ptoa(bz->total_bpages) < maxsize) {
538                         int pages;
539
540                         pages = atop(maxsize) - bz->total_bpages;
541
542                         /* Add pages to our bounce pool */
543                         if (alloc_bounce_pages(newtag, pages) < pages)
544                                 error = ENOMEM;
545                 }
546                 /* Performed initial allocation */
547                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
548         } else
549                 newtag->bounce_zone = NULL;
550
551         if (error != 0) {
552                 free(newtag, M_BUSDMA);
553         } else {
554                 atomic_add_32(&tags_total, 1);
555                 *dmat = newtag;
556         }
557         CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
558             __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
559         return (error);
560 }
561
562 int
563 bus_dma_tag_destroy(bus_dma_tag_t dmat)
564 {
565         bus_dma_tag_t dmat_copy;
566         int error;
567
568         error = 0;
569         dmat_copy = dmat;
570
571         if (dmat != NULL) {
572
573                 if (dmat->map_count != 0) {
574                         error = EBUSY;
575                         goto out;
576                 }
577
578                 while (dmat != NULL) {
579                         bus_dma_tag_t parent;
580
581                         parent = dmat->parent;
582                         atomic_subtract_int(&dmat->ref_count, 1);
583                         if (dmat->ref_count == 0) {
584                                 atomic_subtract_32(&tags_total, 1);
585                                 free(dmat, M_BUSDMA);
586                                 /*
587                                  * Last reference count, so
588                                  * release our reference
589                                  * count on our parent.
590                                  */
591                                 dmat = parent;
592                         } else
593                                 dmat = NULL;
594                 }
595         }
596 out:
597         CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
598         return (error);
599 }
600
601 static int
602 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
603 {
604         struct bounce_zone *bz;
605         int maxpages;
606         int error;
607
608         if (dmat->bounce_zone == NULL)
609                 if ((error = alloc_bounce_zone(dmat)) != 0)
610                         return (error);
611         bz = dmat->bounce_zone;
612         /* Initialize the new map */
613         STAILQ_INIT(&(mapp->bpages));
614
615         /*
616          * Attempt to add pages to our pool on a per-instance basis up to a sane
617          * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
618          * alignment and boundary constraints, it could still auto-bounce due to
619          * cacheline alignment, which requires at most two bounce pages.
620          */
621         if (dmat->flags & BUS_DMA_COULD_BOUNCE)
622                 maxpages = MAX_BPAGES;
623         else
624                 maxpages = 2 * bz->map_count;
625         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
626             (bz->map_count > 0 && bz->total_bpages < maxpages)) {
627                 int pages;
628
629                 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
630                 pages = MIN(maxpages - bz->total_bpages, pages);
631                 pages = MAX(pages, 2);
632                 if (alloc_bounce_pages(dmat, pages) < pages)
633                         return (ENOMEM);
634
635                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
636                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
637         }
638         bz->map_count++;
639         return (0);
640 }
641
642 static bus_dmamap_t
643 allocate_map(bus_dma_tag_t dmat, int mflags)
644 {
645         int mapsize, segsize;
646         bus_dmamap_t map;
647
648         /*
649          * Allocate the map.  The map structure ends with an embedded
650          * variable-sized array of sync_list structures.  Following that
651          * we allocate enough extra space to hold the array of bus_dma_segments.
652          */
653         KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
654            ("cannot allocate %u dma segments (max is %u)",
655             dmat->nsegments, MAX_DMA_SEGMENTS));
656         segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
657         mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
658         map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
659         if (map == NULL) {
660                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
661                 return (NULL);
662         }
663         map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
664         return (map);
665 }
666
667 /*
668  * Allocate a handle for mapping from kva/uva/physical
669  * address space into bus device space.
670  */
671 int
672 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
673 {
674         bus_dmamap_t map;
675         int error = 0;
676
677         *mapp = map = allocate_map(dmat, M_NOWAIT);
678         if (map == NULL) {
679                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
680                 return (ENOMEM);
681         }
682
683         /*
684          * Bouncing might be required if the driver asks for an exclusion
685          * region, a data alignment that is stricter than 1, or DMA that begins
686          * or ends with a partial cacheline.  Whether bouncing will actually
687          * happen can't be known until mapping time, but we need to pre-allocate
688          * resources now because we might not be allowed to at mapping time.
689          */
690         error = allocate_bz_and_pages(dmat, map);
691         if (error != 0) {
692                 free(map, M_BUSDMA);
693                 *mapp = NULL;
694                 return (error);
695         }
696         if (map->flags & DMAMAP_COHERENT)
697                 atomic_add_32(&maps_coherent, 1);
698         atomic_add_32(&maps_total, 1);
699         dmat->map_count++;
700
701         return (0);
702 }
703
704 /*
705  * Destroy a handle for mapping from kva/uva/physical
706  * address space into bus device space.
707  */
708 int
709 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
710 {
711
712         if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
713                 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
714                     __func__, dmat, EBUSY);
715                 return (EBUSY);
716         }
717         if (dmat->bounce_zone)
718                 dmat->bounce_zone->map_count--;
719         if (map->flags & DMAMAP_COHERENT)
720                 atomic_subtract_32(&maps_coherent, 1);
721         atomic_subtract_32(&maps_total, 1);
722         free(map, M_BUSDMA);
723         dmat->map_count--;
724         CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
725         return (0);
726 }
727
728 /*
729  * Allocate a piece of memory that can be efficiently mapped into bus device
730  * space based on the constraints listed in the dma tag.  Returns a pointer to
731  * the allocated memory, and a pointer to an associated bus_dmamap.
732  */
733 int
734 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
735     bus_dmamap_t *mapp)
736 {
737         busdma_bufalloc_t ba;
738         struct busdma_bufzone *bufzone;
739         bus_dmamap_t map;
740         vm_memattr_t memattr;
741         int mflags;
742
743         if (flags & BUS_DMA_NOWAIT)
744                 mflags = M_NOWAIT;
745         else
746                 mflags = M_WAITOK;
747         if (flags & BUS_DMA_ZERO)
748                 mflags |= M_ZERO;
749
750         *mapp = map = allocate_map(dmat, mflags);
751         if (map == NULL) {
752                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
753                     __func__, dmat, dmat->flags, ENOMEM);
754                 return (ENOMEM);
755         }
756         map->flags = DMAMAP_DMAMEM_ALLOC;
757
758         /* Choose a busdma buffer allocator based on memory type flags. */
759         if (flags & BUS_DMA_COHERENT) {
760                 memattr = VM_MEMATTR_UNCACHEABLE;
761                 ba = coherent_allocator;
762                 map->flags |= DMAMAP_COHERENT;
763         } else {
764                 memattr = VM_MEMATTR_DEFAULT;
765                 ba = standard_allocator;
766         }
767
768         /*
769          * Try to find a bufzone in the allocator that holds a cache of buffers
770          * of the right size for this request.  If the buffer is too big to be
771          * held in the allocator cache, this returns NULL.
772          */
773         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
774
775         /*
776          * Allocate the buffer from the uma(9) allocator if...
777          *  - It's small enough to be in the allocator (bufzone not NULL).
778          *  - The alignment constraint isn't larger than the allocation size
779          *    (the allocator aligns buffers to their size boundaries).
780          *  - There's no need to handle lowaddr/highaddr exclusion zones.
781          * else allocate non-contiguous pages if...
782          *  - The page count that could get allocated doesn't exceed nsegments.
783          *  - The alignment constraint isn't larger than a page boundary.
784          *  - There are no boundary-crossing constraints.
785          * else allocate a block of contiguous pages because one or more of the
786          * constraints is something that only the contig allocator can fulfill.
787          */
788         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
789             !exclusion_bounce(dmat)) {
790                 *vaddr = uma_zalloc(bufzone->umazone, mflags);
791         } else if (dmat->nsegments >= btoc(dmat->maxsize) &&
792             dmat->alignment <= PAGE_SIZE && dmat->boundary == 0) {
793                 *vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
794                     mflags, 0, dmat->lowaddr, memattr);
795         } else {
796                 *vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
797                     mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
798                     memattr);
799         }
800         if (*vaddr == NULL) {
801                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
802                     __func__, dmat, dmat->flags, ENOMEM);
803                 free(map, M_BUSDMA);
804                 *mapp = NULL;
805                 return (ENOMEM);
806         }
807         if (map->flags & DMAMAP_COHERENT)
808                 atomic_add_32(&maps_coherent, 1);
809         atomic_add_32(&maps_dmamem, 1);
810         atomic_add_32(&maps_total, 1);
811         dmat->map_count++;
812
813         CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
814             __func__, dmat, dmat->flags, 0);
815         return (0);
816 }
817
818 /*
819  * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
820  * its associated map.
821  */
822 void
823 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
824 {
825         struct busdma_bufzone *bufzone;
826         busdma_bufalloc_t ba;
827
828         if (map->flags & DMAMAP_COHERENT)
829                 ba = coherent_allocator;
830         else
831                 ba = standard_allocator;
832
833         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
834
835         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
836             !exclusion_bounce(dmat))
837                 uma_zfree(bufzone->umazone, vaddr);
838         else
839                 kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
840
841         dmat->map_count--;
842         if (map->flags & DMAMAP_COHERENT)
843                 atomic_subtract_32(&maps_coherent, 1);
844         atomic_subtract_32(&maps_total, 1);
845         atomic_subtract_32(&maps_dmamem, 1);
846         free(map, M_BUSDMA);
847         CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
848 }
849
850 static void
851 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
852     bus_size_t buflen, int flags)
853 {
854         bus_addr_t curaddr;
855         bus_size_t sgsize;
856
857         if (map->pagesneeded == 0) {
858                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
859                     " map= %p, pagesneeded= %d",
860                     dmat->lowaddr, dmat->boundary, dmat->alignment,
861                     map, map->pagesneeded);
862                 /*
863                  * Count the number of bounce pages
864                  * needed in order to complete this transfer
865                  */
866                 curaddr = buf;
867                 while (buflen != 0) {
868                         sgsize = MIN(buflen, dmat->maxsegsz);
869                         if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
870                                 sgsize = MIN(sgsize,
871                                     PAGE_SIZE - (curaddr & PAGE_MASK));
872                                 map->pagesneeded++;
873                         }
874                         curaddr += sgsize;
875                         buflen -= sgsize;
876                 }
877                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
878         }
879 }
880
881 static void
882 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
883     void *buf, bus_size_t buflen, int flags)
884 {
885         vm_offset_t vaddr;
886         vm_offset_t vendaddr;
887         bus_addr_t paddr;
888
889         if (map->pagesneeded == 0) {
890                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
891                     " map= %p, pagesneeded= %d",
892                     dmat->lowaddr, dmat->boundary, dmat->alignment,
893                     map, map->pagesneeded);
894                 /*
895                  * Count the number of bounce pages
896                  * needed in order to complete this transfer
897                  */
898                 vaddr = (vm_offset_t)buf;
899                 vendaddr = (vm_offset_t)buf + buflen;
900
901                 while (vaddr < vendaddr) {
902                         if (__predict_true(pmap == kernel_pmap))
903                                 paddr = pmap_kextract(vaddr);
904                         else
905                                 paddr = pmap_extract(pmap, vaddr);
906                         if (must_bounce(dmat, map, paddr,
907                             min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
908                             PAGE_MASK)))) != 0) {
909                                 map->pagesneeded++;
910                         }
911                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
912
913                 }
914                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
915         }
916 }
917
918 static int
919 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
920 {
921
922         /* Reserve Necessary Bounce Pages */
923         mtx_lock(&bounce_lock);
924         if (flags & BUS_DMA_NOWAIT) {
925                 if (reserve_bounce_pages(dmat, map, 0) != 0) {
926                         map->pagesneeded = 0;
927                         mtx_unlock(&bounce_lock);
928                         return (ENOMEM);
929                 }
930         } else {
931                 if (reserve_bounce_pages(dmat, map, 1) != 0) {
932                         /* Queue us for resources */
933                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
934                         mtx_unlock(&bounce_lock);
935                         return (EINPROGRESS);
936                 }
937         }
938         mtx_unlock(&bounce_lock);
939
940         return (0);
941 }
942
943 /*
944  * Add a single contiguous physical range to the segment list.
945  */
946 static int
947 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
948     bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
949 {
950         bus_addr_t baddr, bmask;
951         int seg;
952
953         /*
954          * Make sure we don't cross any boundaries.
955          */
956         bmask = ~(dmat->boundary - 1);
957         if (dmat->boundary > 0) {
958                 baddr = (curaddr + dmat->boundary) & bmask;
959                 if (sgsize > (baddr - curaddr))
960                         sgsize = (baddr - curaddr);
961         }
962
963         /*
964          * Insert chunk into a segment, coalescing with
965          * previous segment if possible.
966          */
967         seg = *segp;
968         if (seg == -1) {
969                 seg = 0;
970                 segs[seg].ds_addr = curaddr;
971                 segs[seg].ds_len = sgsize;
972         } else {
973                 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
974                     (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
975                     (dmat->boundary == 0 ||
976                     (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
977                         segs[seg].ds_len += sgsize;
978                 else {
979                         if (++seg >= dmat->nsegments)
980                                 return (0);
981                         segs[seg].ds_addr = curaddr;
982                         segs[seg].ds_len = sgsize;
983                 }
984         }
985         *segp = seg;
986         return (sgsize);
987 }
988
989 /*
990  * Utility function to load a physical buffer.  segp contains
991  * the starting segment on entrace, and the ending segment on exit.
992  */
993 int
994 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
995     bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
996 {
997         bus_addr_t curaddr;
998         bus_addr_t sl_end = 0;
999         bus_size_t sgsize;
1000         struct sync_list *sl;
1001         int error;
1002
1003         if (segs == NULL)
1004                 segs = map->segments;
1005
1006         counter_u64_add(maploads_total, 1);
1007         counter_u64_add(maploads_physmem, 1);
1008
1009         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1010                 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1011                 if (map->pagesneeded != 0) {
1012                         counter_u64_add(maploads_bounced, 1);
1013                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1014                         if (error)
1015                                 return (error);
1016                 }
1017         }
1018
1019         sl = map->slist + map->sync_count - 1;
1020
1021         while (buflen > 0) {
1022                 curaddr = buf;
1023                 sgsize = MIN(buflen, dmat->maxsegsz);
1024                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1025                     sgsize)) {
1026                         sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1027                         curaddr = add_bounce_page(dmat, map, 0, curaddr,
1028                             sgsize);
1029                 } else {
1030                         if (map->sync_count > 0)
1031                                 sl_end = sl->paddr + sl->datacount;
1032
1033                         if (map->sync_count == 0 || curaddr != sl_end) {
1034                                 if (++map->sync_count > dmat->nsegments)
1035                                         break;
1036                                 sl++;
1037                                 sl->vaddr = 0;
1038                                 sl->paddr = curaddr;
1039                                 sl->datacount = sgsize;
1040                                 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1041                                 KASSERT(sl->pages != NULL,
1042                                     ("%s: page at PA:0x%08lx is not in "
1043                                     "vm_page_array", __func__, curaddr));
1044                         } else
1045                                 sl->datacount += sgsize;
1046                 }
1047                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1048                     segp);
1049                 if (sgsize == 0)
1050                         break;
1051                 buf += sgsize;
1052                 buflen -= sgsize;
1053         }
1054
1055         /*
1056          * Did we fit?
1057          */
1058         if (buflen != 0) {
1059                 _bus_dmamap_unload(dmat, map);
1060                 return (EFBIG); /* XXX better return value here? */
1061         }
1062         return (0);
1063 }
1064
1065 int
1066 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1067     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1068     bus_dma_segment_t *segs, int *segp)
1069 {
1070
1071         return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1072             segs, segp));
1073 }
1074
1075 /*
1076  * Utility function to load a linear buffer.  segp contains
1077  * the starting segment on entrance, and the ending segment on exit.
1078  */
1079 int
1080 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1081     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1082     int *segp)
1083 {
1084         bus_size_t sgsize;
1085         bus_addr_t curaddr;
1086         bus_addr_t sl_pend = 0;
1087         vm_offset_t kvaddr, vaddr, sl_vend = 0;
1088         struct sync_list *sl;
1089         int error;
1090
1091         counter_u64_add(maploads_total, 1);
1092         if (map->flags & DMAMAP_COHERENT)
1093                 counter_u64_add(maploads_coherent, 1);
1094         if (map->flags & DMAMAP_DMAMEM_ALLOC)
1095                 counter_u64_add(maploads_dmamem, 1);
1096
1097         if (segs == NULL)
1098                 segs = map->segments;
1099
1100         if (flags & BUS_DMA_LOAD_MBUF) {
1101                 counter_u64_add(maploads_mbuf, 1);
1102                 map->flags |= DMAMAP_MBUF;
1103         }
1104
1105         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1106                 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1107                 if (map->pagesneeded != 0) {
1108                         counter_u64_add(maploads_bounced, 1);
1109                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1110                         if (error)
1111                                 return (error);
1112                 }
1113         }
1114
1115         sl = map->slist + map->sync_count - 1;
1116         vaddr = (vm_offset_t)buf;
1117
1118         while (buflen > 0) {
1119                 /*
1120                  * Get the physical address for this segment.
1121                  */
1122                 if (__predict_true(pmap == kernel_pmap)) {
1123                         curaddr = pmap_kextract(vaddr);
1124                         kvaddr = vaddr;
1125                 } else {
1126                         curaddr = pmap_extract(pmap, vaddr);
1127                         kvaddr = 0;
1128                 }
1129
1130                 /*
1131                  * Compute the segment size, and adjust counts.
1132                  */
1133                 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1134                 if (sgsize > dmat->maxsegsz)
1135                         sgsize = dmat->maxsegsz;
1136                 if (buflen < sgsize)
1137                         sgsize = buflen;
1138
1139                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1140                     sgsize)) {
1141                         curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1142                             sgsize);
1143                 } else {
1144                         if (map->sync_count > 0) {
1145                                 sl_pend = sl->paddr + sl->datacount;
1146                                 sl_vend = sl->vaddr + sl->datacount;
1147                         }
1148
1149                         if (map->sync_count == 0 ||
1150                             (kvaddr != 0 && kvaddr != sl_vend) ||
1151                             (curaddr != sl_pend)) {
1152
1153                                 if (++map->sync_count > dmat->nsegments)
1154                                         goto cleanup;
1155                                 sl++;
1156                                 sl->vaddr = kvaddr;
1157                                 sl->paddr = curaddr;
1158                                 if (kvaddr != 0) {
1159                                         sl->pages = NULL;
1160                                 } else {
1161                                         sl->pages = PHYS_TO_VM_PAGE(curaddr);
1162                                         KASSERT(sl->pages != NULL,
1163                                             ("%s: page at PA:0x%08lx is not "
1164                                             "in vm_page_array", __func__,
1165                                             curaddr));
1166                                 }
1167                                 sl->datacount = sgsize;
1168                         } else
1169                                 sl->datacount += sgsize;
1170                 }
1171                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1172                     segp);
1173                 if (sgsize == 0)
1174                         break;
1175                 vaddr += sgsize;
1176                 buflen -= sgsize;
1177         }
1178
1179 cleanup:
1180         /*
1181          * Did we fit?
1182          */
1183         if (buflen != 0) {
1184                 _bus_dmamap_unload(dmat, map);
1185                 return (EFBIG); /* XXX better return value here? */
1186         }
1187         return (0);
1188 }
1189
1190 void
1191 __bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1192     bus_dmamap_callback_t *callback, void *callback_arg)
1193 {
1194
1195         map->mem = *mem;
1196         map->dmat = dmat;
1197         map->callback = callback;
1198         map->callback_arg = callback_arg;
1199 }
1200
1201 bus_dma_segment_t *
1202 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1203     bus_dma_segment_t *segs, int nsegs, int error)
1204 {
1205
1206         if (segs == NULL)
1207                 segs = map->segments;
1208         return (segs);
1209 }
1210
1211 /*
1212  * Release the mapping held by map.
1213  */
1214 void
1215 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1216 {
1217         struct bounce_page *bpage;
1218         struct bounce_zone *bz;
1219
1220         if ((bz = dmat->bounce_zone) != NULL) {
1221                 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1222                         STAILQ_REMOVE_HEAD(&map->bpages, links);
1223                         free_bounce_page(dmat, bpage);
1224                 }
1225
1226                 bz = dmat->bounce_zone;
1227                 bz->free_bpages += map->pagesreserved;
1228                 bz->reserved_bpages -= map->pagesreserved;
1229                 map->pagesreserved = 0;
1230                 map->pagesneeded = 0;
1231         }
1232         map->sync_count = 0;
1233         map->flags &= ~DMAMAP_MBUF;
1234 }
1235
1236 static void
1237 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1238 {
1239         /*
1240          * Write back any partial cachelines immediately before and
1241          * after the DMA region.  We don't need to round the address
1242          * down to the nearest cacheline or specify the exact size,
1243          * as dcache_wb_poc() will do the rounding for us and works
1244          * at cacheline granularity.
1245          */
1246         if (va & BUSDMA_DCACHE_MASK)
1247                 dcache_wb_poc(va, pa, 1);
1248         if ((va + size) & BUSDMA_DCACHE_MASK)
1249                 dcache_wb_poc(va + size, pa + size, 1);
1250
1251         dcache_inv_poc_dma(va, pa, size);
1252 }
1253
1254 static void
1255 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1256 {
1257         uint32_t len, offset;
1258         vm_page_t m;
1259         vm_paddr_t pa;
1260         vm_offset_t va, tempva;
1261         bus_size_t size;
1262
1263         offset = sl->paddr & PAGE_MASK;
1264         m = sl->pages;
1265         size = sl->datacount;
1266         pa = sl->paddr;
1267
1268         for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1269                 tempva = 0;
1270                 if (sl->vaddr == 0) {
1271                         len = min(PAGE_SIZE - offset, size);
1272                         tempva = pmap_quick_enter_page(m);
1273                         va = tempva | offset;
1274                         KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1275                             ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1276                             VM_PAGE_TO_PHYS(m) | offset, pa));
1277                 } else {
1278                         len = sl->datacount;
1279                         va = sl->vaddr;
1280                 }
1281
1282                 switch (op) {
1283                 case BUS_DMASYNC_PREWRITE:
1284                 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1285                         dcache_wb_poc(va, pa, len);
1286                         break;
1287                 case BUS_DMASYNC_PREREAD:
1288                         /*
1289                          * An mbuf may start in the middle of a cacheline. There
1290                          * will be no cpu writes to the beginning of that line
1291                          * (which contains the mbuf header) while dma is in
1292                          * progress.  Handle that case by doing a writeback of
1293                          * just the first cacheline before invalidating the
1294                          * overall buffer.  Any mbuf in a chain may have this
1295                          * misalignment.  Buffers which are not mbufs bounce if
1296                          * they are not aligned to a cacheline.
1297                          */
1298                         dma_preread_safe(va, pa, len);
1299                         break;
1300                 case BUS_DMASYNC_POSTREAD:
1301                 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1302                         dcache_inv_poc(va, pa, len);
1303                         break;
1304                 default:
1305                         panic("unsupported combination of sync operations: "
1306                               "0x%08x\n", op);
1307                 }
1308
1309                 if (tempva != 0)
1310                         pmap_quick_remove_page(tempva);
1311         }
1312 }
1313
1314 void
1315 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1316 {
1317         struct bounce_page *bpage;
1318         struct sync_list *sl, *end;
1319         vm_offset_t datavaddr, tempvaddr;
1320
1321         if (op == BUS_DMASYNC_POSTWRITE)
1322                 return;
1323
1324         /*
1325          * If the buffer was from user space, it is possible that this is not
1326          * the same vm map, especially on a POST operation.  It's not clear that
1327          * dma on userland buffers can work at all right now.  To be safe, until
1328          * we're able to test direct userland dma, panic on a map mismatch.
1329          */
1330         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1331
1332                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1333                     "performing bounce", __func__, dmat, dmat->flags, op);
1334
1335                 /*
1336                  * For PREWRITE do a writeback.  Clean the caches from the
1337                  * innermost to the outermost levels.
1338                  */
1339                 if (op & BUS_DMASYNC_PREWRITE) {
1340                         while (bpage != NULL) {
1341                                 tempvaddr = 0;
1342                                 datavaddr = bpage->datavaddr;
1343                                 if (datavaddr == 0) {
1344                                         tempvaddr = pmap_quick_enter_page(
1345                                             bpage->datapage);
1346                                         datavaddr = tempvaddr | bpage->dataoffs;
1347                                 }
1348                                 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1349                                     bpage->datacount);
1350                                 if (tempvaddr != 0)
1351                                         pmap_quick_remove_page(tempvaddr);
1352                                 dcache_wb_poc(bpage->vaddr, bpage->busaddr,
1353                                     bpage->datacount);
1354                                 bpage = STAILQ_NEXT(bpage, links);
1355                         }
1356                         dmat->bounce_zone->total_bounced++;
1357                 }
1358
1359                 /*
1360                  * Do an invalidate for PREREAD unless a writeback was already
1361                  * done above due to PREWRITE also being set.  The reason for a
1362                  * PREREAD invalidate is to prevent dirty lines currently in the
1363                  * cache from being evicted during the DMA.  If a writeback was
1364                  * done due to PREWRITE also being set there will be no dirty
1365                  * lines and the POSTREAD invalidate handles the rest. The
1366                  * invalidate is done from the innermost to outermost level. If
1367                  * L2 were done first, a dirty cacheline could be automatically
1368                  * evicted from L1 before we invalidated it, re-dirtying the L2.
1369                  */
1370                 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1371                         bpage = STAILQ_FIRST(&map->bpages);
1372                         while (bpage != NULL) {
1373                                 dcache_inv_poc_dma(bpage->vaddr, bpage->busaddr,
1374                                     bpage->datacount);
1375                                 bpage = STAILQ_NEXT(bpage, links);
1376                         }
1377                 }
1378
1379                 /*
1380                  * Re-invalidate the caches on a POSTREAD, even though they were
1381                  * already invalidated at PREREAD time.  Aggressive prefetching
1382                  * due to accesses to other data near the dma buffer could have
1383                  * brought buffer data into the caches which is now stale.  The
1384                  * caches are invalidated from the outermost to innermost; the
1385                  * prefetches could be happening right now, and if L1 were
1386                  * invalidated first, stale L2 data could be prefetched into L1.
1387                  */
1388                 if (op & BUS_DMASYNC_POSTREAD) {
1389                         while (bpage != NULL) {
1390                                 dcache_inv_poc(bpage->vaddr, bpage->busaddr,
1391                                     bpage->datacount);
1392                                 tempvaddr = 0;
1393                                 datavaddr = bpage->datavaddr;
1394                                 if (datavaddr == 0) {
1395                                         tempvaddr = pmap_quick_enter_page(
1396                                             bpage->datapage);
1397                                         datavaddr = tempvaddr | bpage->dataoffs;
1398                                 }
1399                                 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1400                                     bpage->datacount);
1401                                 if (tempvaddr != 0)
1402                                         pmap_quick_remove_page(tempvaddr);
1403                                 bpage = STAILQ_NEXT(bpage, links);
1404                         }
1405                         dmat->bounce_zone->total_bounced++;
1406                 }
1407         }
1408
1409         /*
1410          * For COHERENT memory no cache maintenance is necessary, but ensure all
1411          * writes have reached memory for the PREWRITE case.  No action is
1412          * needed for a PREREAD without PREWRITE also set, because that would
1413          * imply that the cpu had written to the COHERENT buffer and expected
1414          * the dma device to see that change, and by definition a PREWRITE sync
1415          * is required to make that happen.
1416          */
1417         if (map->flags & DMAMAP_COHERENT) {
1418                 if (op & BUS_DMASYNC_PREWRITE) {
1419                         dsb();
1420                         cpu_l2cache_drain_writebuf();
1421                 }
1422                 return;
1423         }
1424
1425         /*
1426          * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1427          * the comments about the sequences for flushing cache levels in the
1428          * bounce buffer code above apply here as well.  In particular, the fact
1429          * that the sequence is inner-to-outer for PREREAD invalidation and
1430          * outer-to-inner for POSTREAD invalidation is not a mistake.
1431          */
1432         if (map->sync_count != 0) {
1433                 sl = &map->slist[0];
1434                 end = &map->slist[map->sync_count];
1435                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1436                     "performing sync", __func__, dmat, dmat->flags, op);
1437
1438                 for ( ; sl != end; ++sl)
1439                         dma_dcache_sync(sl, op);
1440         }
1441 }
1442
1443 static void
1444 init_bounce_pages(void *dummy __unused)
1445 {
1446
1447         total_bpages = 0;
1448         STAILQ_INIT(&bounce_zone_list);
1449         STAILQ_INIT(&bounce_map_waitinglist);
1450         STAILQ_INIT(&bounce_map_callbacklist);
1451         mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1452 }
1453 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1454
1455 static struct sysctl_ctx_list *
1456 busdma_sysctl_tree(struct bounce_zone *bz)
1457 {
1458
1459         return (&bz->sysctl_tree);
1460 }
1461
1462 static struct sysctl_oid *
1463 busdma_sysctl_tree_top(struct bounce_zone *bz)
1464 {
1465
1466         return (bz->sysctl_tree_top);
1467 }
1468
1469 static int
1470 alloc_bounce_zone(bus_dma_tag_t dmat)
1471 {
1472         struct bounce_zone *bz;
1473
1474         /* Check to see if we already have a suitable zone */
1475         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1476                 if ((dmat->alignment <= bz->alignment) &&
1477                     (dmat->lowaddr >= bz->lowaddr)) {
1478                         dmat->bounce_zone = bz;
1479                         return (0);
1480                 }
1481         }
1482
1483         if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1484             M_NOWAIT | M_ZERO)) == NULL)
1485                 return (ENOMEM);
1486
1487         STAILQ_INIT(&bz->bounce_page_list);
1488         bz->free_bpages = 0;
1489         bz->reserved_bpages = 0;
1490         bz->active_bpages = 0;
1491         bz->lowaddr = dmat->lowaddr;
1492         bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1493         bz->map_count = 0;
1494         snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1495         busdma_zonecount++;
1496         snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1497         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1498         dmat->bounce_zone = bz;
1499
1500         sysctl_ctx_init(&bz->sysctl_tree);
1501         bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1502             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1503             CTLFLAG_RD, 0, "");
1504         if (bz->sysctl_tree_top == NULL) {
1505                 sysctl_ctx_free(&bz->sysctl_tree);
1506                 return (0);     /* XXX error code? */
1507         }
1508
1509         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1510             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1511             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1512             "Total bounce pages");
1513         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1514             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1515             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1516             "Free bounce pages");
1517         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1518             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1519             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1520             "Reserved bounce pages");
1521         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1522             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1523             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1524             "Active bounce pages");
1525         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1526             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1527             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1528             "Total bounce requests (pages bounced)");
1529         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1530             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1531             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1532             "Total bounce requests that were deferred");
1533         SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1534             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1535             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1536         SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1537             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1538             "alignment", CTLFLAG_RD, &bz->alignment, "");
1539
1540         return (0);
1541 }
1542
1543 static int
1544 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1545 {
1546         struct bounce_zone *bz;
1547         int count;
1548
1549         bz = dmat->bounce_zone;
1550         count = 0;
1551         while (numpages > 0) {
1552                 struct bounce_page *bpage;
1553
1554                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1555                     M_NOWAIT | M_ZERO);
1556
1557                 if (bpage == NULL)
1558                         break;
1559                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1560                     M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1561                 if (bpage->vaddr == 0) {
1562                         free(bpage, M_BUSDMA);
1563                         break;
1564                 }
1565                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1566                 mtx_lock(&bounce_lock);
1567                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1568                 total_bpages++;
1569                 bz->total_bpages++;
1570                 bz->free_bpages++;
1571                 mtx_unlock(&bounce_lock);
1572                 count++;
1573                 numpages--;
1574         }
1575         return (count);
1576 }
1577
1578 static int
1579 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1580 {
1581         struct bounce_zone *bz;
1582         int pages;
1583
1584         mtx_assert(&bounce_lock, MA_OWNED);
1585         bz = dmat->bounce_zone;
1586         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1587         if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1588                 return (map->pagesneeded - (map->pagesreserved + pages));
1589         bz->free_bpages -= pages;
1590         bz->reserved_bpages += pages;
1591         map->pagesreserved += pages;
1592         pages = map->pagesneeded - map->pagesreserved;
1593
1594         return (pages);
1595 }
1596
1597 static bus_addr_t
1598 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1599     bus_addr_t addr, bus_size_t size)
1600 {
1601         struct bounce_zone *bz;
1602         struct bounce_page *bpage;
1603
1604         KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1605         KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1606
1607         bz = dmat->bounce_zone;
1608         if (map->pagesneeded == 0)
1609                 panic("add_bounce_page: map doesn't need any pages");
1610         map->pagesneeded--;
1611
1612         if (map->pagesreserved == 0)
1613                 panic("add_bounce_page: map doesn't need any pages");
1614         map->pagesreserved--;
1615
1616         mtx_lock(&bounce_lock);
1617         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1618         if (bpage == NULL)
1619                 panic("add_bounce_page: free page list is empty");
1620
1621         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1622         bz->reserved_bpages--;
1623         bz->active_bpages++;
1624         mtx_unlock(&bounce_lock);
1625
1626         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1627                 /* Page offset needs to be preserved. */
1628                 bpage->vaddr |= addr & PAGE_MASK;
1629                 bpage->busaddr |= addr & PAGE_MASK;
1630         }
1631         bpage->datavaddr = vaddr;
1632         bpage->datapage = PHYS_TO_VM_PAGE(addr);
1633         bpage->dataoffs = addr & PAGE_MASK;
1634         bpage->datacount = size;
1635         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1636         return (bpage->busaddr);
1637 }
1638
1639 static void
1640 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1641 {
1642         struct bus_dmamap *map;
1643         struct bounce_zone *bz;
1644
1645         bz = dmat->bounce_zone;
1646         bpage->datavaddr = 0;
1647         bpage->datacount = 0;
1648         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1649                 /*
1650                  * Reset the bounce page to start at offset 0.  Other uses
1651                  * of this bounce page may need to store a full page of
1652                  * data and/or assume it starts on a page boundary.
1653                  */
1654                 bpage->vaddr &= ~PAGE_MASK;
1655                 bpage->busaddr &= ~PAGE_MASK;
1656         }
1657
1658         mtx_lock(&bounce_lock);
1659         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1660         bz->free_bpages++;
1661         bz->active_bpages--;
1662         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1663                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1664                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1665                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1666                             map, links);
1667                         busdma_swi_pending = 1;
1668                         bz->total_deferred++;
1669                         swi_sched(vm_ih, 0);
1670                 }
1671         }
1672         mtx_unlock(&bounce_lock);
1673 }
1674
1675 void
1676 busdma_swi(void)
1677 {
1678         bus_dma_tag_t dmat;
1679         struct bus_dmamap *map;
1680
1681         mtx_lock(&bounce_lock);
1682         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1683                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1684                 mtx_unlock(&bounce_lock);
1685                 dmat = map->dmat;
1686                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1687                 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1688                     map->callback_arg, BUS_DMA_WAITOK);
1689                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1690                 mtx_lock(&bounce_lock);
1691         }
1692         mtx_unlock(&bounce_lock);
1693 }