Add BUS_DMA_ZERO flag to bus_dmamem_alloc.
[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.7 2004/02/16 19:35:53 joerg 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         int mflags;
330         /* If we succeed, no mapping/bouncing will be required */
331         *mapp = NULL;
332
333         if (flags & BUS_DMA_NOWAIT)
334                 mflags = M_NOWAIT;
335         else
336                 mflags = M_WAITOK;
337         if (flags & BUS_DMA_ZERO)
338                 mflags |= M_ZERO;
339
340         if ((dmat->maxsize <= PAGE_SIZE) &&
341             dmat->lowaddr >= ptoa(Maxmem)) {
342                 *vaddr = malloc(dmat->maxsize, M_DEVBUF, mflags);
343         } else {
344                 /*
345                  * XXX Use Contigmalloc until it is merged into this facility
346                  *     and handles multi-seg allocations.  Nobody is doing
347                  *     multi-seg allocations yet though.
348                  */
349                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
350                     0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
351                     dmat->boundary);
352         }
353         if (*vaddr == NULL)
354                 return (ENOMEM);
355         return (0);
356 }
357
358 /*
359  * Free a piece of memory and it's allociated dmamap, that was allocated
360  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
361  */
362 void
363 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
364 {
365         /*
366          * dmamem does not need to be bounced, so the map should be
367          * NULL
368          */
369         if (map != NULL)
370                 panic("bus_dmamem_free: Invalid map freed\n");
371         if ((dmat->maxsize <= PAGE_SIZE) &&
372             dmat->lowaddr >= ptoa(Maxmem))
373                 free(vaddr, M_DEVBUF);
374         else
375                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
376 }
377
378 #define BUS_DMAMAP_NSEGS ((BUS_SPACE_MAXSIZE / PAGE_SIZE) + 1)
379
380 /*
381  * Map the buffer buf into bus space using the dmamap map.
382  */
383 int
384 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
385                 bus_size_t buflen, bus_dmamap_callback_t *callback,
386                 void *callback_arg, int flags)
387 {
388         vm_offset_t             vaddr;
389         vm_paddr_t              paddr;
390 #ifdef __GNUC__
391         bus_dma_segment_t       dm_segments[dmat->nsegments];
392 #else
393         bus_dma_segment_t       dm_segments[BUS_DMAMAP_NSEGS];
394 #endif
395         bus_dma_segment_t      *sg;
396         int                     seg;
397         int                     error;
398         vm_paddr_t              nextpaddr;
399
400         if (map == NULL)
401                 map = &nobounce_dmamap;
402
403         error = 0;
404         /*
405          * If we are being called during a callback, pagesneeded will
406          * be non-zero, so we can avoid doing the work twice.
407          */
408         if (dmat->lowaddr < ptoa(Maxmem) &&
409             map->pagesneeded == 0) {
410                 vm_offset_t     vendaddr;
411
412                 /*
413                  * Count the number of bounce pages
414                  * needed in order to complete this transfer
415                  */
416                 vaddr = trunc_page((vm_offset_t)buf);
417                 vendaddr = (vm_offset_t)buf + buflen;
418
419                 while (vaddr < vendaddr) {
420                         paddr = pmap_kextract(vaddr);
421                         if (run_filter(dmat, paddr) != 0) {
422
423                                 map->pagesneeded++;
424                         }
425                         vaddr += PAGE_SIZE;
426                 }
427         }
428
429         /* Reserve Necessary Bounce Pages */
430         if (map->pagesneeded != 0) {
431                 int s;
432
433                 s = splhigh();
434                 if (reserve_bounce_pages(dmat, map) != 0) {
435
436                         /* Queue us for resources */
437                         map->dmat = dmat;
438                         map->buf = buf;
439                         map->buflen = buflen;
440                         map->callback = callback;
441                         map->callback_arg = callback_arg;
442
443                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
444                         splx(s);
445
446                         return (EINPROGRESS);
447                 }
448                 splx(s);
449         }
450
451         vaddr = (vm_offset_t)buf;
452         sg = &dm_segments[0];
453         seg = 1;
454         sg->ds_len = 0;
455
456         nextpaddr = 0;
457         do {
458                 bus_size_t      size;
459
460                 paddr = pmap_kextract(vaddr);
461                 size = PAGE_SIZE - (paddr & PAGE_MASK);
462                 if (size > buflen)
463                         size = buflen;
464
465                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
466                         paddr = add_bounce_page(dmat, map, vaddr, size);
467                 }
468
469                 if (sg->ds_len == 0) {
470                         sg->ds_addr = paddr;
471                         sg->ds_len = size;
472                 } else if (paddr == nextpaddr) {
473                         sg->ds_len += size;
474                 } else {
475                         /* Go to the next segment */
476                         sg++;
477                         seg++;
478                         if (seg > dmat->nsegments)
479                                 break;
480                         sg->ds_addr = paddr;
481                         sg->ds_len = size;
482                 }
483                 vaddr += size;
484                 nextpaddr = paddr + size;
485                 buflen -= size;
486
487         } while (buflen > 0);
488
489         if (buflen != 0) {
490                 printf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
491                        (u_long)buflen);
492                 error = EFBIG;
493         }
494
495         (*callback)(callback_arg, dm_segments, seg, error);
496
497         return (0);
498 }
499
500 /*
501  * Utility function to load a linear buffer.  lastaddrp holds state
502  * between invocations (for multiple-buffer loads).  segp contains
503  * the starting segment on entrace, and the ending segment on exit.
504  * first indicates if this is the first invocation of this function.
505  */
506 static int
507 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
508                         bus_dma_segment_t segs[],
509                         void *buf, bus_size_t buflen,
510                         struct thread *td,
511                         int flags,
512                         vm_offset_t *lastaddrp,
513                         int *segp,
514                         int first)
515 {
516         bus_size_t sgsize;
517         bus_addr_t curaddr, lastaddr, baddr, bmask;
518         vm_offset_t vaddr = (vm_offset_t)buf;
519         int seg;
520         pmap_t pmap;
521
522         if (td->td_proc != NULL)
523                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
524         else
525                 pmap = NULL;
526
527         lastaddr = *lastaddrp;
528         bmask  = ~(dmat->boundary - 1);
529
530         for (seg = *segp; buflen > 0 ; ) {
531                 /*
532                  * Get the physical address for this segment.
533                  */
534                 if (pmap)
535                         curaddr = pmap_extract(pmap, vaddr);
536                 else
537                         curaddr = pmap_kextract(vaddr);
538
539                 /*
540                  * Compute the segment size, and adjust counts.
541                  */
542                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
543                 if (buflen < sgsize)
544                         sgsize = buflen;
545
546                 /*
547                  * Make sure we don't cross any boundaries.
548                  */
549                 if (dmat->boundary > 0) {
550                         baddr = (curaddr + dmat->boundary) & bmask;
551                         if (sgsize > (baddr - curaddr))
552                                 sgsize = (baddr - curaddr);
553                 }
554
555                 /*
556                  * Insert chunk into a segment, coalescing with
557                  * previous segment if possible.
558                  */
559                 if (first) {
560                         segs[seg].ds_addr = curaddr;
561                         segs[seg].ds_len = sgsize;
562                         first = 0;
563                 } else {
564                         if (curaddr == lastaddr &&
565                             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
566                             (dmat->boundary == 0 ||
567                              (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
568                                 segs[seg].ds_len += sgsize;
569                         else {
570                                 if (++seg >= dmat->nsegments)
571                                         break;
572                                 segs[seg].ds_addr = curaddr;
573                                 segs[seg].ds_len = sgsize;
574                         }
575                 }
576
577                 lastaddr = curaddr + sgsize;
578                 vaddr += sgsize;
579                 buflen -= sgsize;
580         }
581
582         *segp = seg;
583         *lastaddrp = lastaddr;
584
585         /*
586          * Did we fit?
587          */
588         return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
589 }
590
591 /*
592  * Like _bus_dmamap_load(), but for mbufs.
593  */
594 int
595 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
596                      struct mbuf *m0,
597                      bus_dmamap_callback2_t *callback, void *callback_arg,
598                      int flags)
599 {
600 #ifdef __GNUC__
601         bus_dma_segment_t dm_segments[dmat->nsegments];
602 #else
603         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
604 #endif
605         int nsegs, error;
606
607         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
608                 ("bus_dmamap_load_mbuf: No support for bounce pages!"));
609         KASSERT(m0->m_flags & M_PKTHDR,
610                 ("bus_dmamap_load_mbuf: no packet header"));
611
612         nsegs = 0;
613         error = 0;
614         if (m0->m_pkthdr.len <= dmat->maxsize) {
615                 int first = 1;
616                 vm_offset_t lastaddr = 0;
617                 struct mbuf *m;
618
619                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
620                         error = _bus_dmamap_load_buffer(dmat,
621                                         dm_segments,
622                                         m->m_data, m->m_len,
623                                         curthread, flags, &lastaddr,
624                                         &nsegs, first);
625                         first = 0;
626                 }
627         } else {
628                 error = EINVAL;
629         }
630
631         if (error) {
632                 /* force "no valid mappings" in callback */
633                 (*callback)(callback_arg, dm_segments, 0, 0, error);
634         } else {
635                 (*callback)(callback_arg, dm_segments,
636                             nsegs+1, m0->m_pkthdr.len, error);
637         }
638         return (error);
639 }
640
641 /*
642  * Like _bus_dmamap_load(), but for uios.
643  */
644 int
645 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
646                     struct uio *uio,
647                     bus_dmamap_callback2_t *callback, void *callback_arg,
648                     int flags)
649 {
650         vm_offset_t lastaddr;
651 #ifdef __GNUC__
652         bus_dma_segment_t dm_segments[dmat->nsegments];
653 #else
654         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
655 #endif
656         int nsegs, error, first, i;
657         bus_size_t resid;
658         struct iovec *iov;
659         struct thread *td = NULL;
660
661         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
662                 ("bus_dmamap_load_uio: No support for bounce pages!"));
663
664         resid = uio->uio_resid;
665         iov = uio->uio_iov;
666
667         if (uio->uio_segflg == UIO_USERSPACE) {
668                 td = uio->uio_td;
669                 KASSERT(td != NULL && td->td_proc != NULL,
670                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
671         }
672
673         nsegs = 0;
674         error = 0;
675         first = 1;
676         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
677                 /*
678                  * Now at the first iovec to load.  Load each iovec
679                  * until we have exhausted the residual count.
680                  */
681                 bus_size_t minlen =
682                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
683                 caddr_t addr = (caddr_t) iov[i].iov_base;
684
685                 error = _bus_dmamap_load_buffer(dmat,
686                                 dm_segments,
687                                 addr, minlen,
688                                 td, flags, &lastaddr, &nsegs, first);
689                 first = 0;
690
691                 resid -= minlen;
692         }
693
694         if (error) {
695                 /* force "no valid mappings" in callback */
696                 (*callback)(callback_arg, dm_segments, 0, 0, error);
697         } else {
698                 (*callback)(callback_arg, dm_segments,
699                             nsegs+1, uio->uio_resid, error);
700         }
701         return (error);
702 }
703
704 /*
705  * Release the mapping held by map.
706  */
707 void
708 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
709 {
710         struct bounce_page *bpage;
711
712         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
713                 STAILQ_REMOVE_HEAD(&map->bpages, links);
714                 free_bounce_page(dmat, bpage);
715         }
716 }
717
718 void
719 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
720 {
721         struct bounce_page *bpage;
722
723         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
724                 
725                 /*
726                  * Handle data bouncing.  We might also
727                  * want to add support for invalidating
728                  * the caches on broken hardware
729                  */
730                 switch (op) {
731                 case BUS_DMASYNC_PREWRITE:
732                         while (bpage != NULL) {
733                                 bcopy((void *)bpage->datavaddr,
734                                       (void *)bpage->vaddr,
735                                       bpage->datacount);
736                                 bpage = STAILQ_NEXT(bpage, links);
737                         }
738                         break;
739
740                 case BUS_DMASYNC_POSTREAD:
741                         while (bpage != NULL) {
742                                 bcopy((void *)bpage->vaddr,
743                                       (void *)bpage->datavaddr,
744                                       bpage->datacount);
745                                 bpage = STAILQ_NEXT(bpage, links);
746                         }
747                         break;
748                 case BUS_DMASYNC_PREREAD:
749                 case BUS_DMASYNC_POSTWRITE:
750                         /* No-ops */
751                         break;
752                 }
753         }
754 }
755
756 static int
757 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
758 {
759         int count;
760
761         count = 0;
762         if (total_bpages == 0) {
763                 STAILQ_INIT(&bounce_page_list);
764                 STAILQ_INIT(&bounce_map_waitinglist);
765                 STAILQ_INIT(&bounce_map_callbacklist);
766         }
767         
768         while (numpages > 0) {
769                 struct bounce_page *bpage;
770                 int s;
771
772                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
773                                                      M_NOWAIT);
774
775                 if (bpage == NULL)
776                         break;
777                 bzero(bpage, sizeof(*bpage));
778                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
779                                                          M_NOWAIT, 0ul,
780                                                          dmat->lowaddr,
781                                                          PAGE_SIZE,
782                                                          0);
783                 if (bpage->vaddr == NULL) {
784                         free(bpage, M_DEVBUF);
785                         break;
786                 }
787                 bpage->busaddr = pmap_kextract(bpage->vaddr);
788                 s = splhigh();
789                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
790                 total_bpages++;
791                 free_bpages++;
792                 splx(s);
793                 count++;
794                 numpages--;
795         }
796         return (count);
797 }
798
799 static int
800 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
801 {
802         int pages;
803
804         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
805         free_bpages -= pages;
806         reserved_bpages += pages;
807         map->pagesreserved += pages;
808         pages = map->pagesneeded - map->pagesreserved;
809
810         return (pages);
811 }
812
813 static bus_addr_t
814 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
815                 bus_size_t size)
816 {
817         int s;
818         struct bounce_page *bpage;
819
820         if (map->pagesneeded == 0)
821                 panic("add_bounce_page: map doesn't need any pages");
822         map->pagesneeded--;
823
824         if (map->pagesreserved == 0)
825                 panic("add_bounce_page: map doesn't need any pages");
826         map->pagesreserved--;
827
828         s = splhigh();
829         bpage = STAILQ_FIRST(&bounce_page_list);
830         if (bpage == NULL)
831                 panic("add_bounce_page: free page list is empty");
832
833         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
834         reserved_bpages--;
835         active_bpages++;
836         splx(s);
837
838         bpage->datavaddr = vaddr;
839         bpage->datacount = size;
840         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
841         return (bpage->busaddr);
842 }
843
844 static void
845 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
846 {
847         int s;
848         struct bus_dmamap *map;
849
850         bpage->datavaddr = 0;
851         bpage->datacount = 0;
852
853         s = splhigh();
854         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
855         free_bpages++;
856         active_bpages--;
857         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
858                 if (reserve_bounce_pages(map->dmat, map) == 0) {
859                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
860                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
861                                            map, links);
862                         busdma_swi_pending = 1;
863                         setsoftvm();
864                 }
865         }
866         splx(s);
867 }
868
869 void
870 busdma_swi()
871 {
872         int s;
873         struct bus_dmamap *map;
874
875         s = splhigh();
876         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
877                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
878                 splx(s);
879                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
880                                 map->callback, map->callback_arg, /*flags*/0);
881                 s = splhigh();
882         }
883         splx(s);
884 }