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