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