Merge from vendor branch LIBSTDC++:
[dragonfly.git] / sys / i386 / 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/i386/i386/Attic/busdma_machdep.c,v 1.6 2004/01/14 05:30:57 dillon 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
36 #include <vm/vm.h>
37 #include <vm/vm_page.h>
38
39 /* XXX needed for to access pmap to convert per-proc virtual to physical */
40 #include <sys/proc.h>
41 #include <sys/lock.h>
42 #include <vm/vm_map.h>
43
44 #include <machine/bus.h>
45 #include <machine/md_var.h>
46
47 #define MAX_BPAGES 128
48
49 struct bus_dma_tag {
50         bus_dma_tag_t     parent;
51         bus_size_t        alignment;
52         bus_size_t        boundary;
53         bus_addr_t        lowaddr;
54         bus_addr_t        highaddr;
55         bus_dma_filter_t *filter;
56         void             *filterarg;
57         bus_size_t        maxsize;
58         u_int             nsegments;
59         bus_size_t        maxsegsz;
60         int               flags;
61         int               ref_count;
62         int               map_count;
63 };
64
65 struct bounce_page {
66         vm_offset_t     vaddr;          /* kva of bounce buffer */
67         bus_addr_t      busaddr;        /* Physical address */
68         vm_offset_t     datavaddr;      /* kva of client data */
69         bus_size_t      datacount;      /* client data count */
70         STAILQ_ENTRY(bounce_page) links;
71 };
72
73 int busdma_swi_pending;
74
75 static STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
76 static int free_bpages;
77 static int reserved_bpages;
78 static int active_bpages;
79 static int total_bpages;
80 static bus_addr_t bounce_lowaddr = BUS_SPACE_MAXADDR;
81
82 struct bus_dmamap {
83         struct bp_list         bpages;
84         int                    pagesneeded;
85         int                    pagesreserved;
86         bus_dma_tag_t          dmat;
87         void                  *buf;             /* unmapped buffer pointer */
88         bus_size_t             buflen;          /* unmapped buffer length */
89         bus_dmamap_callback_t *callback;
90         void                  *callback_arg;
91         STAILQ_ENTRY(bus_dmamap) links;
92 };
93
94 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
95 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
96 static struct bus_dmamap nobounce_dmamap;
97
98 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
99 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map);
100 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
101                                    vm_offset_t vaddr, bus_size_t size);
102 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
103 static __inline int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr);
104
105 static __inline int
106 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
107 {
108         int retval;
109
110         retval = 0;
111         do {
112                 if (paddr > dmat->lowaddr
113                  && paddr <= dmat->highaddr
114                  && (dmat->filter == NULL
115                   || (*dmat->filter)(dmat->filterarg, paddr) != 0))
116                         retval = 1;
117
118                 dmat = dmat->parent;            
119         } while (retval == 0 && dmat != NULL);
120         return (retval);
121 }
122
123 #define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
124 /*
125  * Allocate a device specific dma_tag.
126  */
127 int
128 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
129                    bus_size_t boundary, bus_addr_t lowaddr,
130                    bus_addr_t highaddr, bus_dma_filter_t *filter,
131                    void *filterarg, bus_size_t maxsize, int nsegments,
132                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)
133 {
134         bus_dma_tag_t newtag;
135         int error = 0;
136
137         /* Return a NULL tag on failure */
138         *dmat = NULL;
139
140         newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_DEVBUF, M_NOWAIT);
141         if (newtag == NULL)
142                 return (ENOMEM);
143
144         newtag->parent = parent;
145         newtag->alignment = alignment;
146         newtag->boundary = boundary;
147         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
148         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) + (PAGE_SIZE - 1);
149         newtag->filter = filter;
150         newtag->filterarg = filterarg;
151         newtag->maxsize = maxsize;
152         newtag->nsegments = nsegments;
153         newtag->maxsegsz = maxsegsz;
154         newtag->flags = flags;
155         newtag->ref_count = 1; /* Count ourself */
156         newtag->map_count = 0;
157         
158         /* Take into account any restrictions imposed by our parent tag */
159         if (parent != NULL) {
160                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
161                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
162                 /*
163                  * XXX Not really correct??? Probably need to honor boundary
164                  *     all the way up the inheritence chain.
165                  */
166                 newtag->boundary = MAX(parent->boundary, newtag->boundary);
167                 if (newtag->filter == NULL) {
168                         /*
169                          * Short circuit looking at our parent directly
170                          * since we have encapsulated all of its information
171                          */
172                         newtag->filter = parent->filter;
173                         newtag->filterarg = parent->filterarg;
174                         newtag->parent = parent->parent;
175                 }
176                 if (newtag->parent != NULL) {
177                         parent->ref_count++;
178                 }
179         }
180         
181         if (newtag->lowaddr < ptoa(Maxmem) &&
182             (flags & BUS_DMA_ALLOCNOW) != 0) {
183                 /* Must bounce */
184
185                 if (lowaddr > bounce_lowaddr) {
186                         /*
187                          * Go through the pool and kill any pages
188                          * that don't reside below lowaddr.
189                          */
190                         panic("bus_dma_tag_create: page reallocation "
191                               "not implemented");
192                 }
193                 if (ptoa(total_bpages) < maxsize) {
194                         int pages;
195
196                         pages = atop(maxsize) - total_bpages;
197
198                         /* Add pages to our bounce pool */
199                         if (alloc_bounce_pages(newtag, pages) < pages)
200                                 error = ENOMEM;
201                 }
202                 /* Performed initial allocation */
203                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
204         }
205         
206         if (error != 0) {
207                 free(newtag, M_DEVBUF);
208         } else {
209                 *dmat = newtag;
210         }
211         return (error);
212 }
213
214 int
215 bus_dma_tag_destroy(bus_dma_tag_t dmat)
216 {
217         if (dmat != NULL) {
218
219                 if (dmat->map_count != 0)
220                         return (EBUSY);
221
222                 while (dmat != NULL) {
223                         bus_dma_tag_t parent;
224
225                         parent = dmat->parent;
226                         dmat->ref_count--;
227                         if (dmat->ref_count == 0) {
228                                 free(dmat, M_DEVBUF);
229                                 /*
230                                  * Last reference count, so
231                                  * release our reference
232                                  * count on our parent.
233                                  */
234                                 dmat = parent;
235                         } else
236                                 dmat = NULL;
237                 }
238         }
239         return (0);
240 }
241
242 /*
243  * Allocate a handle for mapping from kva/uva/physical
244  * address space into bus device space.
245  */
246 int
247 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
248 {
249         int error;
250
251         error = 0;
252
253         if (dmat->lowaddr < ptoa(Maxmem)) {
254                 /* Must bounce */
255                 int maxpages;
256
257                 *mapp = (bus_dmamap_t)malloc(sizeof(**mapp), M_DEVBUF,
258                                              M_NOWAIT);
259                 if (*mapp == NULL) {
260                         return (ENOMEM);
261                 } else {
262                         /* Initialize the new map */
263                         bzero(*mapp, sizeof(**mapp));
264                         STAILQ_INIT(&((*mapp)->bpages));
265                 }
266                 /*
267                  * Attempt to add pages to our pool on a per-instance
268                  * basis up to a sane limit.
269                  */
270                 maxpages = MIN(MAX_BPAGES, Maxmem - atop(dmat->lowaddr));
271                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
272                  || (dmat->map_count > 0
273                   && total_bpages < maxpages)) {
274                         int pages;
275
276                         if (dmat->lowaddr > bounce_lowaddr) {
277                                 /*
278                                  * Go through the pool and kill any pages
279                                  * that don't reside below lowaddr.
280                                  */
281                                 panic("bus_dmamap_create: page reallocation "
282                                       "not implemented");
283                         }
284                         pages = atop(dmat->maxsize);
285                         pages = MIN(maxpages - total_bpages, pages);
286                         error = alloc_bounce_pages(dmat, pages);
287
288                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
289                                 if (error == 0)
290                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
291                         } else {
292                                 error = 0;
293                         }
294                 }
295         } else {
296                 *mapp = NULL;
297         }
298         if (error == 0)
299                 dmat->map_count++;
300         return (error);
301 }
302
303 /*
304  * Destroy a handle for mapping from kva/uva/physical
305  * address space into bus device space.
306  */
307 int
308 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
309 {
310         if (map != NULL) {
311                 if (STAILQ_FIRST(&map->bpages) != NULL)
312                         return (EBUSY);
313                 free(map, M_DEVBUF);
314         }
315         dmat->map_count--;
316         return (0);
317 }
318
319
320 /*
321  * Allocate a piece of memory that can be efficiently mapped into
322  * bus device space based on the constraints lited in the dma tag.
323  * A dmamap to for use with dmamap_load is also allocated.
324  */
325 int
326 bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
327                  bus_dmamap_t *mapp)
328 {
329         /* If we succeed, no mapping/bouncing will be required */
330         *mapp = NULL;
331
332         if ((dmat->maxsize <= PAGE_SIZE) &&
333             dmat->lowaddr >= ptoa(Maxmem)) {
334                 *vaddr = malloc(dmat->maxsize, M_DEVBUF,
335                                 (flags & BUS_DMA_NOWAIT) ? M_NOWAIT : M_WAITOK);
336         } else {
337                 /*
338                  * XXX Use Contigmalloc until it is merged into this facility
339                  *     and handles multi-seg allocations.  Nobody is doing
340                  *     multi-seg allocations yet though.
341                  */
342                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF,
343                     (flags & BUS_DMA_NOWAIT) ? M_NOWAIT : M_WAITOK,
344                     0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
345                     dmat->boundary);
346         }
347         if (*vaddr == NULL)
348                 return (ENOMEM);
349         return (0);
350 }
351
352 /*
353  * Free a piece of memory and it's allociated dmamap, that was allocated
354  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
355  */
356 void
357 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
358 {
359         /*
360          * dmamem does not need to be bounced, so the map should be
361          * NULL
362          */
363         if (map != NULL)
364                 panic("bus_dmamem_free: Invalid map freed\n");
365         if ((dmat->maxsize <= PAGE_SIZE) &&
366             dmat->lowaddr >= ptoa(Maxmem))
367                 free(vaddr, M_DEVBUF);
368         else
369                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
370 }
371
372 #define BUS_DMAMAP_NSEGS ((BUS_SPACE_MAXSIZE / PAGE_SIZE) + 1)
373
374 /*
375  * Map the buffer buf into bus space using the dmamap map.
376  */
377 int
378 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
379                 bus_size_t buflen, bus_dmamap_callback_t *callback,
380                 void *callback_arg, int flags)
381 {
382         vm_offset_t             vaddr;
383         vm_paddr_t              paddr;
384 #ifdef __GNUC__
385         bus_dma_segment_t       dm_segments[dmat->nsegments];
386 #else
387         bus_dma_segment_t       dm_segments[BUS_DMAMAP_NSEGS];
388 #endif
389         bus_dma_segment_t      *sg;
390         int                     seg;
391         int                     error;
392         vm_paddr_t              nextpaddr;
393
394         if (map == NULL)
395                 map = &nobounce_dmamap;
396
397         error = 0;
398         /*
399          * If we are being called during a callback, pagesneeded will
400          * be non-zero, so we can avoid doing the work twice.
401          */
402         if (dmat->lowaddr < ptoa(Maxmem) &&
403             map->pagesneeded == 0) {
404                 vm_offset_t     vendaddr;
405
406                 /*
407                  * Count the number of bounce pages
408                  * needed in order to complete this transfer
409                  */
410                 vaddr = trunc_page((vm_offset_t)buf);
411                 vendaddr = (vm_offset_t)buf + buflen;
412
413                 while (vaddr < vendaddr) {
414                         paddr = pmap_kextract(vaddr);
415                         if (run_filter(dmat, paddr) != 0) {
416
417                                 map->pagesneeded++;
418                         }
419                         vaddr += PAGE_SIZE;
420                 }
421         }
422
423         /* Reserve Necessary Bounce Pages */
424         if (map->pagesneeded != 0) {
425                 int s;
426
427                 s = splhigh();
428                 if (reserve_bounce_pages(dmat, map) != 0) {
429
430                         /* Queue us for resources */
431                         map->dmat = dmat;
432                         map->buf = buf;
433                         map->buflen = buflen;
434                         map->callback = callback;
435                         map->callback_arg = callback_arg;
436
437                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
438                         splx(s);
439
440                         return (EINPROGRESS);
441                 }
442                 splx(s);
443         }
444
445         vaddr = (vm_offset_t)buf;
446         sg = &dm_segments[0];
447         seg = 1;
448         sg->ds_len = 0;
449
450         nextpaddr = 0;
451         do {
452                 bus_size_t      size;
453
454                 paddr = pmap_kextract(vaddr);
455                 size = PAGE_SIZE - (paddr & PAGE_MASK);
456                 if (size > buflen)
457                         size = buflen;
458
459                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
460                         paddr = add_bounce_page(dmat, map, vaddr, size);
461                 }
462
463                 if (sg->ds_len == 0) {
464                         sg->ds_addr = paddr;
465                         sg->ds_len = size;
466                 } else if (paddr == nextpaddr) {
467                         sg->ds_len += size;
468                 } else {
469                         /* Go to the next segment */
470                         sg++;
471                         seg++;
472                         if (seg > dmat->nsegments)
473                                 break;
474                         sg->ds_addr = paddr;
475                         sg->ds_len = size;
476                 }
477                 vaddr += size;
478                 nextpaddr = paddr + size;
479                 buflen -= size;
480
481         } while (buflen > 0);
482
483         if (buflen != 0) {
484                 printf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
485                        (u_long)buflen);
486                 error = EFBIG;
487         }
488
489         (*callback)(callback_arg, dm_segments, seg, error);
490
491         return (0);
492 }
493
494 /*
495  * Utility function to load a linear buffer.  lastaddrp holds state
496  * between invocations (for multiple-buffer loads).  segp contains
497  * the starting segment on entrace, and the ending segment on exit.
498  * first indicates if this is the first invocation of this function.
499  */
500 static int
501 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
502                         bus_dma_segment_t segs[],
503                         void *buf, bus_size_t buflen,
504                         struct thread *td,
505                         int flags,
506                         vm_offset_t *lastaddrp,
507                         int *segp,
508                         int first)
509 {
510         bus_size_t sgsize;
511         bus_addr_t curaddr, lastaddr, baddr, bmask;
512         vm_offset_t vaddr = (vm_offset_t)buf;
513         int seg;
514         pmap_t pmap;
515
516         if (td->td_proc != NULL)
517                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
518         else
519                 pmap = NULL;
520
521         lastaddr = *lastaddrp;
522         bmask  = ~(dmat->boundary - 1);
523
524         for (seg = *segp; buflen > 0 ; ) {
525                 /*
526                  * Get the physical address for this segment.
527                  */
528                 if (pmap)
529                         curaddr = pmap_extract(pmap, vaddr);
530                 else
531                         curaddr = pmap_kextract(vaddr);
532
533                 /*
534                  * Compute the segment size, and adjust counts.
535                  */
536                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
537                 if (buflen < sgsize)
538                         sgsize = buflen;
539
540                 /*
541                  * Make sure we don't cross any boundaries.
542                  */
543                 if (dmat->boundary > 0) {
544                         baddr = (curaddr + dmat->boundary) & bmask;
545                         if (sgsize > (baddr - curaddr))
546                                 sgsize = (baddr - curaddr);
547                 }
548
549                 /*
550                  * Insert chunk into a segment, coalescing with
551                  * previous segment if possible.
552                  */
553                 if (first) {
554                         segs[seg].ds_addr = curaddr;
555                         segs[seg].ds_len = sgsize;
556                         first = 0;
557                 } else {
558                         if (curaddr == lastaddr &&
559                             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
560                             (dmat->boundary == 0 ||
561                              (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
562                                 segs[seg].ds_len += sgsize;
563                         else {
564                                 if (++seg >= dmat->nsegments)
565                                         break;
566                                 segs[seg].ds_addr = curaddr;
567                                 segs[seg].ds_len = sgsize;
568                         }
569                 }
570
571                 lastaddr = curaddr + sgsize;
572                 vaddr += sgsize;
573                 buflen -= sgsize;
574         }
575
576         *segp = seg;
577         *lastaddrp = lastaddr;
578
579         /*
580          * Did we fit?
581          */
582         return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
583 }
584
585 /*
586  * Like _bus_dmamap_load(), but for mbufs.
587  */
588 int
589 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
590                      struct mbuf *m0,
591                      bus_dmamap_callback2_t *callback, void *callback_arg,
592                      int flags)
593 {
594 #ifdef __GNUC__
595         bus_dma_segment_t dm_segments[dmat->nsegments];
596 #else
597         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
598 #endif
599         int nsegs, error;
600
601         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
602                 ("bus_dmamap_load_mbuf: No support for bounce pages!"));
603         KASSERT(m0->m_flags & M_PKTHDR,
604                 ("bus_dmamap_load_mbuf: no packet header"));
605
606         nsegs = 0;
607         error = 0;
608         if (m0->m_pkthdr.len <= dmat->maxsize) {
609                 int first = 1;
610                 vm_offset_t lastaddr = 0;
611                 struct mbuf *m;
612
613                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
614                         error = _bus_dmamap_load_buffer(dmat,
615                                         dm_segments,
616                                         m->m_data, m->m_len,
617                                         curthread, flags, &lastaddr,
618                                         &nsegs, first);
619                         first = 0;
620                 }
621         } else {
622                 error = EINVAL;
623         }
624
625         if (error) {
626                 /* force "no valid mappings" in callback */
627                 (*callback)(callback_arg, dm_segments, 0, 0, error);
628         } else {
629                 (*callback)(callback_arg, dm_segments,
630                             nsegs+1, m0->m_pkthdr.len, error);
631         }
632         return (error);
633 }
634
635 /*
636  * Like _bus_dmamap_load(), but for uios.
637  */
638 int
639 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
640                     struct uio *uio,
641                     bus_dmamap_callback2_t *callback, void *callback_arg,
642                     int flags)
643 {
644         vm_offset_t lastaddr;
645 #ifdef __GNUC__
646         bus_dma_segment_t dm_segments[dmat->nsegments];
647 #else
648         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
649 #endif
650         int nsegs, error, first, i;
651         bus_size_t resid;
652         struct iovec *iov;
653         struct thread *td = NULL;
654
655         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
656                 ("bus_dmamap_load_uio: No support for bounce pages!"));
657
658         resid = uio->uio_resid;
659         iov = uio->uio_iov;
660
661         if (uio->uio_segflg == UIO_USERSPACE) {
662                 td = uio->uio_td;
663                 KASSERT(td != NULL && td->td_proc != NULL,
664                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
665         }
666
667         nsegs = 0;
668         error = 0;
669         first = 1;
670         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
671                 /*
672                  * Now at the first iovec to load.  Load each iovec
673                  * until we have exhausted the residual count.
674                  */
675                 bus_size_t minlen =
676                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
677                 caddr_t addr = (caddr_t) iov[i].iov_base;
678
679                 error = _bus_dmamap_load_buffer(dmat,
680                                 dm_segments,
681                                 addr, minlen,
682                                 td, flags, &lastaddr, &nsegs, first);
683                 first = 0;
684
685                 resid -= minlen;
686         }
687
688         if (error) {
689                 /* force "no valid mappings" in callback */
690                 (*callback)(callback_arg, dm_segments, 0, 0, error);
691         } else {
692                 (*callback)(callback_arg, dm_segments,
693                             nsegs+1, uio->uio_resid, error);
694         }
695         return (error);
696 }
697
698 /*
699  * Release the mapping held by map.
700  */
701 void
702 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
703 {
704         struct bounce_page *bpage;
705
706         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
707                 STAILQ_REMOVE_HEAD(&map->bpages, links);
708                 free_bounce_page(dmat, bpage);
709         }
710 }
711
712 void
713 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
714 {
715         struct bounce_page *bpage;
716
717         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
718                 
719                 /*
720                  * Handle data bouncing.  We might also
721                  * want to add support for invalidating
722                  * the caches on broken hardware
723                  */
724                 switch (op) {
725                 case BUS_DMASYNC_PREWRITE:
726                         while (bpage != NULL) {
727                                 bcopy((void *)bpage->datavaddr,
728                                       (void *)bpage->vaddr,
729                                       bpage->datacount);
730                                 bpage = STAILQ_NEXT(bpage, links);
731                         }
732                         break;
733
734                 case BUS_DMASYNC_POSTREAD:
735                         while (bpage != NULL) {
736                                 bcopy((void *)bpage->vaddr,
737                                       (void *)bpage->datavaddr,
738                                       bpage->datacount);
739                                 bpage = STAILQ_NEXT(bpage, links);
740                         }
741                         break;
742                 case BUS_DMASYNC_PREREAD:
743                 case BUS_DMASYNC_POSTWRITE:
744                         /* No-ops */
745                         break;
746                 }
747         }
748 }
749
750 static int
751 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
752 {
753         int count;
754
755         count = 0;
756         if (total_bpages == 0) {
757                 STAILQ_INIT(&bounce_page_list);
758                 STAILQ_INIT(&bounce_map_waitinglist);
759                 STAILQ_INIT(&bounce_map_callbacklist);
760         }
761         
762         while (numpages > 0) {
763                 struct bounce_page *bpage;
764                 int s;
765
766                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
767                                                      M_NOWAIT);
768
769                 if (bpage == NULL)
770                         break;
771                 bzero(bpage, sizeof(*bpage));
772                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
773                                                          M_NOWAIT, 0ul,
774                                                          dmat->lowaddr,
775                                                          PAGE_SIZE,
776                                                          0);
777                 if (bpage->vaddr == NULL) {
778                         free(bpage, M_DEVBUF);
779                         break;
780                 }
781                 bpage->busaddr = pmap_kextract(bpage->vaddr);
782                 s = splhigh();
783                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
784                 total_bpages++;
785                 free_bpages++;
786                 splx(s);
787                 count++;
788                 numpages--;
789         }
790         return (count);
791 }
792
793 static int
794 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
795 {
796         int pages;
797
798         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
799         free_bpages -= pages;
800         reserved_bpages += pages;
801         map->pagesreserved += pages;
802         pages = map->pagesneeded - map->pagesreserved;
803
804         return (pages);
805 }
806
807 static bus_addr_t
808 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
809                 bus_size_t size)
810 {
811         int s;
812         struct bounce_page *bpage;
813
814         if (map->pagesneeded == 0)
815                 panic("add_bounce_page: map doesn't need any pages");
816         map->pagesneeded--;
817
818         if (map->pagesreserved == 0)
819                 panic("add_bounce_page: map doesn't need any pages");
820         map->pagesreserved--;
821
822         s = splhigh();
823         bpage = STAILQ_FIRST(&bounce_page_list);
824         if (bpage == NULL)
825                 panic("add_bounce_page: free page list is empty");
826
827         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
828         reserved_bpages--;
829         active_bpages++;
830         splx(s);
831
832         bpage->datavaddr = vaddr;
833         bpage->datacount = size;
834         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
835         return (bpage->busaddr);
836 }
837
838 static void
839 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
840 {
841         int s;
842         struct bus_dmamap *map;
843
844         bpage->datavaddr = 0;
845         bpage->datacount = 0;
846
847         s = splhigh();
848         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
849         free_bpages++;
850         active_bpages--;
851         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
852                 if (reserve_bounce_pages(map->dmat, map) == 0) {
853                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
854                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
855                                            map, links);
856                         busdma_swi_pending = 1;
857                         setsoftvm();
858                 }
859         }
860         splx(s);
861 }
862
863 void
864 busdma_swi()
865 {
866         int s;
867         struct bus_dmamap *map;
868
869         s = splhigh();
870         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
871                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
872                 splx(s);
873                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
874                                 map->callback, map->callback_arg, /*flags*/0);
875                 s = splhigh();
876         }
877         splx(s);
878 }