busdma(9): Add sysctl node to show whether aligment constraint is obeyed or not
[dragonfly.git] / sys / platform / pc32 / i386 / busdma_machdep.c
1 /*
2  * Copyright (c) 1997, 1998 Justin T. Gibbs.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.16.2.2 2003/01/23 00:55:27 scottl 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/thread2.h>
36 #include <sys/bus_dma.h>
37 #include <sys/kernel.h>
38 #include <sys/sysctl.h>
39 #include <sys/lock.h>
40 #include <sys/spinlock2.h>
41
42 #include <vm/vm.h>
43 #include <vm/vm_page.h>
44
45 /* XXX needed for to access pmap to convert per-proc virtual to physical */
46 #include <sys/proc.h>
47 #include <sys/lock.h>
48 #include <vm/vm_map.h>
49
50 #include <machine/md_var.h>
51
52 #define MAX_BPAGES      1024
53
54 struct bounce_zone;
55 struct bus_dmamap;
56
57 struct bus_dma_tag {
58         bus_dma_tag_t   parent;
59         bus_size_t      alignment;
60         bus_size_t      boundary;
61         bus_addr_t      lowaddr;
62         bus_addr_t      highaddr;
63         bus_dma_filter_t *filter;
64         void            *filterarg;
65         bus_size_t      maxsize;
66         u_int           nsegments;
67         bus_size_t      maxsegsz;
68         int             flags;
69         int             ref_count;
70         int             map_count;
71         bus_dma_segment_t *segments;
72         struct bounce_zone *bounce_zone;
73 };
74
75 /*
76  * bus_dma_tag private flags
77  */
78 #define BUS_DMA_BOUNCE_ALIGN    BUS_DMA_BUS2
79 #define BUS_DMA_BOUNCE_LOWADDR  BUS_DMA_BUS3
80 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
81
82 #define BUS_DMA_COULD_BOUNCE    (BUS_DMA_BOUNCE_LOWADDR | BUS_DMA_BOUNCE_ALIGN)
83
84 #define BUS_DMAMEM_KMALLOC(dmat) \
85         ((dmat)->maxsize <= PAGE_SIZE && \
86          (dmat)->alignment <= PAGE_SIZE && \
87          (dmat)->lowaddr >= ptoa(Maxmem))
88
89 struct bounce_page {
90         vm_offset_t     vaddr;          /* kva of bounce buffer */
91         bus_addr_t      busaddr;        /* Physical address */
92         vm_offset_t     datavaddr;      /* kva of client data */
93         bus_size_t      datacount;      /* client data count */
94         STAILQ_ENTRY(bounce_page) links;
95 };
96
97 struct bounce_zone {
98         STAILQ_ENTRY(bounce_zone) links;
99         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
100         STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
101 #ifdef SMP
102         struct spinlock spin;
103 #else
104         int             unused0;
105 #endif
106         int             total_bpages;
107         int             free_bpages;
108         int             reserved_bpages;
109         int             active_bpages;
110         int             total_bounced;
111         int             total_deferred;
112         int             reserve_failed;
113         bus_size_t      alignment;
114         bus_size_t      boundary;
115         bus_addr_t      lowaddr;
116         char            zoneid[8];
117         char            lowaddrid[20];
118         struct sysctl_ctx_list sysctl_ctx;
119         struct sysctl_oid *sysctl_tree;
120 };
121
122 #ifdef SMP
123 #define BZ_LOCK(bz)     spin_lock_wr(&(bz)->spin)
124 #define BZ_UNLOCK(bz)   spin_unlock_wr(&(bz)->spin)
125 #else
126 #define BZ_LOCK(bz)     crit_enter()
127 #define BZ_UNLOCK(bz)   crit_exit()
128 #endif
129
130 static struct lwkt_token bounce_zone_tok =
131         LWKT_TOKEN_INITIALIZER(bounce_zone_tok);
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 = 0; /* 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, alignment, CTLFLAG_RD, &bounce_alignment,
178            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                         backtrace();
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                 kprintf("boundary check failed\n");
452                 if (verify)
453                         backtrace(); /* XXX panic */
454                 maxsize = dmat->maxsize;
455         }
456         if (vaddr & (dmat->alignment - 1)) {
457                 kprintf("alignment check failed\n");
458                 if (verify)
459                         backtrace(); /* XXX panic */
460                 if (dmat->maxsize < dmat->alignment)
461                         maxsize = dmat->alignment;
462                 else
463                         maxsize = dmat->maxsize;
464         }
465         return maxsize;
466 }
467
468 /*
469  * Allocate a piece of memory that can be efficiently mapped into
470  * bus device space based on the constraints lited in the dma tag.
471  *
472  * mapp is degenerate.  By definition this allocation should not require
473  * bounce buffers so do not allocate a dma map.
474  */
475 int
476 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
477                  bus_dmamap_t *mapp)
478 {
479         int mflags;
480
481         /* If we succeed, no mapping/bouncing will be required */
482         *mapp = NULL;
483
484         if (dmat->segments == NULL) {
485                 KKASSERT(dmat->nsegments < 16384);
486                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
487                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
488         }
489
490         if (flags & BUS_DMA_NOWAIT)
491                 mflags = M_NOWAIT;
492         else
493                 mflags = M_WAITOK;
494         if (flags & BUS_DMA_ZERO)
495                 mflags |= M_ZERO;
496
497         if (BUS_DMAMEM_KMALLOC(dmat)) {
498                 bus_size_t maxsize;
499
500                 *vaddr = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
501
502                 /*
503                  * XXX
504                  * Check whether the allocation
505                  * - crossed a page boundary
506                  * - was not aligned
507                  * Retry with power-of-2 alignment in the above cases.
508                  */
509                 maxsize = check_kmalloc(dmat, *vaddr, 0);
510                 if (maxsize) {
511                         size_t size;
512
513                         kfree(*vaddr, M_DEVBUF);
514                         /* XXX check for overflow? */
515                         for (size = 1; size <= maxsize; size <<= 1)
516                                 ;
517                         *vaddr = kmalloc(size, M_DEVBUF, mflags);
518                         check_kmalloc(dmat, *vaddr, 1);
519                 }
520         } else {
521                 /*
522                  * XXX Use Contigmalloc until it is merged into this facility
523                  *     and handles multi-seg allocations.  Nobody is doing
524                  *     multi-seg allocations yet though.
525                  */
526                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
527                     0ul, dmat->lowaddr, dmat->alignment, dmat->boundary);
528         }
529         if (*vaddr == NULL)
530                 return (ENOMEM);
531         return (0);
532 }
533
534 /*
535  * Free a piece of memory and it's allociated dmamap, that was allocated
536  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
537  */
538 void
539 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
540 {
541         /*
542          * dmamem does not need to be bounced, so the map should be
543          * NULL
544          */
545         if (map != NULL)
546                 panic("bus_dmamem_free: Invalid map freed\n");
547         if (BUS_DMAMEM_KMALLOC(dmat))
548                 kfree(vaddr, M_DEVBUF);
549         else
550                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
551 }
552
553 static __inline vm_paddr_t
554 _bus_dma_extract(pmap_t pmap, vm_offset_t vaddr)
555 {
556         if (pmap)
557                 return pmap_extract(pmap, vaddr);
558         else
559                 return pmap_kextract(vaddr);
560 }
561
562 /*
563  * Utility function to load a linear buffer.  lastaddrp holds state
564  * between invocations (for multiple-buffer loads).  segp contains
565  * the segment following the starting one on entrace, and the ending
566  * segment on exit.  first indicates if this is the first invocation
567  * of this function.
568  */
569 static int
570 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
571                         bus_dmamap_t map,
572                         void *buf, bus_size_t buflen,
573                         bus_dma_segment_t *segments,
574                         int nsegments,
575                         pmap_t pmap,
576                         int flags,
577                         vm_paddr_t *lastpaddrp,
578                         int *segp,
579                         int first)
580 {
581         vm_offset_t vaddr;
582         vm_paddr_t paddr, nextpaddr;
583         bus_dma_segment_t *sg;
584         bus_addr_t bmask;
585         int seg, error = 0;
586
587         if (map == NULL)
588                 map = &nobounce_dmamap;
589
590 #ifdef INVARIANTS
591         if (dmat->flags & BUS_DMA_ALIGNED)
592                 KKASSERT(((uintptr_t)buf & (dmat->alignment - 1)) == 0);
593 #endif
594
595         /*
596          * If we are being called during a callback, pagesneeded will
597          * be non-zero, so we can avoid doing the work twice.
598          */
599         if ((dmat->flags & BUS_DMA_COULD_BOUNCE) &&
600             map != &nobounce_dmamap && map->pagesneeded == 0) {
601                 vm_offset_t vendaddr;
602
603                 /*
604                  * Count the number of bounce pages
605                  * needed in order to complete this transfer
606                  */
607                 vaddr = (vm_offset_t)buf;
608                 vendaddr = (vm_offset_t)buf + buflen;
609
610                 while (vaddr < vendaddr) {
611                         paddr = _bus_dma_extract(pmap, vaddr);
612                         if (run_filter(dmat, paddr) != 0)
613                                 map->pagesneeded++;
614                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
615                 }
616         }
617
618         /* Reserve Necessary Bounce Pages */
619         if (map->pagesneeded != 0) {
620                 struct bounce_zone *bz;
621
622                 bz = dmat->bounce_zone;
623                 BZ_LOCK(bz);
624                 if (flags & BUS_DMA_NOWAIT) {
625                         if (reserve_bounce_pages(dmat, map, 0) != 0) {
626                                 BZ_UNLOCK(bz);
627                                 error = ENOMEM;
628                                 goto free_bounce;
629                         }
630                 } else {
631                         if (reserve_bounce_pages(dmat, map, 1) != 0) {
632                                 /* Queue us for resources */
633                                 map->dmat = dmat;
634                                 map->buf = buf;
635                                 map->buflen = buflen;
636
637                                 STAILQ_INSERT_TAIL(
638                                     &dmat->bounce_zone->bounce_map_waitinglist,
639                                     map, links);
640                                 BZ_UNLOCK(bz);
641
642                                 return (EINPROGRESS);
643                         }
644                 }
645                 BZ_UNLOCK(bz);
646         }
647
648         KKASSERT(*segp >= 1 && *segp <= nsegments);
649         seg = *segp;
650         sg = &segments[seg - 1];
651
652         vaddr = (vm_offset_t)buf;
653         nextpaddr = *lastpaddrp;
654         bmask = ~(dmat->boundary - 1);  /* note: will be 0 if boundary is 0 */
655
656         /* force at least one segment */
657         do {
658                 bus_size_t size;
659
660                 /*
661                  * Per-page main loop
662                  */
663                 paddr = _bus_dma_extract(pmap, vaddr);
664                 size = PAGE_SIZE - (paddr & PAGE_MASK);
665                 if (size > buflen)
666                         size = buflen;
667                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
668                         /*
669                          * note: this paddr has the same in-page offset
670                          * as vaddr and thus the paddr above, so the
671                          * size does not have to be recalculated
672                          */
673                         paddr = add_bounce_page(dmat, map, vaddr, size);
674                 }
675
676                 /*
677                  * Fill in the bus_dma_segment
678                  */
679                 if (first) {
680                         sg->ds_addr = paddr;
681                         sg->ds_len = size;
682                         first = 0;
683                 } else if (paddr == nextpaddr) {
684                         sg->ds_len += size;
685                 } else {
686                         sg++;
687                         seg++;
688                         if (seg > nsegments)
689                                 break;
690                         sg->ds_addr = paddr;
691                         sg->ds_len = size;
692                 }
693                 nextpaddr = paddr + size;
694
695                 /*
696                  * Handle maxsegsz and boundary issues with a nested loop
697                  */
698                 for (;;) {
699                         bus_size_t tmpsize;
700
701                         /*
702                          * Limit to the boundary and maximum segment size
703                          */
704                         if (((nextpaddr - 1) ^ sg->ds_addr) & bmask) {
705                                 tmpsize = dmat->boundary -
706                                           (sg->ds_addr & ~bmask);
707                                 if (tmpsize > dmat->maxsegsz)
708                                         tmpsize = dmat->maxsegsz;
709                                 KKASSERT(tmpsize < sg->ds_len);
710                         } else if (sg->ds_len > dmat->maxsegsz) {
711                                 tmpsize = dmat->maxsegsz;
712                         } else {
713                                 break;
714                         }
715
716                         /*
717                          * Futz, split the data into a new segment.
718                          */
719                         if (seg >= nsegments)
720                                 goto fail;
721                         sg[1].ds_len = sg[0].ds_len - tmpsize;
722                         sg[1].ds_addr = sg[0].ds_addr + tmpsize;
723                         sg[0].ds_len = tmpsize;
724                         sg++;
725                         seg++;
726                 }
727
728                 /*
729                  * Adjust for loop
730                  */
731                 buflen -= size;
732                 vaddr += size;
733         } while (buflen > 0);
734 fail:
735         if (buflen != 0)
736                 error = EFBIG;
737
738         *segp = seg;
739         *lastpaddrp = nextpaddr;
740
741 free_bounce:
742         if (error && (dmat->flags & BUS_DMA_COULD_BOUNCE) &&
743             map != &nobounce_dmamap) {
744                 _bus_dmamap_unload(dmat, map);
745                 return_bounce_pages(dmat, map);
746         }
747         return error;
748 }
749
750 /*
751  * Map the buffer buf into bus space using the dmamap map.
752  */
753 int
754 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
755                 bus_size_t buflen, bus_dmamap_callback_t *callback,
756                 void *callback_arg, int flags)
757 {
758         vm_paddr_t lastaddr = 0;
759         int error, nsegs = 1;
760
761         if (map != NULL) {
762                 /*
763                  * XXX
764                  * Follow old semantics.  Once all of the callers are fixed,
765                  * we should get rid of these internal flag "adjustment".
766                  */
767                 flags &= ~BUS_DMA_NOWAIT;
768                 flags |= BUS_DMA_WAITOK;
769
770                 map->callback = callback;
771                 map->callback_arg = callback_arg;
772         }
773
774         error = _bus_dmamap_load_buffer(dmat, map, buf, buflen,
775                         dmat->segments, dmat->nsegments,
776                         NULL, flags, &lastaddr, &nsegs, 1);
777         if (error == EINPROGRESS)
778                 return error;
779
780         callback(callback_arg, dmat->segments, nsegs, error);
781         return 0;
782 }
783
784 /*
785  * Like _bus_dmamap_load(), but for mbufs.
786  */
787 int
788 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
789                      struct mbuf *m0,
790                      bus_dmamap_callback2_t *callback, void *callback_arg,
791                      int flags)
792 {
793         int nsegs, error;
794
795         /*
796          * XXX
797          * Follow old semantics.  Once all of the callers are fixed,
798          * we should get rid of these internal flag "adjustment".
799          */
800         flags &= ~BUS_DMA_WAITOK;
801         flags |= BUS_DMA_NOWAIT;
802
803         error = bus_dmamap_load_mbuf_segment(dmat, map, m0,
804                         dmat->segments, dmat->nsegments, &nsegs, flags);
805         if (error) {
806                 /* force "no valid mappings" in callback */
807                 callback(callback_arg, dmat->segments, 0, 0, error);
808         } else {
809                 callback(callback_arg, dmat->segments, nsegs,
810                          m0->m_pkthdr.len, error);
811         }
812         return error;
813 }
814
815 int
816 bus_dmamap_load_mbuf_segment(bus_dma_tag_t dmat, bus_dmamap_t map,
817                              struct mbuf *m0,
818                              bus_dma_segment_t *segs, int maxsegs,
819                              int *nsegs, int flags)
820 {
821         int error;
822
823         M_ASSERTPKTHDR(m0);
824
825         KASSERT(maxsegs >= 1, ("invalid maxsegs %d\n", maxsegs));
826         KASSERT(maxsegs <= dmat->nsegments,
827                 ("%d too many segments, dmat only support %d segments\n",
828                  maxsegs, dmat->nsegments));
829         KASSERT(flags & BUS_DMA_NOWAIT,
830                 ("only BUS_DMA_NOWAIT is supported\n"));
831
832         if (m0->m_pkthdr.len <= dmat->maxsize) {
833                 int first = 1;
834                 vm_paddr_t lastaddr = 0;
835                 struct mbuf *m;
836
837                 *nsegs = 1;
838                 error = 0;
839                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
840                         if (m->m_len == 0)
841                                 continue;
842
843                         error = _bus_dmamap_load_buffer(dmat, map,
844                                         m->m_data, m->m_len,
845                                         segs, maxsegs,
846                                         NULL, flags, &lastaddr,
847                                         nsegs, first);
848                         if (error == ENOMEM && !first) {
849                                 /*
850                                  * Out of bounce pages due to too many
851                                  * fragments in the mbuf chain; return
852                                  * EFBIG instead.
853                                  */
854                                 error = EFBIG;
855                         }
856                         first = 0;
857                 }
858 #ifdef INVARIANTS
859                 if (!error)
860                         KKASSERT(*nsegs <= maxsegs && *nsegs >= 1);
861 #endif
862         } else {
863                 *nsegs = 0;
864                 error = EINVAL;
865         }
866         KKASSERT(error != EINPROGRESS);
867         return error;
868 }
869
870 /*
871  * Like _bus_dmamap_load(), but for uios.
872  */
873 int
874 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
875                     struct uio *uio,
876                     bus_dmamap_callback2_t *callback, void *callback_arg,
877                     int flags)
878 {
879         vm_paddr_t lastaddr;
880         int nsegs, error, first, i;
881         bus_size_t resid;
882         struct iovec *iov;
883         pmap_t pmap;
884
885         /*
886          * XXX
887          * Follow old semantics.  Once all of the callers are fixed,
888          * we should get rid of these internal flag "adjustment".
889          */
890         flags &= ~BUS_DMA_WAITOK;
891         flags |= BUS_DMA_NOWAIT;
892
893         resid = uio->uio_resid;
894         iov = uio->uio_iov;
895
896         if (uio->uio_segflg == UIO_USERSPACE) {
897                 struct thread *td;
898
899                 td = uio->uio_td;
900                 KASSERT(td != NULL && td->td_proc != NULL,
901                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
902                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
903         } else {
904                 pmap = NULL;
905         }
906
907         error = 0;
908         nsegs = 1;
909         first = 1;
910         lastaddr = 0;
911         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
912                 /*
913                  * Now at the first iovec to load.  Load each iovec
914                  * until we have exhausted the residual count.
915                  */
916                 bus_size_t minlen =
917                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
918                 caddr_t addr = (caddr_t) iov[i].iov_base;
919
920                 error = _bus_dmamap_load_buffer(dmat, map, addr, minlen,
921                                 dmat->segments, dmat->nsegments,
922                                 pmap, flags, &lastaddr, &nsegs, first);
923                 first = 0;
924
925                 resid -= minlen;
926         }
927
928         if (error) {
929                 /* force "no valid mappings" in callback */
930                 callback(callback_arg, dmat->segments, 0, 0, error);
931         } else {
932                 callback(callback_arg, dmat->segments, nsegs,
933                          uio->uio_resid, error);
934         }
935         return error;
936 }
937
938 /*
939  * Release the mapping held by map.
940  */
941 void
942 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
943 {
944         struct bounce_page *bpage;
945
946         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
947                 STAILQ_REMOVE_HEAD(&map->bpages, links);
948                 free_bounce_page(dmat, bpage);
949         }
950 }
951
952 void
953 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
954 {
955         struct bounce_page *bpage;
956
957         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
958                 /*
959                  * Handle data bouncing.  We might also
960                  * want to add support for invalidating
961                  * the caches on broken hardware
962                  */
963                 switch (op) {
964                 case BUS_DMASYNC_PREWRITE:
965                         while (bpage != NULL) {
966                                 bcopy((void *)bpage->datavaddr,
967                                       (void *)bpage->vaddr,
968                                       bpage->datacount);
969                                 bpage = STAILQ_NEXT(bpage, links);
970                         }
971                         dmat->bounce_zone->total_bounced++;
972                         break;
973
974                 case BUS_DMASYNC_POSTREAD:
975                         while (bpage != NULL) {
976                                 bcopy((void *)bpage->vaddr,
977                                       (void *)bpage->datavaddr,
978                                       bpage->datacount);
979                                 bpage = STAILQ_NEXT(bpage, links);
980                         }
981                         dmat->bounce_zone->total_bounced++;
982                         break;
983
984                 case BUS_DMASYNC_PREREAD:
985                 case BUS_DMASYNC_POSTWRITE:
986                         /* No-ops */
987                         break;
988                 }
989         }
990 }
991
992 static int
993 alloc_bounce_zone(bus_dma_tag_t dmat)
994 {
995         struct bounce_zone *bz, *new_bz;
996         lwkt_tokref ref;
997
998         KASSERT(dmat->bounce_zone == NULL,
999                 ("bounce zone was already assigned\n"));
1000
1001         new_bz = kmalloc(sizeof(*new_bz), M_DEVBUF, M_INTWAIT | M_ZERO);
1002
1003         lwkt_gettoken(&ref, &bounce_zone_tok);
1004
1005         /* Check to see if we already have a suitable zone */
1006         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1007                 if (dmat->alignment <= bz->alignment &&
1008                     dmat->boundary <= bz->boundary &&
1009                     dmat->lowaddr >= bz->lowaddr) {
1010                         lwkt_reltoken(&ref);
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         bz->boundary = round_page(dmat->boundary);
1030         if (bz->boundary == 0)
1031                 bz->boundary = PAGE_SIZE;
1032         ksnprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1033         busdma_zonecount++;
1034         ksnprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1035         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1036
1037         lwkt_reltoken(&ref);
1038
1039         dmat->bounce_zone = bz;
1040
1041         sysctl_ctx_init(&bz->sysctl_ctx);
1042         bz->sysctl_tree = SYSCTL_ADD_NODE(&bz->sysctl_ctx,
1043             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1044             CTLFLAG_RD, 0, "");
1045         if (bz->sysctl_tree == NULL) {
1046                 sysctl_ctx_free(&bz->sysctl_ctx);
1047                 return 0;       /* XXX error code? */
1048         }
1049
1050         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1051             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1052             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1053             "Total bounce pages");
1054         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1055             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1056             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1057             "Free bounce pages");
1058         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1059             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1060             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1061             "Reserved bounce pages");
1062         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1063             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1064             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1065             "Active bounce pages");
1066         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1067             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1068             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1069             "Total bounce requests");
1070         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1071             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1072             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1073             "Total bounce requests that were deferred");
1074         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1075             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1076             "reserve_failed", CTLFLAG_RD, &bz->reserve_failed, 0,
1077             "Total bounce page reservations that were failed");
1078         SYSCTL_ADD_STRING(&bz->sysctl_ctx,
1079             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1080             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1081         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1082             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1083             "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
1084         SYSCTL_ADD_INT(&bz->sysctl_ctx,
1085             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
1086             "boundary", CTLFLAG_RD, &bz->boundary, 0, "");
1087
1088         return 0;
1089 }
1090
1091 static int
1092 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages, int flags)
1093 {
1094         struct bounce_zone *bz = dmat->bounce_zone;
1095         int count = 0, mflags;
1096
1097         if (flags & BUS_DMA_NOWAIT)
1098                 mflags = M_NOWAIT;
1099         else
1100                 mflags = M_WAITOK;
1101
1102         while (numpages > 0) {
1103                 struct bounce_page *bpage;
1104
1105                 bpage = kmalloc(sizeof(*bpage), M_DEVBUF, M_INTWAIT | M_ZERO);
1106
1107                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
1108                                                          mflags, 0ul,
1109                                                          bz->lowaddr,
1110                                                          bz->alignment,
1111                                                          bz->boundary);
1112                 if (bpage->vaddr == 0) {
1113                         kfree(bpage, M_DEVBUF);
1114                         break;
1115                 }
1116                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1117
1118                 BZ_LOCK(bz);
1119                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1120                 total_bounce_pages++;
1121                 bz->total_bpages++;
1122                 bz->free_bpages++;
1123                 BZ_UNLOCK(bz);
1124
1125                 count++;
1126                 numpages--;
1127         }
1128         return count;
1129 }
1130
1131 /* Assume caller holds bounce zone spinlock */
1132 static int
1133 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1134 {
1135         struct bounce_zone *bz = dmat->bounce_zone;
1136         int pages;
1137
1138         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1139         if (!commit && map->pagesneeded > (map->pagesreserved + pages)) {
1140                 bz->reserve_failed++;
1141                 return (map->pagesneeded - (map->pagesreserved + pages));
1142         }
1143
1144         bz->free_bpages -= pages;
1145
1146         bz->reserved_bpages += pages;
1147         KKASSERT(bz->reserved_bpages <= bz->total_bpages);
1148
1149         map->pagesreserved += pages;
1150         pages = map->pagesneeded - map->pagesreserved;
1151
1152         return pages;
1153 }
1154
1155 static void
1156 return_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
1157 {
1158         struct bounce_zone *bz = dmat->bounce_zone;
1159         int reserved = map->pagesreserved;
1160         bus_dmamap_t wait_map;
1161
1162         map->pagesreserved = 0;
1163         map->pagesneeded = 0;
1164
1165         if (reserved == 0)
1166                 return;
1167
1168         BZ_LOCK(bz);
1169
1170         bz->free_bpages += reserved;
1171         KKASSERT(bz->free_bpages <= bz->total_bpages);
1172
1173         KKASSERT(bz->reserved_bpages >= reserved);
1174         bz->reserved_bpages -= reserved;
1175
1176         wait_map = get_map_waiting(dmat);
1177
1178         BZ_UNLOCK(bz);
1179
1180         if (wait_map != NULL)
1181                 add_map_callback(map);
1182 }
1183
1184 static bus_addr_t
1185 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1186                 bus_size_t size)
1187 {
1188         struct bounce_zone *bz = dmat->bounce_zone;
1189         struct bounce_page *bpage;
1190
1191         KASSERT(map->pagesneeded > 0, ("map doesn't need any pages"));
1192         map->pagesneeded--;
1193
1194         KASSERT(map->pagesreserved > 0, ("map doesn't reserve any pages"));
1195         map->pagesreserved--;
1196
1197         BZ_LOCK(bz);
1198
1199         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1200         KASSERT(bpage != NULL, ("free page list is empty"));
1201         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1202
1203         KKASSERT(bz->reserved_bpages > 0);
1204         bz->reserved_bpages--;
1205
1206         bz->active_bpages++;
1207         KKASSERT(bz->active_bpages <= bz->total_bpages);
1208
1209         BZ_UNLOCK(bz);
1210
1211         bpage->datavaddr = vaddr;
1212         bpage->datacount = size;
1213         STAILQ_INSERT_TAIL(&map->bpages, bpage, links);
1214         return bpage->busaddr;
1215 }
1216
1217 static void
1218 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1219 {
1220         struct bounce_zone *bz = dmat->bounce_zone;
1221         bus_dmamap_t map;
1222
1223         bpage->datavaddr = 0;
1224         bpage->datacount = 0;
1225
1226         BZ_LOCK(bz);
1227
1228         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1229
1230         bz->free_bpages++;
1231         KKASSERT(bz->free_bpages <= bz->total_bpages);
1232
1233         KKASSERT(bz->active_bpages > 0);
1234         bz->active_bpages--;
1235
1236         map = get_map_waiting(dmat);
1237
1238         BZ_UNLOCK(bz);
1239
1240         if (map != NULL)
1241                 add_map_callback(map);
1242 }
1243
1244 /* Assume caller holds bounce zone spinlock */
1245 static bus_dmamap_t
1246 get_map_waiting(bus_dma_tag_t dmat)
1247 {
1248         struct bounce_zone *bz = dmat->bounce_zone;
1249         bus_dmamap_t map;
1250
1251         map = STAILQ_FIRST(&bz->bounce_map_waitinglist);
1252         if (map != NULL) {
1253                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1254                         STAILQ_REMOVE_HEAD(&bz->bounce_map_waitinglist, links);
1255                         bz->total_deferred++;
1256                 } else {
1257                         map = NULL;
1258                 }
1259         }
1260         return map;
1261 }
1262
1263 static void
1264 add_map_callback(bus_dmamap_t map)
1265 {
1266         /* XXX callbacklist is not MPSAFE */
1267         crit_enter();
1268         get_mplock();
1269         STAILQ_INSERT_TAIL(&bounce_map_callbacklist, map, links);
1270         busdma_swi_pending = 1;
1271         setsoftvm();
1272         rel_mplock();
1273         crit_exit();
1274 }
1275
1276 void
1277 busdma_swi(void)
1278 {
1279         bus_dmamap_t map;
1280
1281         crit_enter();
1282         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1283                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1284                 crit_exit();
1285                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
1286                                 map->callback, map->callback_arg, /*flags*/0);
1287                 crit_enter();
1288         }
1289         crit_exit();
1290 }