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