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