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