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