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