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