64 bit address space cleanups which are a prerequisit for future 64 bit
[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.5 2003/11/03 17:11:18 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                                         NULL, flags, &lastaddr, &nsegs, first);
618                         first = 0;
619                 }
620         } else {
621                 error = EINVAL;
622         }
623
624         if (error) {
625                 /* force "no valid mappings" in callback */
626                 (*callback)(callback_arg, dm_segments, 0, 0, error);
627         } else {
628                 (*callback)(callback_arg, dm_segments,
629                             nsegs+1, m0->m_pkthdr.len, error);
630         }
631         return (error);
632 }
633
634 /*
635  * Like _bus_dmamap_load(), but for uios.
636  */
637 int
638 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
639                     struct uio *uio,
640                     bus_dmamap_callback2_t *callback, void *callback_arg,
641                     int flags)
642 {
643         vm_offset_t lastaddr;
644 #ifdef __GNUC__
645         bus_dma_segment_t dm_segments[dmat->nsegments];
646 #else
647         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
648 #endif
649         int nsegs, error, first, i;
650         bus_size_t resid;
651         struct iovec *iov;
652         struct thread *td = NULL;
653
654         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
655                 ("bus_dmamap_load_uio: No support for bounce pages!"));
656
657         resid = uio->uio_resid;
658         iov = uio->uio_iov;
659
660         if (uio->uio_segflg == UIO_USERSPACE) {
661                 td = uio->uio_td;
662                 KASSERT(td != NULL && td->td_proc != NULL,
663                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
664         }
665
666         nsegs = 0;
667         error = 0;
668         first = 1;
669         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
670                 /*
671                  * Now at the first iovec to load.  Load each iovec
672                  * until we have exhausted the residual count.
673                  */
674                 bus_size_t minlen =
675                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
676                 caddr_t addr = (caddr_t) iov[i].iov_base;
677
678                 error = _bus_dmamap_load_buffer(dmat,
679                                 dm_segments,
680                                 addr, minlen,
681                                 td, flags, &lastaddr, &nsegs, first);
682                 first = 0;
683
684                 resid -= minlen;
685         }
686
687         if (error) {
688                 /* force "no valid mappings" in callback */
689                 (*callback)(callback_arg, dm_segments, 0, 0, error);
690         } else {
691                 (*callback)(callback_arg, dm_segments,
692                             nsegs+1, uio->uio_resid, error);
693         }
694         return (error);
695 }
696
697 /*
698  * Release the mapping held by map.
699  */
700 void
701 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
702 {
703         struct bounce_page *bpage;
704
705         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
706                 STAILQ_REMOVE_HEAD(&map->bpages, links);
707                 free_bounce_page(dmat, bpage);
708         }
709 }
710
711 void
712 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
713 {
714         struct bounce_page *bpage;
715
716         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
717                 
718                 /*
719                  * Handle data bouncing.  We might also
720                  * want to add support for invalidating
721                  * the caches on broken hardware
722                  */
723                 switch (op) {
724                 case BUS_DMASYNC_PREWRITE:
725                         while (bpage != NULL) {
726                                 bcopy((void *)bpage->datavaddr,
727                                       (void *)bpage->vaddr,
728                                       bpage->datacount);
729                                 bpage = STAILQ_NEXT(bpage, links);
730                         }
731                         break;
732
733                 case BUS_DMASYNC_POSTREAD:
734                         while (bpage != NULL) {
735                                 bcopy((void *)bpage->vaddr,
736                                       (void *)bpage->datavaddr,
737                                       bpage->datacount);
738                                 bpage = STAILQ_NEXT(bpage, links);
739                         }
740                         break;
741                 case BUS_DMASYNC_PREREAD:
742                 case BUS_DMASYNC_POSTWRITE:
743                         /* No-ops */
744                         break;
745                 }
746         }
747 }
748
749 static int
750 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
751 {
752         int count;
753
754         count = 0;
755         if (total_bpages == 0) {
756                 STAILQ_INIT(&bounce_page_list);
757                 STAILQ_INIT(&bounce_map_waitinglist);
758                 STAILQ_INIT(&bounce_map_callbacklist);
759         }
760         
761         while (numpages > 0) {
762                 struct bounce_page *bpage;
763                 int s;
764
765                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
766                                                      M_NOWAIT);
767
768                 if (bpage == NULL)
769                         break;
770                 bzero(bpage, sizeof(*bpage));
771                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
772                                                          M_NOWAIT, 0ul,
773                                                          dmat->lowaddr,
774                                                          PAGE_SIZE,
775                                                          0);
776                 if (bpage->vaddr == NULL) {
777                         free(bpage, M_DEVBUF);
778                         break;
779                 }
780                 bpage->busaddr = pmap_kextract(bpage->vaddr);
781                 s = splhigh();
782                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
783                 total_bpages++;
784                 free_bpages++;
785                 splx(s);
786                 count++;
787                 numpages--;
788         }
789         return (count);
790 }
791
792 static int
793 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
794 {
795         int pages;
796
797         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
798         free_bpages -= pages;
799         reserved_bpages += pages;
800         map->pagesreserved += pages;
801         pages = map->pagesneeded - map->pagesreserved;
802
803         return (pages);
804 }
805
806 static bus_addr_t
807 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
808                 bus_size_t size)
809 {
810         int s;
811         struct bounce_page *bpage;
812
813         if (map->pagesneeded == 0)
814                 panic("add_bounce_page: map doesn't need any pages");
815         map->pagesneeded--;
816
817         if (map->pagesreserved == 0)
818                 panic("add_bounce_page: map doesn't need any pages");
819         map->pagesreserved--;
820
821         s = splhigh();
822         bpage = STAILQ_FIRST(&bounce_page_list);
823         if (bpage == NULL)
824                 panic("add_bounce_page: free page list is empty");
825
826         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
827         reserved_bpages--;
828         active_bpages++;
829         splx(s);
830
831         bpage->datavaddr = vaddr;
832         bpage->datacount = size;
833         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
834         return (bpage->busaddr);
835 }
836
837 static void
838 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
839 {
840         int s;
841         struct bus_dmamap *map;
842
843         bpage->datavaddr = 0;
844         bpage->datacount = 0;
845
846         s = splhigh();
847         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
848         free_bpages++;
849         active_bpages--;
850         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
851                 if (reserve_bounce_pages(map->dmat, map) == 0) {
852                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
853                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
854                                            map, links);
855                         busdma_swi_pending = 1;
856                         setsoftvm();
857                 }
858         }
859         splx(s);
860 }
861
862 void
863 busdma_swi()
864 {
865         int s;
866         struct bus_dmamap *map;
867
868         s = splhigh();
869         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
870                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
871                 splx(s);
872                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
873                                 map->callback, map->callback_arg, /*flags*/0);
874                 s = splhigh();
875         }
876         splx(s);
877 }