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