354d70870cb580ed8ac04b98e4e484c0382bf38e
[dragonfly.git] / sys / platform / pc32 / i386 / busdma_machdep.c
1 /*
2  * Copyright (c) 1997, 1998 Justin T. Gibbs.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.94 2008/08/15 20:51:31 kmacy Exp $
27  * $DragonFly: src/sys/platform/pc32/i386/busdma_machdep.c,v 1.23 2008/06/05 18:06:32 swildner Exp $
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/mbuf.h>
34 #include <sys/uio.h>
35 #include <sys/bus_dma.h>
36 #include <sys/kernel.h>
37 #include <sys/sysctl.h>
38 #include <sys/lock.h>
39
40 #include <sys/thread2.h>
41 #include <sys/spinlock2.h>
42 #include <sys/mplock2.h>
43
44 #include <vm/vm.h>
45 #include <vm/vm_page.h>
46
47 /* XXX needed for to access pmap to convert per-proc virtual to physical */
48 #include <sys/proc.h>
49 #include <sys/lock.h>
50 #include <vm/vm_map.h>
51
52 #include <machine/md_var.h>
53
54 #define MAX_BPAGES      1024
55
56 /*
57  * 16 x N declared on stack.
58  */
59 #define BUS_DMA_CACHE_SEGMENTS  8
60
61 struct bounce_zone;
62 struct bus_dmamap;
63
64 struct bus_dma_tag {
65         bus_dma_tag_t   parent;
66         bus_size_t      alignment;
67         bus_size_t      boundary;
68         bus_addr_t      lowaddr;
69         bus_addr_t      highaddr;
70         bus_dma_filter_t *filter;
71         void            *filterarg;
72         bus_size_t      maxsize;
73         u_int           nsegments;
74         bus_size_t      maxsegsz;
75         int             flags;
76         int             ref_count;
77         int             map_count;
78         bus_dma_segment_t *segments;
79         struct bounce_zone *bounce_zone;
80 #ifdef SMP
81         struct spinlock spin;
82 #else
83         int             unused0;
84 #endif
85 };
86
87 /*
88  * bus_dma_tag private flags
89  */
90 #define BUS_DMA_BOUNCE_ALIGN    BUS_DMA_BUS2
91 #define BUS_DMA_BOUNCE_LOWADDR  BUS_DMA_BUS3
92 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
93
94 #define BUS_DMA_COULD_BOUNCE    (BUS_DMA_BOUNCE_LOWADDR | BUS_DMA_BOUNCE_ALIGN)
95
96 #define BUS_DMAMEM_KMALLOC(dmat) \
97         ((dmat)->maxsize <= PAGE_SIZE && \
98          (dmat)->alignment <= PAGE_SIZE && \
99          (dmat)->lowaddr >= ptoa(Maxmem))
100
101 struct bounce_page {
102         vm_offset_t     vaddr;          /* kva of bounce buffer */
103         bus_addr_t      busaddr;        /* Physical address */
104         vm_offset_t     datavaddr;      /* kva of client data */
105         bus_size_t      datacount;      /* client data count */
106         STAILQ_ENTRY(bounce_page) links;
107 };
108
109 struct bounce_zone {
110         STAILQ_ENTRY(bounce_zone) links;
111         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
112         STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
113 #ifdef SMP
114         struct spinlock spin;
115 #else
116         int             unused0;
117 #endif
118         int             total_bpages;
119         int             free_bpages;
120         int             reserved_bpages;
121         int             active_bpages;
122         int             total_bounced;
123         int             total_deferred;
124         int             reserve_failed;
125         bus_size_t      alignment;
126         bus_addr_t      lowaddr;
127         char            zoneid[8];
128         char            lowaddrid[20];
129         struct sysctl_ctx_list sysctl_ctx;
130         struct sysctl_oid *sysctl_tree;
131 };
132
133 #ifdef SMP
134 #define BZ_LOCK(bz)     spin_lock(&(bz)->spin)
135 #define BZ_UNLOCK(bz)   spin_unlock(&(bz)->spin)
136 #else
137 #define BZ_LOCK(bz)     crit_enter()
138 #define BZ_UNLOCK(bz)   crit_exit()
139 #endif
140
141 static struct lwkt_token bounce_zone_tok =
142         LWKT_TOKEN_MP_INITIALIZER(bounce_zone_tok);
143 static int busdma_zonecount;
144 static STAILQ_HEAD(, bounce_zone) bounce_zone_list =
145         STAILQ_HEAD_INITIALIZER(bounce_zone_list);
146
147 static int busdma_priv_zonecount = -1;
148
149 int busdma_swi_pending;
150 static int total_bounce_pages;
151 static int max_bounce_pages = MAX_BPAGES;
152 static int bounce_alignment = 1; /* XXX temporary */
153
154 TUNABLE_INT("hw.busdma.max_bpages", &max_bounce_pages);
155 TUNABLE_INT("hw.busdma.bounce_alignment", &bounce_alignment);
156
157 struct bus_dmamap {
158         struct bp_list  bpages;
159         int             pagesneeded;
160         int             pagesreserved;
161         bus_dma_tag_t   dmat;
162         void            *buf;           /* unmapped buffer pointer */
163         bus_size_t      buflen;         /* unmapped buffer length */
164         bus_dmamap_callback_t *callback;
165         void            *callback_arg;
166         STAILQ_ENTRY(bus_dmamap) links;
167 };
168
169 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist =
170         STAILQ_HEAD_INITIALIZER(bounce_map_callbacklist);
171 static struct spinlock bounce_map_list_spin =
172         SPINLOCK_INITIALIZER(&bounce_map_list_spin);
173
174 static struct bus_dmamap nobounce_dmamap;
175
176 static int              alloc_bounce_zone(bus_dma_tag_t);
177 static int              alloc_bounce_pages(bus_dma_tag_t, u_int, int);
178 static void             free_bounce_pages_all(bus_dma_tag_t);
179 static void             free_bounce_zone(bus_dma_tag_t);
180 static int              reserve_bounce_pages(bus_dma_tag_t, bus_dmamap_t, int);
181 static void             return_bounce_pages(bus_dma_tag_t, bus_dmamap_t);
182 static bus_addr_t       add_bounce_page(bus_dma_tag_t, bus_dmamap_t,
183                             vm_offset_t, bus_size_t);
184 static void             free_bounce_page(bus_dma_tag_t, struct bounce_page *);
185
186 static bus_dmamap_t     get_map_waiting(bus_dma_tag_t);
187 static void             add_map_callback(bus_dmamap_t);
188
189 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
190 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bounce_pages,
191            0, "Total bounce pages");
192 SYSCTL_INT(_hw_busdma, OID_AUTO, max_bpages, CTLFLAG_RD, &max_bounce_pages,
193            0, "Max bounce pages per bounce zone");
194 SYSCTL_INT(_hw_busdma, OID_AUTO, bounce_alignment, CTLFLAG_RD,
195            &bounce_alignment, 0, "Obey alignment constraint");
196
197 static __inline int
198 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
199 {
200         int retval;
201
202         retval = 0;
203         do {
204                 if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr) ||
205                      (bounce_alignment && (paddr & (dmat->alignment - 1)) != 0))
206                  && (dmat->filter == NULL ||
207                      dmat->filter(dmat->filterarg, paddr) != 0))
208                         retval = 1;
209
210                 dmat = dmat->parent;
211         } while (retval == 0 && dmat != NULL);
212         return (retval);
213 }
214
215 static __inline
216 bus_dma_segment_t *
217 bus_dma_tag_lock(bus_dma_tag_t tag, bus_dma_segment_t *cache)
218 {
219         if (tag->nsegments <= BUS_DMA_CACHE_SEGMENTS)
220                 return(cache);
221 #ifdef SMP
222         spin_lock(&tag->spin);
223 #endif
224         return(tag->segments);
225 }
226
227 static __inline
228 void
229 bus_dma_tag_unlock(bus_dma_tag_t tag)
230 {
231 #ifdef SMP
232         if (tag->nsegments > BUS_DMA_CACHE_SEGMENTS)
233                 spin_unlock(&tag->spin);
234 #endif
235 }
236
237 /*
238  * Allocate a device specific dma_tag.
239  */
240 int
241 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
242                    bus_size_t boundary, bus_addr_t lowaddr,
243                    bus_addr_t highaddr, bus_dma_filter_t *filter,
244                    void *filterarg, bus_size_t maxsize, int nsegments,
245                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)
246 {
247         bus_dma_tag_t newtag;
248         int error = 0;
249
250         /*
251          * Sanity checks
252          */
253
254         if (alignment == 0)
255                 alignment = 1;
256         if (alignment & (alignment - 1))
257                 panic("alignment must be power of 2\n");
258
259         if (boundary != 0) {
260                 if (boundary & (boundary - 1))
261                         panic("boundary must be power of 2\n");
262                 if (boundary < maxsegsz) {
263                         kprintf("boundary < maxsegsz:\n");
264                         print_backtrace(-1);
265                         maxsegsz = boundary;
266                 }
267         }
268
269         /* Return a NULL tag on failure */
270         *dmat = NULL;
271
272         newtag = kmalloc(sizeof(*newtag), M_DEVBUF, M_INTWAIT | M_ZERO);
273
274 #ifdef SMP
275         spin_init(&newtag->spin);
276 #endif
277         newtag->parent = parent;
278         newtag->alignment = alignment;
279         newtag->boundary = boundary;
280         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
281         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) + (PAGE_SIZE - 1);
282         newtag->filter = filter;
283         newtag->filterarg = filterarg;
284         newtag->maxsize = maxsize;
285         newtag->nsegments = nsegments;
286         newtag->maxsegsz = maxsegsz;
287         newtag->flags = flags;
288         newtag->ref_count = 1; /* Count ourself */
289         newtag->map_count = 0;
290         newtag->segments = NULL;
291         newtag->bounce_zone = NULL;
292
293         /* Take into account any restrictions imposed by our parent tag */
294         if (parent != NULL) {
295                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
296                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
297
298                 if (newtag->boundary == 0) {
299                         newtag->boundary = parent->boundary;
300                 } else if (parent->boundary != 0) {
301                         newtag->boundary = MIN(parent->boundary,
302                                                newtag->boundary);
303                 }
304
305 #ifdef notyet
306                 newtag->alignment = MAX(parent->alignment, newtag->alignment);
307 #endif
308
309                 if (newtag->filter == NULL) {
310                         /*
311                          * Short circuit looking at our parent directly
312                          * since we have encapsulated all of its information
313                          */
314                         newtag->filter = parent->filter;
315                         newtag->filterarg = parent->filterarg;
316                         newtag->parent = parent->parent;
317                 }
318                 if (newtag->parent != NULL)
319                         parent->ref_count++;
320         }
321
322         if (newtag->lowaddr < ptoa(Maxmem))
323                 newtag->flags |= BUS_DMA_BOUNCE_LOWADDR;
324         if (bounce_alignment && newtag->alignment > 1 &&
325             !(newtag->flags & BUS_DMA_ALIGNED))
326                 newtag->flags |= BUS_DMA_BOUNCE_ALIGN;
327
328         if ((newtag->flags & BUS_DMA_COULD_BOUNCE) &&
329             (flags & BUS_DMA_ALLOCNOW) != 0) {
330                 struct bounce_zone *bz;
331
332                 /* Must bounce */
333
334                 error = alloc_bounce_zone(newtag);
335                 if (error)
336                         goto back;
337                 bz = newtag->bounce_zone;
338
339                 if ((newtag->flags & BUS_DMA_ALLOCALL) == 0 &&
340                     ptoa(bz->total_bpages) < maxsize) {
341                         int pages;
342
343                         if (flags & BUS_DMA_ONEBPAGE) {
344                                 pages = 1;
345                         } else {
346                                 pages = atop(round_page(maxsize)) -
347                                         bz->total_bpages;
348                                 pages = MAX(pages, 1);
349                         }
350
351                         /* Add pages to our bounce pool */
352                         if (alloc_bounce_pages(newtag, pages, flags) < pages)
353                                 error = ENOMEM;
354
355                         /* Performed initial allocation */
356                         newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
357                 }
358         }
359 back:
360         if (error)
361                 kfree(newtag, M_DEVBUF);
362         else
363                 *dmat = newtag;
364         return error;
365 }
366
367 int
368 bus_dma_tag_destroy(bus_dma_tag_t dmat)
369 {
370         if (dmat != NULL) {
371                 if (dmat->map_count != 0)
372                         return (EBUSY);
373
374                 while (dmat != NULL) {
375                         bus_dma_tag_t parent;
376
377                         parent = dmat->parent;
378                         dmat->ref_count--;
379                         if (dmat->ref_count == 0) {
380                                 free_bounce_zone(dmat);
381                                 if (dmat->segments != NULL)
382                                         kfree(dmat->segments, M_DEVBUF);
383                                 kfree(dmat, M_DEVBUF);
384                                 /*
385                                  * Last reference count, so
386                                  * release our reference
387                                  * count on our parent.
388                                  */
389                                 dmat = parent;
390                         } else
391                                 dmat = NULL;
392                 }
393         }
394         return (0);
395 }
396
397 bus_size_t
398 bus_dma_tag_getmaxsize(bus_dma_tag_t tag)
399 {
400         return(tag->maxsize);
401 }
402
403 /*
404  * Allocate a handle for mapping from kva/uva/physical
405  * address space into bus device space.
406  */
407 int
408 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
409 {
410         int error;
411
412         error = 0;
413
414         if (dmat->segments == NULL) {
415                 KKASSERT(dmat->nsegments && dmat->nsegments < 16384);
416                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
417                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
418         }
419
420         if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
421                 struct bounce_zone *bz;
422                 int maxpages;
423
424                 /* Must bounce */
425
426                 if (dmat->bounce_zone == NULL) {
427                         error = alloc_bounce_zone(dmat);
428                         if (error)
429                                 return error;
430                 }
431                 bz = dmat->bounce_zone;
432
433                 *mapp = kmalloc(sizeof(**mapp), M_DEVBUF, M_INTWAIT | M_ZERO);
434
435                 /* Initialize the new map */
436                 STAILQ_INIT(&((*mapp)->bpages));
437
438                 /*
439                  * Attempt to add pages to our pool on a per-instance
440                  * basis up to a sane limit.
441                  */
442                 if (dmat->flags & BUS_DMA_ALLOCALL) {
443                         maxpages = Maxmem - atop(dmat->lowaddr);
444                 } else if (dmat->flags & BUS_DMA_BOUNCE_ALIGN) {
445                         maxpages = max_bounce_pages;
446                 } else {
447                         maxpages = MIN(max_bounce_pages,
448                                        Maxmem - atop(dmat->lowaddr));
449                 }
450                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
451                     (dmat->map_count > 0 && bz->total_bpages < maxpages)) {
452                         int pages;
453
454                         if (flags & BUS_DMA_ONEBPAGE) {
455                                 pages = 1;
456                         } else {
457                                 pages = atop(round_page(dmat->maxsize));
458                                 pages = MIN(maxpages - bz->total_bpages, pages);
459                                 pages = MAX(pages, 1);
460                         }
461                         if (alloc_bounce_pages(dmat, pages, flags) < pages)
462                                 error = ENOMEM;
463
464                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
465                                 if (!error &&
466                                     (dmat->flags & BUS_DMA_ALLOCALL) == 0)
467                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
468                         } else {
469                                 error = 0;
470                         }
471                 }
472         } else {
473                 *mapp = NULL;
474         }
475         if (!error)
476                 dmat->map_count++;
477         return error;
478 }
479
480 /*
481  * Destroy a handle for mapping from kva/uva/physical
482  * address space into bus device space.
483  */
484 int
485 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
486 {
487         if (map != NULL) {
488                 if (STAILQ_FIRST(&map->bpages) != NULL)
489                         return (EBUSY);
490                 kfree(map, M_DEVBUF);
491         }
492         dmat->map_count--;
493         return (0);
494 }
495
496 static __inline bus_size_t
497 check_kmalloc(bus_dma_tag_t dmat, const void *vaddr0, int verify)
498 {
499         bus_size_t maxsize = 0;
500         uintptr_t vaddr = (uintptr_t)vaddr0;
501
502         if ((vaddr ^ (vaddr + dmat->maxsize - 1)) & ~PAGE_MASK) {
503                 if (verify || bootverbose)
504                         kprintf("boundary check failed\n");
505                 if (verify)
506                         print_backtrace(-1); /* XXX panic */
507                 maxsize = dmat->maxsize;
508         }
509         if (vaddr & (dmat->alignment - 1)) {
510                 if (verify || bootverbose)
511                         kprintf("alignment check failed\n");
512                 if (verify)
513                         print_backtrace(-1); /* XXX panic */
514                 if (dmat->maxsize < dmat->alignment)
515                         maxsize = dmat->alignment;
516                 else
517                         maxsize = dmat->maxsize;
518         }
519         return maxsize;
520 }
521
522 /*
523  * Allocate a piece of memory that can be efficiently mapped into
524  * bus device space based on the constraints lited in the dma tag.
525  *
526  * mapp is degenerate.  By definition this allocation should not require
527  * bounce buffers so do not allocate a dma map.
528  */
529 int
530 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
531                  bus_dmamap_t *mapp)
532 {
533         int mflags;
534
535         /* If we succeed, no mapping/bouncing will be required */
536         *mapp = NULL;
537
538         if (dmat->segments == NULL) {
539                 KKASSERT(dmat->nsegments < 16384);
540                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
541                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
542         }
543
544         if (flags & BUS_DMA_NOWAIT)
545                 mflags = M_NOWAIT;
546         else
547                 mflags = M_WAITOK;
548         if (flags & BUS_DMA_ZERO)
549                 mflags |= M_ZERO;
550
551         if (BUS_DMAMEM_KMALLOC(dmat)) {
552                 bus_size_t maxsize;
553
554                 *vaddr = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
555
556                 /*
557                  * XXX
558                  * Check whether the allocation
559                  * - crossed a page boundary
560                  * - was not aligned
561                  * Retry with power-of-2 alignment in the above cases.
562                  */
563                 maxsize = check_kmalloc(dmat, *vaddr, 0);
564                 if (maxsize) {
565                         size_t size;
566
567                         kfree(*vaddr, M_DEVBUF);
568                         /* XXX check for overflow? */
569                         for (size = 1; size <= maxsize; size <<= 1)
570                                 ;
571                         *vaddr = kmalloc(size, M_DEVBUF, mflags);
572                         check_kmalloc(dmat, *vaddr, 1);
573                 }
574         } else {
575                 /*
576                  * XXX Use Contigmalloc until it is merged into this facility
577                  *     and handles multi-seg allocations.  Nobody is doing
578                  *     multi-seg allocations yet though.
579                  */
580                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
581                     0ul, dmat->lowaddr, dmat->alignment, dmat->boundary);
582         }
583         if (*vaddr == NULL)
584                 return (ENOMEM);
585         return (0);
586 }
587
588 /*
589  * Free a piece of memory and it's allociated dmamap, that was allocated
590  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
591  */
592 void
593 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
594 {
595         /*
596          * dmamem does not need to be bounced, so the map should be
597          * NULL
598          */
599         if (map != NULL)
600                 panic("bus_dmamem_free: Invalid map freed\n");
601         if (BUS_DMAMEM_KMALLOC(dmat))
602                 kfree(vaddr, M_DEVBUF);
603         else
604                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
605 }
606
607 static __inline vm_paddr_t
608 _bus_dma_extract(pmap_t pmap, vm_offset_t vaddr)
609 {
610         if (pmap)
611                 return pmap_extract(pmap, vaddr);
612         else
613                 return pmap_kextract(vaddr);
614 }
615
616 /*
617  * Utility function to load a linear buffer.  lastaddrp holds state
618  * between invocations (for multiple-buffer loads).  segp contains
619  * the segment following the starting one on entrace, and the ending
620  * segment on exit.  first indicates if this is the first invocation
621  * of this function.
622  */
623 static int
624 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
625                         bus_dmamap_t map,
626                         void *buf, bus_size_t buflen,
627                         bus_dma_segment_t *segments,
628                         int nsegments,
629                         pmap_t pmap,
630                         int flags,
631                         vm_paddr_t *lastpaddrp,
632                         int *segp,
633                         int first)
634 {
635         vm_offset_t vaddr;
636         vm_paddr_t paddr, nextpaddr;
637         bus_dma_segment_t *sg;
638         bus_addr_t bmask;
639         int seg, error = 0;
640
641         if (map == NULL)
642                 map = &nobounce_dmamap;
643
644 #ifdef INVARIANTS
645         if (dmat->flags & BUS_DMA_ALIGNED)
646                 KKASSERT(((uintptr_t)buf & (dmat->alignment - 1)) == 0);
647 #endif
648
649         /*
650          * If we are being called during a callback, pagesneeded will
651          * be non-zero, so we can avoid doing the work twice.
652          */
653         if ((dmat->flags & BUS_DMA_COULD_BOUNCE) &&
654             map != &nobounce_dmamap && map->pagesneeded == 0) {
655                 vm_offset_t vendaddr;
656
657                 /*
658                  * Count the number of bounce pages
659                  * needed in order to complete this transfer
660                  */
661                 vaddr = (vm_offset_t)buf;
662                 vendaddr = (vm_offset_t)buf + buflen;
663
664                 while (vaddr < vendaddr) {
665                         paddr = _bus_dma_extract(pmap, vaddr);
666                         if (run_filter(dmat, paddr) != 0)
667                                 map->pagesneeded++;
668                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
669                 }
670         }
671
672         /* Reserve Necessary Bounce Pages */
673         if (map->pagesneeded != 0) {
674                 struct bounce_zone *bz;
675
676                 bz = dmat->bounce_zone;
677                 BZ_LOCK(bz);
678                 if (flags & BUS_DMA_NOWAIT) {
679                         if (reserve_bounce_pages(dmat, map, 0) != 0) {
680                                 BZ_UNLOCK(bz);
681                                 error = ENOMEM;
682                                 goto free_bounce;
683                         }
684                 } else {
685                         if (reserve_bounce_pages(dmat, map, 1) != 0) {
686                                 /* Queue us for resources */
687                                 map->dmat = dmat;
688                                 map->buf = buf;
689                                 map->buflen = buflen;
690
691                                 STAILQ_INSERT_TAIL(
692                                     &dmat->bounce_zone->bounce_map_waitinglist,
693                                     map, links);
694                                 BZ_UNLOCK(bz);
695
696                                 return (EINPROGRESS);
697                         }
698                 }
699                 BZ_UNLOCK(bz);
700         }
701
702         KKASSERT(*segp >= 1 && *segp <= nsegments);
703         seg = *segp;
704         sg = &segments[seg - 1];
705
706         vaddr = (vm_offset_t)buf;
707         nextpaddr = *lastpaddrp;
708         bmask = ~(dmat->boundary - 1);  /* note: will be 0 if boundary is 0 */
709
710         /* force at least one segment */
711         do {
712                 bus_size_t size;
713
714                 /*
715                  * Per-page main loop
716                  */
717                 paddr = _bus_dma_extract(pmap, vaddr);
718                 size = PAGE_SIZE - (paddr & PAGE_MASK);
719                 if (size > buflen)
720                         size = buflen;
721                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
722                         /*
723                          * note: this paddr has the same in-page offset
724                          * as vaddr and thus the paddr above, so the
725                          * size does not have to be recalculated
726                          */
727                         paddr = add_bounce_page(dmat, map, vaddr, size);
728                 }
729
730                 /*
731                  * Fill in the bus_dma_segment
732                  */
733                 if (first) {
734                         sg->ds_addr = paddr;
735                         sg->ds_len = size;
736                         first = 0;
737                 } else if (paddr == nextpaddr) {
738                         sg->ds_len += size;
739                 } else {
740                         sg++;
741                         seg++;
742                         if (seg > nsegments)
743                                 break;
744                         sg->ds_addr = paddr;
745                         sg->ds_len = size;
746                 }
747                 nextpaddr = paddr + size;
748
749                 /*
750                  * Handle maxsegsz and boundary issues with a nested loop
751                  */
752                 for (;;) {
753                         bus_size_t tmpsize;
754
755                         /*
756                          * Limit to the boundary and maximum segment size
757                          */
758                         if (((nextpaddr - 1) ^ sg->ds_addr) & bmask) {
759                                 tmpsize = dmat->boundary -
760                                           (sg->ds_addr & ~bmask);
761                                 if (tmpsize > dmat->maxsegsz)
762                                         tmpsize = dmat->maxsegsz;
763                                 KKASSERT(tmpsize < sg->ds_len);
764                         } else if (sg->ds_len > dmat->maxsegsz) {
765                                 tmpsize = dmat->maxsegsz;
766                         } else {
767                                 break;
768                         }
769
770                         /*
771                          * Futz, split the data into a new segment.
772                          */
773                         if (seg >= nsegments)
774                                 goto fail;
775                         sg[1].ds_len = sg[0].ds_len - tmpsize;
776                         sg[1].ds_addr = sg[0].ds_addr + tmpsize;
777                         sg[0].ds_len = tmpsize;
778                         sg++;
779                         seg++;
780                 }
781
782                 /*
783                  * Adjust for loop
784                  */
785                 buflen -= size;
786                 vaddr += size;
787         } while (buflen > 0);
788 fail:
789         if (buflen != 0)
790                 error = EFBIG;
791
792         *segp = seg;
793         *lastpaddrp = nextpaddr;
794
795 free_bounce:
796         if (error && (dmat->flags & BUS_DMA_COULD_BOUNCE) &&
797             map != &nobounce_dmamap) {
798                 _bus_dmamap_unload(dmat, map);
799                 return_bounce_pages(dmat, map);
800         }
801         return error;
802 }
803
804 /*
805  * Map the buffer buf into bus space using the dmamap map.
806  */
807 int
808 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
809                 bus_size_t buflen, bus_dmamap_callback_t *callback,
810                 void *callback_arg, int flags)
811 {
812         bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
813         bus_dma_segment_t *segments;
814         vm_paddr_t lastaddr = 0;
815         int error, nsegs = 1;
816
817         if (map != NULL) {
818                 /*
819                  * XXX
820                  * Follow old semantics.  Once all of the callers are fixed,
821                  * we should get rid of these internal flag "adjustment".
822                  */
823                 flags &= ~BUS_DMA_NOWAIT;
824                 flags |= BUS_DMA_WAITOK;
825
826                 map->callback = callback;
827                 map->callback_arg = callback_arg;
828         }
829
830         segments = bus_dma_tag_lock(dmat, cache_segments);
831         error = _bus_dmamap_load_buffer(dmat, map, buf, buflen,
832                         segments, dmat->nsegments,
833                         NULL, flags, &lastaddr, &nsegs, 1);
834         if (error == EINPROGRESS) {
835                 KKASSERT((dmat->flags &
836                           (BUS_DMA_PRIVBZONE | BUS_DMA_ALLOCALL)) !=
837                          (BUS_DMA_PRIVBZONE | BUS_DMA_ALLOCALL));
838                 bus_dma_tag_unlock(dmat);
839                 return error;
840         }
841         callback(callback_arg, segments, nsegs, error);
842         bus_dma_tag_unlock(dmat);
843         return 0;
844 }
845
846 /*
847  * Like _bus_dmamap_load(), but for mbufs.
848  */
849 int
850 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
851                      struct mbuf *m0,
852                      bus_dmamap_callback2_t *callback, void *callback_arg,
853                      int flags)
854 {
855         bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
856         bus_dma_segment_t *segments;
857         int nsegs, error;
858
859         /*
860          * XXX
861          * Follow old semantics.  Once all of the callers are fixed,
862          * we should get rid of these internal flag "adjustment".
863          */
864         flags &= ~BUS_DMA_WAITOK;
865         flags |= BUS_DMA_NOWAIT;
866
867         segments = bus_dma_tag_lock(dmat, cache_segments);
868         error = bus_dmamap_load_mbuf_segment(dmat, map, m0,
869                         segments, dmat->nsegments, &nsegs, flags);
870         if (error) {
871                 /* force "no valid mappings" in callback */
872                 callback(callback_arg, segments, 0,
873                          0, error);
874         } else {
875                 callback(callback_arg, segments, nsegs,
876                          m0->m_pkthdr.len, error);
877         }
878         bus_dma_tag_unlock(dmat);
879         return error;
880 }
881
882 int
883 bus_dmamap_load_mbuf_segment(bus_dma_tag_t dmat, bus_dmamap_t map,
884                              struct mbuf *m0,
885                              bus_dma_segment_t *segs, int maxsegs,
886                              int *nsegs, int flags)
887 {
888         int error;
889
890         M_ASSERTPKTHDR(m0);
891
892         KASSERT(maxsegs >= 1, ("invalid maxsegs %d\n", maxsegs));
893         KASSERT(maxsegs <= dmat->nsegments,
894                 ("%d too many segments, dmat only support %d segments\n",
895                  maxsegs, dmat->nsegments));
896         KASSERT(flags & BUS_DMA_NOWAIT,
897                 ("only BUS_DMA_NOWAIT is supported\n"));
898
899         if (m0->m_pkthdr.len <= dmat->maxsize) {
900                 int first = 1;
901                 vm_paddr_t lastaddr = 0;
902                 struct mbuf *m;
903
904                 *nsegs = 1;
905                 error = 0;
906                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
907                         if (m->m_len == 0)
908                                 continue;
909
910                         error = _bus_dmamap_load_buffer(dmat, map,
911                                         m->m_data, m->m_len,
912                                         segs, maxsegs,
913                                         NULL, flags, &lastaddr,
914                                         nsegs, first);
915                         if (error == ENOMEM && !first) {
916                                 /*
917                                  * Out of bounce pages due to too many
918                                  * fragments in the mbuf chain; return
919                                  * EFBIG instead.
920                                  */
921                                 error = EFBIG;
922                         }
923                         first = 0;
924                 }
925 #ifdef INVARIANTS
926                 if (!error)
927                         KKASSERT(*nsegs <= maxsegs && *nsegs >= 1);
928 #endif
929         } else {
930                 *nsegs = 0;
931                 error = EINVAL;
932         }
933         KKASSERT(error != EINPROGRESS);
934         return error;
935 }
936
937 /*
938  * Like _bus_dmamap_load(), but for uios.
939  */
940 int
941 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
942                     struct uio *uio,
943                     bus_dmamap_callback2_t *callback, void *callback_arg,
944                     int flags)
945 {
946         vm_paddr_t lastaddr;
947         int nsegs, error, first, i;
948         bus_size_t resid;
949         struct iovec *iov;
950         pmap_t pmap;
951         bus_dma_segment_t cache_segments[BUS_DMA_CACHE_SEGMENTS];
952         bus_dma_segment_t *segments;
953         bus_dma_segment_t *segs;
954         int nsegs_left;
955
956         if (dmat->nsegments <= BUS_DMA_CACHE_SEGMENTS)
957                 segments = cache_segments;
958         else
959                 segments = kmalloc(sizeof(bus_dma_segment_t) * dmat->nsegments,
960                                    M_DEVBUF, M_WAITOK | M_ZERO);
961
962         /*
963          * XXX
964          * Follow old semantics.  Once all of the callers are fixed,
965          * we should get rid of these internal flag "adjustment".
966          */
967         flags &= ~BUS_DMA_WAITOK;
968         flags |= BUS_DMA_NOWAIT;
969
970         resid = (bus_size_t)uio->uio_resid;
971         iov = uio->uio_iov;
972
973         segs = segments;
974         nsegs_left = dmat->nsegments;
975
976         if (uio->uio_segflg == UIO_USERSPACE) {
977                 struct thread *td;
978
979                 td = uio->uio_td;
980                 KASSERT(td != NULL && td->td_proc != NULL,
981                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
982                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
983         } else {
984                 pmap = NULL;
985         }
986
987         error = 0;
988         nsegs = 1;
989         first = 1;
990         lastaddr = 0;
991         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
992                 /*
993                  * Now at the first iovec to load.  Load each iovec
994                  * until we have exhausted the residual count.
995                  */
996                 bus_size_t minlen =
997                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
998                 caddr_t addr = (caddr_t) iov[i].iov_base;
999
1000                 error = _bus_dmamap_load_buffer(dmat, map, addr, minlen,
1001                                 segs, nsegs_left,
1002                                 pmap, flags, &lastaddr, &nsegs, first);
1003                 first = 0;
1004
1005                 resid -= minlen;
1006                 if (error == 0) {
1007                         nsegs_left -= nsegs;
1008                         segs += nsegs;
1009                 }
1010         }
1011
1012         /*
1013          * Minimum one DMA segment, even if 0-length buffer.
1014          */
1015         if (nsegs_left == dmat->nsegments)
1016                 --nsegs_left;
1017
1018         if (error) {
1019                 /* force "no valid mappings" in callback */
1020                 callback(callback_arg, segments, 0,
1021                          0, error);
1022         } else {
1023                 callback(callback_arg, segments, dmat->nsegments - nsegs_left,
1024                          (bus_size_t)uio->uio_resid, error);
1025         }
1026         if (dmat->nsegments > BUS_DMA_CACHE_SEGMENTS)
1027                 kfree(segments, M_DEVBUF);
1028         return error;
1029 }
1030
1031 /*
1032  * Release the mapping held by map.
1033  */
1034 void
1035 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1036 {
1037         struct bounce_page *bpage;
1038
1039         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1040                 STAILQ_REMOVE_HEAD(&map->bpages, links);
1041                 free_bounce_page(dmat, bpage);
1042         }
1043 }
1044
1045 void
1046 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1047 {
1048         struct bounce_page *bpage;
1049
1050         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1051                 /*
1052                  * Handle data bouncing.  We might also
1053                  * want to add support for invalidating
1054                  * the caches on broken hardware
1055                  */
1056                 switch (op) {
1057                 case BUS_DMASYNC_PREWRITE:
1058                         while (bpage != NULL) {
1059                                 bcopy((void *)bpage->datavaddr,
1060                                       (void *)bpage->vaddr,
1061                                       bpage->datacount);
1062                                 bpage = STAILQ_NEXT(bpage, links);
1063                         }
1064                         dmat->bounce_zone->total_bounced++;
1065                         break;
1066
1067                 case BUS_DMASYNC_POSTREAD:
1068                         while (bpage != NULL) {
1069                                 bcopy((void *)bpage->vaddr,
1070                                       (void *)bpage->datavaddr,
1071                                       bpage->datacount);
1072                                 bpage = STAILQ_NEXT(bpage, links);
1073                         }
1074                         dmat->bounce_zone->total_bounced++;
1075                         break;
1076
1077                 case BUS_DMASYNC_PREREAD:
1078                 case BUS_DMASYNC_POSTWRITE:
1079                         /* No-ops */
1080                         break;
1081                 }
1082         }
1083 }
1084
1085 static int
1086 alloc_bounce_zone(bus_dma_tag_t dmat)
1087 {
1088         struct bounce_zone *bz, *new_bz;
1089
1090         KASSERT(dmat->bounce_zone == NULL,
1091                 ("bounce zone was already assigned\n"));
1092
1093         new_bz = kmalloc(sizeof(*new_bz), M_DEVBUF, M_INTWAIT | M_ZERO);
1094
1095         lwkt_gettoken(&bounce_zone_tok);
1096
1097         if ((dmat->flags & BUS_DMA_PRIVBZONE) == 0) {
1098                 /*
1099                  * For shared bounce zone, check to see
1100                  * if we already have a suitable zone
1101                  */
1102                 STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1103                         if (dmat->alignment <= bz->alignment &&
1104                             dmat->lowaddr >= bz->lowaddr) {
1105                                 lwkt_reltoken(&bounce_zone_tok);
1106
1107                                 dmat->bounce_zone = bz;
1108                                 kfree(new_bz, M_DEVBUF);
1109                                 return 0;
1110                         }
1111                 }
1112         }
1113         bz = new_bz;
1114
1115 #ifdef SMP
1116         spin_init(&bz->spin);
1117 #endif
1118         STAILQ_INIT(&bz->bounce_page_list);
1119         STAILQ_INIT(&bz->bounce_map_waitinglist);
1120         bz->free_bpages = 0;
1121         bz->reserved_bpages = 0;
1122         bz->active_bpages = 0;
1123         bz->lowaddr = dmat->lowaddr;
1124         bz->alignment = round_page(dmat->alignment);
1125         ksnprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1126
1127         if ((dmat->flags & BUS_DMA_PRIVBZONE) == 0) {
1128                 ksnprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1129                 busdma_zonecount++;
1130                 STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1131         } else {
1132                 ksnprintf(bz->zoneid, 8, "zone%d", busdma_priv_zonecount);
1133                 busdma_priv_zonecount--;
1134         }
1135
1136         lwkt_reltoken(&bounce_zone_tok);
1137
1138         dmat->bounce_zone = bz;
1139
1140         sysctl_ctx_init(&bz->sysctl_ctx);
1141         bz->sysctl_tree = SYSCTL_ADD_NODE(&bz->sysctl_ctx,
1142             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1143             CTLFLAG_RD, 0, "");
1144         if (bz->sysctl_tree == NULL) {
1145                 sysctl_ctx_free(&bz->sysctl_ctx);
1146                 return 0;       /* XXX error code? */
1147         }
1148
1149         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1150             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1151             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1152             "Total bounce pages");
1153         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1154             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1155             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1156             "Free bounce pages");
1157         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1158             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1159             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1160             "Reserved bounce pages");
1161         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1162             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1163             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1164             "Active bounce pages");
1165         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1166             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1167             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1168             "Total bounce requests");
1169         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1170             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1171             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1172             "Total bounce requests that were deferred");
1173         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1174             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1175             "reserve_failed", CTLFLAG_RD, &bz->reserve_failed, 0,
1176             "Total bounce page reservations that were failed");
1177         SYSCTL_ADD_STRING(&bz->sysctl_ctx,
1178             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1179             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1180         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1181             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1182             "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
1183
1184         return 0;
1185 }
1186
1187 static int
1188 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages, int flags)
1189 {
1190         struct bounce_zone *bz = dmat->bounce_zone;
1191         int count = 0, mflags;
1192
1193         if (flags & BUS_DMA_NOWAIT)
1194                 mflags = M_NOWAIT;
1195         else
1196                 mflags = M_WAITOK;
1197
1198         while (numpages > 0) {
1199                 struct bounce_page *bpage;
1200
1201                 bpage = kmalloc(sizeof(*bpage), M_DEVBUF, M_INTWAIT | M_ZERO);
1202
1203                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1204                                                          mflags, 0ul,
1205                                                          bz->lowaddr,
1206                                                          bz->alignment, 0);
1207                 if (bpage->vaddr == 0) {
1208                         kfree(bpage, M_DEVBUF);
1209                         break;
1210                 }
1211                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1212
1213                 BZ_LOCK(bz);
1214                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1215                 total_bounce_pages++;
1216                 bz->total_bpages++;
1217                 bz->free_bpages++;
1218                 BZ_UNLOCK(bz);
1219
1220                 count++;
1221                 numpages--;
1222         }
1223         return count;
1224 }
1225
1226 static void
1227 free_bounce_pages_all(bus_dma_tag_t dmat)
1228 {
1229         struct bounce_zone *bz = dmat->bounce_zone;
1230         struct bounce_page *bpage;
1231
1232         BZ_LOCK(bz);
1233
1234         while ((bpage = STAILQ_FIRST(&bz->bounce_page_list)) != NULL) {
1235                 STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1236
1237                 KKASSERT(total_bounce_pages > 0);
1238                 total_bounce_pages--;
1239
1240                 KKASSERT(bz->total_bpages > 0);
1241                 bz->total_bpages--;
1242
1243                 KKASSERT(bz->free_bpages > 0);
1244                 bz->free_bpages--;
1245
1246                 contigfree((void *)bpage->vaddr, PAGE_SIZE, M_DEVBUF);
1247                 kfree(bpage, M_DEVBUF);
1248         }
1249         if (bz->total_bpages) {
1250                 kprintf("#%d bounce pages are still in use\n",
1251                         bz->total_bpages);
1252                 print_backtrace(-1);
1253         }
1254
1255         BZ_UNLOCK(bz);
1256 }
1257
1258 static void
1259 free_bounce_zone(bus_dma_tag_t dmat)
1260 {
1261         struct bounce_zone *bz = dmat->bounce_zone;
1262
1263         if (bz == NULL)
1264                 return;
1265
1266         if ((dmat->flags & BUS_DMA_PRIVBZONE) == 0)
1267                 return;
1268
1269         free_bounce_pages_all(dmat);
1270         dmat->bounce_zone = NULL;
1271
1272         sysctl_ctx_free(&bz->sysctl_ctx);
1273         kfree(bz, M_DEVBUF);
1274 }
1275
1276 /* Assume caller holds bounce zone spinlock */
1277 static int
1278 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1279 {
1280         struct bounce_zone *bz = dmat->bounce_zone;
1281         int pages;
1282
1283         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1284         if (!commit && map->pagesneeded > (map->pagesreserved + pages)) {
1285                 bz->reserve_failed++;
1286                 return (map->pagesneeded - (map->pagesreserved + pages));
1287         }
1288
1289         bz->free_bpages -= pages;
1290
1291         bz->reserved_bpages += pages;
1292         KKASSERT(bz->reserved_bpages <= bz->total_bpages);
1293
1294         map->pagesreserved += pages;
1295         pages = map->pagesneeded - map->pagesreserved;
1296
1297         return pages;
1298 }
1299
1300 static void
1301 return_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
1302 {
1303         struct bounce_zone *bz = dmat->bounce_zone;
1304         int reserved = map->pagesreserved;
1305         bus_dmamap_t wait_map;
1306
1307         map->pagesreserved = 0;
1308         map->pagesneeded = 0;
1309
1310         if (reserved == 0)
1311                 return;
1312
1313         BZ_LOCK(bz);
1314
1315         bz->free_bpages += reserved;
1316         KKASSERT(bz->free_bpages <= bz->total_bpages);
1317
1318         KKASSERT(bz->reserved_bpages >= reserved);
1319         bz->reserved_bpages -= reserved;
1320
1321         wait_map = get_map_waiting(dmat);
1322
1323         BZ_UNLOCK(bz);
1324
1325         if (wait_map != NULL)
1326                 add_map_callback(map);
1327 }
1328
1329 static bus_addr_t
1330 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1331                 bus_size_t size)
1332 {
1333         struct bounce_zone *bz = dmat->bounce_zone;
1334         struct bounce_page *bpage;
1335
1336         KASSERT(map->pagesneeded > 0, ("map doesn't need any pages"));
1337         map->pagesneeded--;
1338
1339         KASSERT(map->pagesreserved > 0, ("map doesn't reserve any pages"));
1340         map->pagesreserved--;
1341
1342         BZ_LOCK(bz);
1343
1344         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1345         KASSERT(bpage != NULL, ("free page list is empty"));
1346         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1347
1348         KKASSERT(bz->reserved_bpages > 0);
1349         bz->reserved_bpages--;
1350
1351         bz->active_bpages++;
1352         KKASSERT(bz->active_bpages <= bz->total_bpages);
1353
1354         BZ_UNLOCK(bz);
1355
1356         bpage->datavaddr = vaddr;
1357         bpage->datacount = size;
1358         STAILQ_INSERT_TAIL(&map->bpages, bpage, links);
1359         return bpage->busaddr;
1360 }
1361
1362 static void
1363 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1364 {
1365         struct bounce_zone *bz = dmat->bounce_zone;
1366         bus_dmamap_t map;
1367
1368         bpage->datavaddr = 0;
1369         bpage->datacount = 0;
1370
1371         BZ_LOCK(bz);
1372
1373         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1374
1375         bz->free_bpages++;
1376         KKASSERT(bz->free_bpages <= bz->total_bpages);
1377
1378         KKASSERT(bz->active_bpages > 0);
1379         bz->active_bpages--;
1380
1381         map = get_map_waiting(dmat);
1382
1383         BZ_UNLOCK(bz);
1384
1385         if (map != NULL)
1386                 add_map_callback(map);
1387 }
1388
1389 /* Assume caller holds bounce zone spinlock */
1390 static bus_dmamap_t
1391 get_map_waiting(bus_dma_tag_t dmat)
1392 {
1393         struct bounce_zone *bz = dmat->bounce_zone;
1394         bus_dmamap_t map;
1395
1396         map = STAILQ_FIRST(&bz->bounce_map_waitinglist);
1397         if (map != NULL) {
1398                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1399                         STAILQ_REMOVE_HEAD(&bz->bounce_map_waitinglist, links);
1400                         bz->total_deferred++;
1401                 } else {
1402                         map = NULL;
1403                 }
1404         }
1405         return map;
1406 }
1407
1408 static void
1409 add_map_callback(bus_dmamap_t map)
1410 {
1411         spin_lock(&bounce_map_list_spin);
1412         STAILQ_INSERT_TAIL(&bounce_map_callbacklist, map, links);
1413         busdma_swi_pending = 1;
1414         setsoftvm();
1415         spin_unlock(&bounce_map_list_spin);
1416 }
1417
1418 void
1419 busdma_swi(void)
1420 {
1421         bus_dmamap_t map;
1422
1423         spin_lock(&bounce_map_list_spin);
1424         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1425                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1426                 spin_unlock(&bounce_map_list_spin);
1427                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
1428                                 map->callback, map->callback_arg, /*flags*/0);
1429                 spin_lock(&bounce_map_list_spin);
1430         }
1431         spin_unlock(&bounce_map_list_spin);
1432 }