]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/mips/mips/busdma_machdep.c
MFV r333789: libpcap 1.9.0 (pre-release)
[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_set_domain(bus_dma_tag_t dmat, int domain)
485 {
486
487         return (0);
488 }
489
490 int
491 bus_dma_tag_destroy(bus_dma_tag_t dmat)
492 {
493 #ifdef KTR
494         bus_dma_tag_t dmat_copy = dmat;
495 #endif
496
497         if (dmat != NULL) {
498                 if (dmat->map_count != 0)
499                         return (EBUSY);
500
501                 while (dmat != NULL) {
502                         bus_dma_tag_t parent;
503
504                         parent = dmat->parent;
505                         atomic_subtract_int(&dmat->ref_count, 1);
506                         if (dmat->ref_count == 0) {
507                                 if (dmat->segments != NULL)
508                                         free(dmat->segments, M_BUSDMA);
509                                 free(dmat, M_BUSDMA);
510                                 /*
511                                  * Last reference count, so
512                                  * release our reference
513                                  * count on our parent.
514                                  */
515                                 dmat = parent;
516                         } else
517                                 dmat = NULL;
518                 }
519         }
520         CTR2(KTR_BUSDMA, "%s tag %p", __func__, dmat_copy);
521
522         return (0);
523 }
524
525 #include <sys/kdb.h>
526 /*
527  * Allocate a handle for mapping from kva/uva/physical
528  * address space into bus device space.
529  */
530 int
531 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
532 {
533         bus_dmamap_t newmap;
534         int error = 0;
535
536         if (dmat->segments == NULL) {
537                 dmat->segments = (bus_dma_segment_t *)malloc(
538                     sizeof(bus_dma_segment_t) * dmat->nsegments, M_BUSDMA,
539                     M_NOWAIT);
540                 if (dmat->segments == NULL) {
541                         CTR3(KTR_BUSDMA, "%s: tag %p error %d",
542                             __func__, dmat, ENOMEM);
543                         return (ENOMEM);
544                 }
545         }
546
547         newmap = _busdma_alloc_dmamap(dmat);
548         if (newmap == NULL) {
549                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
550                 return (ENOMEM);
551         }
552         *mapp = newmap;
553
554         /*
555          * Bouncing might be required if the driver asks for an active
556          * exclusion region, a data alignment that is stricter than 1, and/or
557          * an active address boundary.
558          */
559         if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
560
561                 /* Must bounce */
562                 struct bounce_zone *bz;
563                 int maxpages;
564
565                 if (dmat->bounce_zone == NULL) {
566                         if ((error = alloc_bounce_zone(dmat)) != 0) {
567                                 _busdma_free_dmamap(newmap);
568                                 *mapp = NULL;
569                                 return (error);
570                         }
571                 }
572                 bz = dmat->bounce_zone;
573
574                 /* Initialize the new map */
575                 STAILQ_INIT(&((*mapp)->bpages));
576
577                 /*
578                  * Attempt to add pages to our pool on a per-instance
579                  * basis up to a sane limit.
580                  */
581                 maxpages = MAX_BPAGES;
582                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
583                  || (bz->map_count > 0 && bz->total_bpages < maxpages)) {
584                         int pages;
585
586                         pages = MAX(atop(dmat->maxsize), 1);
587                         pages = MIN(maxpages - bz->total_bpages, pages);
588                         pages = MAX(pages, 1);
589                         if (alloc_bounce_pages(dmat, pages) < pages)
590                                 error = ENOMEM;
591
592                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
593                                 if (error == 0)
594                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
595                         } else {
596                                 error = 0;
597                         }
598                 }
599                 bz->map_count++;
600         }
601
602         CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
603             __func__, dmat, dmat->flags, error);
604
605         return (0);
606 }
607
608 /*
609  * Destroy a handle for mapping from kva/uva/physical
610  * address space into bus device space.
611  */
612 int
613 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
614 {
615
616         if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
617                 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
618                     __func__, dmat, EBUSY);
619                 return (EBUSY);
620         }
621         if (dmat->bounce_zone)
622                 dmat->bounce_zone->map_count--;
623         _busdma_free_dmamap(map);
624         CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
625         return (0);
626 }
627
628 /*
629  * Allocate a piece of memory that can be efficiently mapped into
630  * bus device space based on the constraints lited in the dma tag.
631  * A dmamap to for use with dmamap_load is also allocated.
632  */
633 int
634 bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddrp, int flags,
635     bus_dmamap_t *mapp)
636 {
637         bus_dmamap_t newmap = NULL;
638         busdma_bufalloc_t ba;
639         struct busdma_bufzone *bufzone;
640         vm_memattr_t memattr;
641         void *vaddr;
642
643         int mflags;
644
645         if (flags & BUS_DMA_NOWAIT)
646                 mflags = M_NOWAIT;
647         else
648                 mflags = M_WAITOK;
649         if (dmat->segments == NULL) {
650                 dmat->segments = (bus_dma_segment_t *)malloc(
651                     sizeof(bus_dma_segment_t) * dmat->nsegments, M_BUSDMA,
652                     mflags);
653                 if (dmat->segments == NULL) {
654                         CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
655                             __func__, dmat, dmat->flags, ENOMEM);
656                         return (ENOMEM);
657                 }
658         }
659
660         newmap = _busdma_alloc_dmamap(dmat);
661         if (newmap == NULL) {
662                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
663                     __func__, dmat, dmat->flags, ENOMEM);
664                 return (ENOMEM);
665         }
666
667         /*
668          * If all the memory is coherent with DMA then we don't need to
669          * do anything special for a coherent mapping request.
670          */
671         if (dmat->flags & BUS_DMA_COHERENT)
672             flags &= ~BUS_DMA_COHERENT;
673
674         if (flags & BUS_DMA_COHERENT) {
675                 memattr = VM_MEMATTR_UNCACHEABLE;
676                 ba = coherent_allocator;
677                 newmap->flags |= DMAMAP_UNCACHEABLE;
678         } else {
679                 memattr = VM_MEMATTR_DEFAULT;
680                 ba = standard_allocator;
681         }
682         /* All buffers we allocate are cache-aligned. */
683         newmap->flags |= DMAMAP_CACHE_ALIGNED;
684
685         if (flags & BUS_DMA_ZERO)
686                 mflags |= M_ZERO;
687
688         /*
689          * Try to find a bufzone in the allocator that holds a cache of buffers
690          * of the right size for this request.  If the buffer is too big to be
691          * held in the allocator cache, this returns NULL.
692          */
693         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
694
695         /*
696          * Allocate the buffer from the uma(9) allocator if...
697          *  - It's small enough to be in the allocator (bufzone not NULL).
698          *  - The alignment constraint isn't larger than the allocation size
699          *    (the allocator aligns buffers to their size boundaries).
700          *  - There's no need to handle lowaddr/highaddr exclusion zones.
701          * else allocate non-contiguous pages if...
702          *  - The page count that could get allocated doesn't exceed
703          *    nsegments also when the maximum segment size is less
704          *    than PAGE_SIZE.
705          *  - The alignment constraint isn't larger than a page boundary.
706          *  - There are no boundary-crossing constraints.
707          * else allocate a block of contiguous pages because one or more of the
708          * constraints is something that only the contig allocator can fulfill.
709          */
710         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
711             !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr)) {
712                 vaddr = uma_zalloc(bufzone->umazone, mflags);
713         } else if (dmat->nsegments >=
714             howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
715             dmat->alignment <= PAGE_SIZE &&
716             (dmat->boundary % PAGE_SIZE) == 0) {
717                 vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
718                     mflags, 0, dmat->lowaddr, memattr);
719         } else {
720                 vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
721                     mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
722                     memattr);
723         }
724         if (vaddr == NULL) {
725                 _busdma_free_dmamap(newmap);
726                 newmap = NULL;
727         } else {
728                 newmap->sync_count = 0;
729         }
730         *vaddrp = vaddr;
731         *mapp = newmap;
732
733         return (vaddr == NULL ? ENOMEM : 0);
734 }
735
736 /*
737  * Free a piece of memory and it's allocated dmamap, that was allocated
738  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
739  */
740 void
741 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
742 {
743         struct busdma_bufzone *bufzone;
744         busdma_bufalloc_t ba;
745
746         if (map->flags & DMAMAP_UNCACHEABLE)
747                 ba = coherent_allocator;
748         else
749                 ba = standard_allocator;
750
751         free(map->slist, M_BUSDMA);
752         uma_zfree(dmamap_zone, map);
753
754         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
755
756         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
757             !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr))
758                 uma_zfree(bufzone->umazone, vaddr);
759         else
760                 kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
761         CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
762 }
763
764 static void
765 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
766     bus_size_t buflen, int flags)
767 {
768         bus_addr_t curaddr;
769         bus_size_t sgsize;
770
771         if (map->pagesneeded == 0) {
772                 CTR3(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d",
773                     dmat->lowaddr, dmat->boundary, dmat->alignment);
774                 CTR2(KTR_BUSDMA, "map= %p, pagesneeded= %d",
775                     map, map->pagesneeded);
776                 /*
777                  * Count the number of bounce pages
778                  * needed in order to complete this transfer
779                  */
780                 curaddr = buf;
781                 while (buflen != 0) {
782                         sgsize = MIN(buflen, dmat->maxsegsz);
783                         if (run_filter(dmat, curaddr) != 0) {
784                                 sgsize = MIN(sgsize, PAGE_SIZE);
785                                 map->pagesneeded++;
786                         }
787                         curaddr += sgsize;
788                         buflen -= sgsize;
789                 }
790                 CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
791         }
792 }
793
794 static void
795 _bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map, pmap_t pmap,
796     void *buf, bus_size_t buflen, int flags)
797 {
798         vm_offset_t vaddr;
799         vm_offset_t vendaddr;
800         bus_addr_t paddr;
801
802         if (map->pagesneeded == 0) {
803                 CTR3(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d",
804                     dmat->lowaddr, dmat->boundary, dmat->alignment);
805                 CTR2(KTR_BUSDMA, "map= %p, pagesneeded= %d",
806                     map, map->pagesneeded);
807                 /*
808                  * Count the number of bounce pages
809                  * needed in order to complete this transfer
810                  */
811                 vaddr = (vm_offset_t)buf;
812                 vendaddr = (vm_offset_t)buf + buflen;
813
814                 while (vaddr < vendaddr) {
815                         bus_size_t sg_len;
816
817                         KASSERT(kernel_pmap == pmap, ("pmap is not kernel pmap"));
818                         sg_len = PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK);
819                         paddr = pmap_kextract(vaddr);
820                         if (((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
821                             run_filter(dmat, paddr) != 0) {
822                                 sg_len = roundup2(sg_len, dmat->alignment);
823                                 map->pagesneeded++;
824                         }
825                         vaddr += sg_len;
826                 }
827                 CTR1(KTR_BUSDMA, "pagesneeded= %d\n", map->pagesneeded);
828         }
829 }
830
831 static int
832 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,int flags)
833 {
834
835         /* Reserve Necessary Bounce Pages */
836         mtx_lock(&bounce_lock);
837         if (flags & BUS_DMA_NOWAIT) {
838                 if (reserve_bounce_pages(dmat, map, 0) != 0) {
839                         mtx_unlock(&bounce_lock);
840                         return (ENOMEM);
841                 }
842         } else {
843                 if (reserve_bounce_pages(dmat, map, 1) != 0) {
844                         /* Queue us for resources */
845                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist,
846                             map, links);
847                         mtx_unlock(&bounce_lock);
848                         return (EINPROGRESS);
849                 }
850         }
851         mtx_unlock(&bounce_lock);
852
853         return (0);
854 }
855
856 /*
857  * Add a single contiguous physical range to the segment list.
858  */
859 static int
860 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
861     bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
862 {
863         bus_addr_t baddr, bmask;
864         int seg;
865
866         /*
867          * Make sure we don't cross any boundaries.
868          */
869         bmask = ~(dmat->boundary - 1);
870         if (dmat->boundary > 0) {
871                 baddr = (curaddr + dmat->boundary) & bmask;
872                 if (sgsize > (baddr - curaddr))
873                         sgsize = (baddr - curaddr);
874         }
875         /*
876          * Insert chunk into a segment, coalescing with
877          * the previous segment if possible.
878          */
879         seg = *segp;
880         if (seg >= 0 &&
881             curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
882             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
883             (dmat->boundary == 0 ||
884              (segs[seg].ds_addr & bmask) == (curaddr & bmask))) {
885                 segs[seg].ds_len += sgsize;
886         } else {
887                 if (++seg >= dmat->nsegments)
888                         return (0);
889                 segs[seg].ds_addr = curaddr;
890                 segs[seg].ds_len = sgsize;
891         }
892         *segp = seg;
893         return (sgsize);
894 }
895
896 /*
897  * Utility function to load a physical buffer.  segp contains
898  * the starting segment on entrace, and the ending segment on exit.
899  */
900 int
901 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
902     vm_paddr_t buf, bus_size_t buflen, int flags, bus_dma_segment_t *segs,
903     int *segp)
904 {
905         bus_addr_t curaddr;
906         bus_size_t sgsize;
907         int error;
908
909         if (segs == NULL)
910                 segs = dmat->segments;
911
912         if ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) {
913                 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
914                 if (map->pagesneeded != 0) {
915                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
916                         if (error)
917                                 return (error);
918                 }
919         }
920
921         while (buflen > 0) {
922                 curaddr = buf;
923                 sgsize = MIN(buflen, dmat->maxsegsz);
924                 if (((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
925                     map->pagesneeded != 0 && run_filter(dmat, curaddr)) {
926                         sgsize = MIN(sgsize, PAGE_SIZE);
927                         curaddr = add_bounce_page(dmat, map, 0, curaddr,
928                             sgsize);
929                 }
930                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
931                     segp);
932                 if (sgsize == 0)
933                         break;
934                 buf += sgsize;
935                 buflen -= sgsize;
936         }
937
938         /*
939          * Did we fit?
940          */
941         if (buflen != 0) {
942                 bus_dmamap_unload(dmat, map);
943                 return (EFBIG); /* XXX better return value here? */
944         }
945         return (0);
946 }
947
948 int
949 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
950     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
951     bus_dma_segment_t *segs, int *segp)
952 {
953
954         return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
955             segs, segp));
956 }
957
958 /*
959  * Utility function to load a linear buffer.  segp contains
960  * the starting segment on entrance, and the ending segment on exit.
961  * first indicates if this is the first invocation of this function.
962  */
963 int
964 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
965     bus_size_t buflen, struct pmap *pmap, int flags, bus_dma_segment_t *segs,
966     int *segp)
967 {
968         bus_size_t sgsize;
969         bus_addr_t curaddr;
970         struct sync_list *sl;
971         vm_offset_t vaddr = (vm_offset_t)buf;
972         int error = 0;
973
974
975         if (segs == NULL)
976                 segs = dmat->segments;
977         if ((flags & BUS_DMA_LOAD_MBUF) != 0)
978                 map->flags |= DMAMAP_CACHE_ALIGNED;
979
980         if ((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) {
981                 _bus_dmamap_count_pages(dmat, map, pmap, buf, buflen, flags);
982                 if (map->pagesneeded != 0) {
983                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
984                         if (error)
985                                 return (error);
986                 }
987         }
988         CTR3(KTR_BUSDMA, "lowaddr= %d boundary= %d, "
989             "alignment= %d", dmat->lowaddr, dmat->boundary, dmat->alignment);
990
991         while (buflen > 0) {
992                 /*
993                  * Get the physical address for this segment.
994                  *
995                  * XXX Don't support checking for coherent mappings
996                  * XXX in user address space.
997                  */
998                 KASSERT(kernel_pmap == pmap, ("pmap is not kernel pmap"));
999                 curaddr = pmap_kextract(vaddr);
1000
1001                 /*
1002                  * Compute the segment size, and adjust counts.
1003                  */
1004                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
1005                 if (sgsize > dmat->maxsegsz)
1006                         sgsize = dmat->maxsegsz;
1007                 if (buflen < sgsize)
1008                         sgsize = buflen;
1009
1010                 if (((dmat->flags & BUS_DMA_COULD_BOUNCE) != 0) &&
1011                     map->pagesneeded != 0 && run_filter(dmat, curaddr)) {
1012                         curaddr = add_bounce_page(dmat, map, vaddr, curaddr,
1013                             sgsize);
1014                 } else {
1015                         sl = &map->slist[map->sync_count - 1];
1016                         if (map->sync_count == 0 ||
1017                             vaddr != sl->vaddr + sl->datacount) {
1018                                 if (++map->sync_count > dmat->nsegments)
1019                                         goto cleanup;
1020                                 sl++;
1021                                 sl->vaddr = vaddr;
1022                                 sl->datacount = sgsize;
1023                                 sl->busaddr = curaddr;
1024                         } else
1025                                 sl->datacount += sgsize;
1026                 }
1027                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1028                     segp);
1029                 if (sgsize == 0)
1030                         break;
1031                 vaddr += sgsize;
1032                 buflen -= sgsize;
1033         }
1034
1035 cleanup:
1036         /*
1037          * Did we fit?
1038          */
1039         if (buflen != 0) {
1040                 bus_dmamap_unload(dmat, map);
1041                 error = EFBIG; /* XXX better return value here? */
1042         }
1043         return (error);
1044 }
1045
1046 void
1047 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map,
1048     struct memdesc *mem, bus_dmamap_callback_t *callback, void *callback_arg)
1049 {
1050
1051         KASSERT(dmat != NULL, ("dmatag is NULL"));
1052         KASSERT(map != NULL, ("dmamap is NULL"));
1053         map->mem = *mem;
1054         map->callback = callback;
1055         map->callback_arg = callback_arg;
1056 }
1057
1058 bus_dma_segment_t *
1059 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1060     bus_dma_segment_t *segs, int nsegs, int error)
1061 {
1062
1063         if (segs == NULL)
1064                 segs = dmat->segments;
1065         return (segs);
1066 }
1067
1068 /*
1069  * Release the mapping held by map.
1070  */
1071 void
1072 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1073 {
1074         struct bounce_page *bpage;
1075
1076         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1077                 STAILQ_REMOVE_HEAD(&map->bpages, links);
1078                 free_bounce_page(dmat, bpage);
1079         }
1080         map->sync_count = 0;
1081         return;
1082 }
1083
1084 static void
1085 bus_dmamap_sync_buf(vm_offset_t buf, int len, bus_dmasync_op_t op, int aligned)
1086 {
1087         char tmp_cl[mips_dcache_max_linesize], tmp_clend[mips_dcache_max_linesize];
1088         vm_offset_t buf_cl, buf_clend;
1089         vm_size_t size_cl, size_clend;
1090         int cache_linesize_mask = mips_dcache_max_linesize - 1;
1091
1092         /*
1093          * dcache invalidation operates on cache line aligned addresses
1094          * and could modify areas of memory that share the same cache line
1095          * at the beginning and the ending of the buffer. In order to
1096          * prevent a data loss we save these chunks in temporary buffer
1097          * before invalidation and restore them afer it.
1098          *
1099          * If the aligned flag is set the buffer is either an mbuf or came from
1100          * our allocator caches.  In both cases they are always sized and
1101          * aligned to cacheline boundaries, so we can skip preserving nearby
1102          * data if a transfer appears to overlap cachelines.  An mbuf in
1103          * particular will usually appear to be overlapped because of offsetting
1104          * within the buffer to align the L3 headers, but we know that the bytes
1105          * preceeding that offset are part of the same mbuf memory and are not
1106          * unrelated adjacent data (and a rule of mbuf handling is that the cpu
1107          * is not allowed to touch the mbuf while dma is in progress, including
1108          * header fields).
1109          */
1110         if (aligned) {
1111                 size_cl = 0;
1112                 size_clend = 0;
1113         } else {
1114                 buf_cl = buf & ~cache_linesize_mask;
1115                 size_cl = buf & cache_linesize_mask;
1116                 buf_clend = buf + len;
1117                 size_clend = (mips_dcache_max_linesize -
1118                     (buf_clend & cache_linesize_mask)) & cache_linesize_mask;
1119         }
1120
1121         switch (op) {
1122         case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1123         case BUS_DMASYNC_POSTREAD:
1124
1125                 /*
1126                  * Save buffers that might be modified by invalidation
1127                  */
1128                 if (size_cl)
1129                         memcpy (tmp_cl, (void*)buf_cl, size_cl);
1130                 if (size_clend)
1131                         memcpy (tmp_clend, (void*)buf_clend, size_clend);
1132                 mips_dcache_inv_range(buf, len);
1133                 /*
1134                  * Restore them
1135                  */
1136                 if (size_cl)
1137                         memcpy ((void*)buf_cl, tmp_cl, size_cl);
1138                 if (size_clend)
1139                         memcpy ((void*)buf_clend, tmp_clend, size_clend);
1140                 /*
1141                  * Copies above have brought corresponding memory
1142                  * cache lines back into dirty state. Write them back
1143                  * out and invalidate affected cache lines again if
1144                  * necessary.
1145                  */
1146                 if (size_cl)
1147                         mips_dcache_wbinv_range(buf_cl, size_cl);
1148                 if (size_clend && (size_cl == 0 ||
1149                     buf_clend - buf_cl > mips_dcache_max_linesize))
1150                         mips_dcache_wbinv_range(buf_clend, size_clend);
1151                 break;
1152
1153         case BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE:
1154                 mips_dcache_wbinv_range(buf, len);
1155                 break;
1156
1157         case BUS_DMASYNC_PREREAD:
1158                 /*
1159                  * Save buffers that might be modified by invalidation
1160                  */
1161                 if (size_cl)
1162                         memcpy (tmp_cl, (void *)buf_cl, size_cl);
1163                 if (size_clend)
1164                         memcpy (tmp_clend, (void *)buf_clend, size_clend);
1165                 mips_dcache_inv_range(buf, len);
1166                 /*
1167                  * Restore them
1168                  */
1169                 if (size_cl)
1170                         memcpy ((void *)buf_cl, tmp_cl, size_cl);
1171                 if (size_clend)
1172                         memcpy ((void *)buf_clend, tmp_clend, size_clend);
1173                 /*
1174                  * Copies above have brought corresponding memory
1175                  * cache lines back into dirty state. Write them back
1176                  * out and invalidate affected cache lines again if
1177                  * necessary.
1178                  */
1179                 if (size_cl)
1180                         mips_dcache_wbinv_range(buf_cl, size_cl);
1181                 if (size_clend && (size_cl == 0 ||
1182                     buf_clend - buf_cl > mips_dcache_max_linesize))
1183                         mips_dcache_wbinv_range(buf_clend, size_clend);
1184                 break;
1185
1186         case BUS_DMASYNC_PREWRITE:
1187 #ifdef BUS_DMA_FORCE_WBINV
1188                 mips_dcache_wbinv_range(buf, len);
1189 #else
1190                 mips_dcache_wb_range(buf, len);
1191 #endif
1192                 break;
1193         }
1194 }
1195
1196 static void
1197 _bus_dmamap_sync_bp(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1198 {
1199         struct bounce_page *bpage;
1200
1201         STAILQ_FOREACH(bpage, &map->bpages, links) {
1202                 if (op & BUS_DMASYNC_PREWRITE) {
1203                         if (bpage->datavaddr != 0)
1204                                 bcopy((void *)bpage->datavaddr,
1205                                     (void *)(bpage->vaddr_nocache != 0 ?
1206                                              bpage->vaddr_nocache :
1207                                              bpage->vaddr),
1208                                     bpage->datacount);
1209                         else
1210                                 physcopyout(bpage->dataaddr,
1211                                     (void *)(bpage->vaddr_nocache != 0 ?
1212                                              bpage->vaddr_nocache :
1213                                              bpage->vaddr),
1214                                     bpage->datacount);
1215                         if (bpage->vaddr_nocache == 0) {
1216 #ifdef BUS_DMA_FORCE_WBINV
1217                                 mips_dcache_wbinv_range(bpage->vaddr,
1218                                     bpage->datacount);
1219 #else
1220                                 mips_dcache_wb_range(bpage->vaddr,
1221                                     bpage->datacount);
1222 #endif
1223                         }
1224                         dmat->bounce_zone->total_bounced++;
1225                 }
1226                 if (op & BUS_DMASYNC_POSTREAD) {
1227                         if (bpage->vaddr_nocache == 0) {
1228                                 mips_dcache_inv_range(bpage->vaddr,
1229                                     bpage->datacount);
1230                         }
1231                         if (bpage->datavaddr != 0)
1232                                 bcopy((void *)(bpage->vaddr_nocache != 0 ?
1233                                     bpage->vaddr_nocache : bpage->vaddr),
1234                                     (void *)bpage->datavaddr, bpage->datacount);
1235                         else
1236                                 physcopyin((void *)(bpage->vaddr_nocache != 0 ?
1237                                     bpage->vaddr_nocache : bpage->vaddr),
1238                                     bpage->dataaddr, bpage->datacount);
1239                         dmat->bounce_zone->total_bounced++;
1240                 }
1241         }
1242 }
1243
1244 void
1245 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1246 {
1247         struct sync_list *sl, *end;
1248         int aligned;
1249
1250         if (op == BUS_DMASYNC_POSTWRITE)
1251                 return;
1252         if (STAILQ_FIRST(&map->bpages))
1253                 _bus_dmamap_sync_bp(dmat, map, op);
1254
1255         if ((dmat->flags & BUS_DMA_COHERENT) ||
1256             (map->flags & DMAMAP_UNCACHEABLE)) {
1257                 if (op & BUS_DMASYNC_PREWRITE)
1258                         mips_sync();
1259                 return;
1260         }
1261
1262         aligned = (map->flags & DMAMAP_CACHE_ALIGNED) ? 1 : 0;
1263
1264         CTR3(KTR_BUSDMA, "%s: op %x flags %x", __func__, op, map->flags);
1265         if (map->sync_count) {
1266                 end = &map->slist[map->sync_count];
1267                 for (sl = &map->slist[0]; sl != end; sl++)
1268                         bus_dmamap_sync_buf(sl->vaddr, sl->datacount, op,
1269                             aligned);
1270         }
1271 }
1272
1273 static void
1274 init_bounce_pages(void *dummy __unused)
1275 {
1276
1277         total_bpages = 0;
1278         STAILQ_INIT(&bounce_zone_list);
1279         STAILQ_INIT(&bounce_map_waitinglist);
1280         STAILQ_INIT(&bounce_map_callbacklist);
1281         mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1282 }
1283 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1284
1285 static struct sysctl_ctx_list *
1286 busdma_sysctl_tree(struct bounce_zone *bz)
1287 {
1288         return (&bz->sysctl_tree);
1289 }
1290
1291 static struct sysctl_oid *
1292 busdma_sysctl_tree_top(struct bounce_zone *bz)
1293 {
1294         return (bz->sysctl_tree_top);
1295 }
1296
1297 static int
1298 alloc_bounce_zone(bus_dma_tag_t dmat)
1299 {
1300         struct bounce_zone *bz;
1301
1302         /* Check to see if we already have a suitable zone */
1303         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1304                 if ((dmat->alignment <= bz->alignment)
1305                  && (dmat->lowaddr >= bz->lowaddr)) {
1306                         dmat->bounce_zone = bz;
1307                         return (0);
1308                 }
1309         }
1310
1311         if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1312             M_NOWAIT | M_ZERO)) == NULL)
1313                 return (ENOMEM);
1314
1315         STAILQ_INIT(&bz->bounce_page_list);
1316         bz->free_bpages = 0;
1317         bz->reserved_bpages = 0;
1318         bz->active_bpages = 0;
1319         bz->lowaddr = dmat->lowaddr;
1320         bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1321         bz->map_count = 0;
1322         snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1323         busdma_zonecount++;
1324         snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1325         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1326         dmat->bounce_zone = bz;
1327
1328         sysctl_ctx_init(&bz->sysctl_tree);
1329         bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1330             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1331             CTLFLAG_RD, 0, "");
1332         if (bz->sysctl_tree_top == NULL) {
1333                 sysctl_ctx_free(&bz->sysctl_tree);
1334                 return (0);     /* XXX error code? */
1335         }
1336
1337         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1338             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1339             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1340             "Total bounce pages");
1341         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1342             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1343             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1344             "Free bounce pages");
1345         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1346             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1347             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1348             "Reserved bounce pages");
1349         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1350             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1351             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1352             "Active bounce pages");
1353         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1354             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1355             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1356             "Total bounce requests");
1357         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1358             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1359             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1360             "Total bounce requests that were deferred");
1361         SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1362             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1363             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1364         SYSCTL_ADD_UAUTO(busdma_sysctl_tree(bz),
1365             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1366             "alignment", CTLFLAG_RD, &bz->alignment, "");
1367
1368         return (0);
1369 }
1370
1371 static int
1372 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1373 {
1374         struct bounce_zone *bz;
1375         int count;
1376
1377         bz = dmat->bounce_zone;
1378         count = 0;
1379         while (numpages > 0) {
1380                 struct bounce_page *bpage;
1381
1382                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1383                                                      M_NOWAIT | M_ZERO);
1384
1385                 if (bpage == NULL)
1386                         break;
1387                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1388                                                          M_NOWAIT, 0ul,
1389                                                          bz->lowaddr,
1390                                                          PAGE_SIZE,
1391                                                          0);
1392                 if (bpage->vaddr == 0) {
1393                         free(bpage, M_BUSDMA);
1394                         break;
1395                 }
1396                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1397                 bpage->vaddr_nocache =
1398                     (vm_offset_t)pmap_mapdev(bpage->busaddr, PAGE_SIZE);
1399                 mtx_lock(&bounce_lock);
1400                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1401                 total_bpages++;
1402                 bz->total_bpages++;
1403                 bz->free_bpages++;
1404                 mtx_unlock(&bounce_lock);
1405                 count++;
1406                 numpages--;
1407         }
1408         return (count);
1409 }
1410
1411 static int
1412 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1413 {
1414         struct bounce_zone *bz;
1415         int pages;
1416
1417         mtx_assert(&bounce_lock, MA_OWNED);
1418         bz = dmat->bounce_zone;
1419         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1420         if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1421                 return (map->pagesneeded - (map->pagesreserved + pages));
1422         bz->free_bpages -= pages;
1423         bz->reserved_bpages += pages;
1424         map->pagesreserved += pages;
1425         pages = map->pagesneeded - map->pagesreserved;
1426
1427         return (pages);
1428 }
1429
1430 static bus_addr_t
1431 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1432                 bus_addr_t addr, bus_size_t size)
1433 {
1434         struct bounce_zone *bz;
1435         struct bounce_page *bpage;
1436
1437         KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1438         KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1439
1440         bz = dmat->bounce_zone;
1441         if (map->pagesneeded == 0)
1442                 panic("add_bounce_page: map doesn't need any pages");
1443         map->pagesneeded--;
1444
1445         if (map->pagesreserved == 0)
1446                 panic("add_bounce_page: map doesn't need any pages");
1447         map->pagesreserved--;
1448
1449         mtx_lock(&bounce_lock);
1450         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1451         if (bpage == NULL)
1452                 panic("add_bounce_page: free page list is empty");
1453
1454         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1455         bz->reserved_bpages--;
1456         bz->active_bpages++;
1457         mtx_unlock(&bounce_lock);
1458
1459         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1460                 /* Page offset needs to be preserved. */
1461                 bpage->vaddr |= addr & PAGE_MASK;
1462                 bpage->busaddr |= addr & PAGE_MASK;
1463         }
1464         bpage->datavaddr = vaddr;
1465         bpage->dataaddr = addr;
1466         bpage->datacount = size;
1467         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1468         return (bpage->busaddr);
1469 }
1470
1471 static void
1472 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1473 {
1474         struct bus_dmamap *map;
1475         struct bounce_zone *bz;
1476
1477         bz = dmat->bounce_zone;
1478         bpage->datavaddr = 0;
1479         bpage->datacount = 0;
1480         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1481                 /*
1482                  * Reset the bounce page to start at offset 0.  Other uses
1483                  * of this bounce page may need to store a full page of
1484                  * data and/or assume it starts on a page boundary.
1485                  */
1486                 bpage->vaddr &= ~PAGE_MASK;
1487                 bpage->busaddr &= ~PAGE_MASK;
1488         }
1489
1490         mtx_lock(&bounce_lock);
1491         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1492         bz->free_bpages++;
1493         bz->active_bpages--;
1494         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1495                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1496                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1497                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1498                                            map, links);
1499                         busdma_swi_pending = 1;
1500                         bz->total_deferred++;
1501                         swi_sched(vm_ih, 0);
1502                 }
1503         }
1504         mtx_unlock(&bounce_lock);
1505 }
1506
1507 void
1508 busdma_swi(void)
1509 {
1510         bus_dma_tag_t dmat;
1511         struct bus_dmamap *map;
1512
1513         mtx_lock(&bounce_lock);
1514         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1515                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1516                 mtx_unlock(&bounce_lock);
1517                 dmat = map->dmat;
1518                 (dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_LOCK);
1519                 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1520                     map->callback_arg, BUS_DMA_WAITOK);
1521                 (dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1522                 mtx_lock(&bounce_lock);
1523         }
1524         mtx_unlock(&bounce_lock);
1525 }