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