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