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