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