proc->thread stage 4: rework the VFS and DEVICE subsystems to take thread
[dragonfly.git] / sys / platform / pc32 / i386 / busdma_machdep.c
1 /*
2  * Copyright (c) 1997, 1998 Justin T. Gibbs.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.16.2.2 2003/01/23 00:55:27 scottl Exp $
27  * $DragonFly: src/sys/platform/pc32/i386/busdma_machdep.c,v 1.3 2003/06/25 03:55:53 dillon Exp $
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/mbuf.h>
34 #include <sys/uio.h>
35
36 #include <vm/vm.h>
37 #include <vm/vm_page.h>
38
39 /* XXX needed for to access pmap to convert per-proc virtual to physical */
40 #include <sys/proc.h>
41 #include <sys/lock.h>
42 #include <vm/vm_map.h>
43
44 #include <machine/bus.h>
45 #include <machine/md_var.h>
46
47 #define MAX(a,b) (((a) > (b)) ? (a) : (b))
48 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
49 #define MAX_BPAGES 128
50
51 struct bus_dma_tag {
52         bus_dma_tag_t     parent;
53         bus_size_t        alignment;
54         bus_size_t        boundary;
55         bus_addr_t        lowaddr;
56         bus_addr_t        highaddr;
57         bus_dma_filter_t *filter;
58         void             *filterarg;
59         bus_size_t        maxsize;
60         u_int             nsegments;
61         bus_size_t        maxsegsz;
62         int               flags;
63         int               ref_count;
64         int               map_count;
65 };
66
67 struct bounce_page {
68         vm_offset_t     vaddr;          /* kva of bounce buffer */
69         bus_addr_t      busaddr;        /* Physical address */
70         vm_offset_t     datavaddr;      /* kva of client data */
71         bus_size_t      datacount;      /* client data count */
72         STAILQ_ENTRY(bounce_page) links;
73 };
74
75 int busdma_swi_pending;
76
77 static STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
78 static int free_bpages;
79 static int reserved_bpages;
80 static int active_bpages;
81 static int total_bpages;
82 static bus_addr_t bounce_lowaddr = BUS_SPACE_MAXADDR;
83
84 struct bus_dmamap {
85         struct bp_list         bpages;
86         int                    pagesneeded;
87         int                    pagesreserved;
88         bus_dma_tag_t          dmat;
89         void                  *buf;             /* unmapped buffer pointer */
90         bus_size_t             buflen;          /* unmapped buffer length */
91         bus_dmamap_callback_t *callback;
92         void                  *callback_arg;
93         STAILQ_ENTRY(bus_dmamap) links;
94 };
95
96 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
97 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
98 static struct bus_dmamap nobounce_dmamap;
99
100 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
101 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map);
102 static vm_offset_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
103                                    vm_offset_t vaddr, bus_size_t size);
104 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
105 static __inline int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr);
106
107 static __inline int
108 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
109 {
110         int retval;
111
112         retval = 0;
113         do {
114                 if (paddr > dmat->lowaddr
115                  && paddr <= dmat->highaddr
116                  && (dmat->filter == NULL
117                   || (*dmat->filter)(dmat->filterarg, paddr) != 0))
118                         retval = 1;
119
120                 dmat = dmat->parent;            
121         } while (retval == 0 && dmat != NULL);
122         return (retval);
123 }
124
125 #define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
126 /*
127  * Allocate a device specific dma_tag.
128  */
129 int
130 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
131                    bus_size_t boundary, bus_addr_t lowaddr,
132                    bus_addr_t highaddr, bus_dma_filter_t *filter,
133                    void *filterarg, bus_size_t maxsize, int nsegments,
134                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)
135 {
136         bus_dma_tag_t newtag;
137         int error = 0;
138
139         /* Return a NULL tag on failure */
140         *dmat = NULL;
141
142         newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_DEVBUF, M_NOWAIT);
143         if (newtag == NULL)
144                 return (ENOMEM);
145
146         newtag->parent = parent;
147         newtag->alignment = alignment;
148         newtag->boundary = boundary;
149         newtag->lowaddr = trunc_page((vm_offset_t)lowaddr) + (PAGE_SIZE - 1);
150         newtag->highaddr = trunc_page((vm_offset_t)highaddr) + (PAGE_SIZE - 1);
151         newtag->filter = filter;
152         newtag->filterarg = filterarg;
153         newtag->maxsize = maxsize;
154         newtag->nsegments = nsegments;
155         newtag->maxsegsz = maxsegsz;
156         newtag->flags = flags;
157         newtag->ref_count = 1; /* Count ourself */
158         newtag->map_count = 0;
159         
160         /* Take into account any restrictions imposed by our parent tag */
161         if (parent != NULL) {
162                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
163                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
164                 /*
165                  * XXX Not really correct??? Probably need to honor boundary
166                  *     all the way up the inheritence chain.
167                  */
168                 newtag->boundary = MAX(parent->boundary, newtag->boundary);
169                 if (newtag->filter == NULL) {
170                         /*
171                          * Short circuit looking at our parent directly
172                          * since we have encapsulated all of its information
173                          */
174                         newtag->filter = parent->filter;
175                         newtag->filterarg = parent->filterarg;
176                         newtag->parent = parent->parent;
177                 }
178                 if (newtag->parent != NULL) {
179                         parent->ref_count++;
180                 }
181         }
182         
183         if (newtag->lowaddr < ptoa(Maxmem) && (flags & BUS_DMA_ALLOCNOW) != 0) {
184                 /* Must bounce */
185
186                 if (lowaddr > bounce_lowaddr) {
187                         /*
188                          * Go through the pool and kill any pages
189                          * that don't reside below lowaddr.
190                          */
191                         panic("bus_dma_tag_create: page reallocation "
192                               "not implemented");
193                 }
194                 if (ptoa(total_bpages) < maxsize) {
195                         int pages;
196
197                         pages = atop(maxsize) - total_bpages;
198
199                         /* Add pages to our bounce pool */
200                         if (alloc_bounce_pages(newtag, pages) < pages)
201                                 error = ENOMEM;
202                 }
203                 /* Performed initial allocation */
204                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
205         }
206         
207         if (error != 0) {
208                 free(newtag, M_DEVBUF);
209         } else {
210                 *dmat = newtag;
211         }
212         return (error);
213 }
214
215 int
216 bus_dma_tag_destroy(bus_dma_tag_t dmat)
217 {
218         if (dmat != NULL) {
219
220                 if (dmat->map_count != 0)
221                         return (EBUSY);
222
223                 while (dmat != NULL) {
224                         bus_dma_tag_t parent;
225
226                         parent = dmat->parent;
227                         dmat->ref_count--;
228                         if (dmat->ref_count == 0) {
229                                 free(dmat, M_DEVBUF);
230                                 /*
231                                  * Last reference count, so
232                                  * release our reference
233                                  * count on our parent.
234                                  */
235                                 dmat = parent;
236                         } else
237                                 dmat = NULL;
238                 }
239         }
240         return (0);
241 }
242
243 /*
244  * Allocate a handle for mapping from kva/uva/physical
245  * address space into bus device space.
246  */
247 int
248 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
249 {
250         int error;
251
252         error = 0;
253
254         if (dmat->lowaddr < ptoa(Maxmem)) {
255                 /* Must bounce */
256                 int maxpages;
257
258                 *mapp = (bus_dmamap_t)malloc(sizeof(**mapp), M_DEVBUF,
259                                              M_NOWAIT);
260                 if (*mapp == NULL) {
261                         return (ENOMEM);
262                 } else {
263                         /* Initialize the new map */
264                         bzero(*mapp, sizeof(**mapp));
265                         STAILQ_INIT(&((*mapp)->bpages));
266                 }
267                 /*
268                  * Attempt to add pages to our pool on a per-instance
269                  * basis up to a sane limit.
270                  */
271                 maxpages = MIN(MAX_BPAGES, Maxmem - atop(dmat->lowaddr));
272                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
273                  || (dmat->map_count > 0
274                   && total_bpages < maxpages)) {
275                         int pages;
276
277                         if (dmat->lowaddr > bounce_lowaddr) {
278                                 /*
279                                  * Go through the pool and kill any pages
280                                  * that don't reside below lowaddr.
281                                  */
282                                 panic("bus_dmamap_create: page reallocation "
283                                       "not implemented");
284                         }
285                         pages = atop(dmat->maxsize);
286                         pages = MIN(maxpages - total_bpages, pages);
287                         error = alloc_bounce_pages(dmat, pages);
288
289                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
290                                 if (error == 0)
291                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
292                         } else {
293                                 error = 0;
294                         }
295                 }
296         } else {
297                 *mapp = NULL;
298         }
299         if (error == 0)
300                 dmat->map_count++;
301         return (error);
302 }
303
304 /*
305  * Destroy a handle for mapping from kva/uva/physical
306  * address space into bus device space.
307  */
308 int
309 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
310 {
311         if (map != NULL) {
312                 if (STAILQ_FIRST(&map->bpages) != NULL)
313                         return (EBUSY);
314                 free(map, M_DEVBUF);
315         }
316         dmat->map_count--;
317         return (0);
318 }
319
320
321 /*
322  * Allocate a piece of memory that can be efficiently mapped into
323  * bus device space based on the constraints lited in the dma tag.
324  * A dmamap to for use with dmamap_load is also allocated.
325  */
326 int
327 bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
328                  bus_dmamap_t *mapp)
329 {
330         /* If we succeed, no mapping/bouncing will be required */
331         *mapp = NULL;
332
333         if ((dmat->maxsize <= PAGE_SIZE) && dmat->lowaddr >= ptoa(Maxmem)) {
334                 *vaddr = malloc(dmat->maxsize, M_DEVBUF,
335                                 (flags & BUS_DMA_NOWAIT) ? M_NOWAIT : M_WAITOK);
336         } else {
337                 /*
338                  * XXX Use Contigmalloc until it is merged into this facility
339                  *     and handles multi-seg allocations.  Nobody is doing
340                  *     multi-seg allocations yet though.
341                  */
342                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF,
343                     (flags & BUS_DMA_NOWAIT) ? M_NOWAIT : M_WAITOK,
344                     0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
345                     dmat->boundary);
346         }
347         if (*vaddr == NULL)
348                 return (ENOMEM);
349         return (0);
350 }
351
352 /*
353  * Free a piece of memory and it's allociated dmamap, that was allocated
354  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
355  */
356 void
357 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
358 {
359         /*
360          * dmamem does not need to be bounced, so the map should be
361          * NULL
362          */
363         if (map != NULL)
364                 panic("bus_dmamem_free: Invalid map freed\n");
365         if ((dmat->maxsize <= PAGE_SIZE) && dmat->lowaddr >= ptoa(Maxmem))
366                 free(vaddr, M_DEVBUF);
367         else
368                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
369 }
370
371 #define BUS_DMAMAP_NSEGS ((BUS_SPACE_MAXSIZE / PAGE_SIZE) + 1)
372
373 /*
374  * Map the buffer buf into bus space using the dmamap map.
375  */
376 int
377 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
378                 bus_size_t buflen, bus_dmamap_callback_t *callback,
379                 void *callback_arg, int flags)
380 {
381         vm_offset_t             vaddr;
382         vm_offset_t             paddr;
383 #ifdef __GNUC__
384         bus_dma_segment_t       dm_segments[dmat->nsegments];
385 #else
386         bus_dma_segment_t       dm_segments[BUS_DMAMAP_NSEGS];
387 #endif
388         bus_dma_segment_t      *sg;
389         int                     seg;
390         int                     error;
391         vm_offset_t             nextpaddr;
392
393         if (map == NULL)
394                 map = &nobounce_dmamap;
395
396         error = 0;
397         /*
398          * If we are being called during a callback, pagesneeded will
399          * be non-zero, so we can avoid doing the work twice.
400          */
401         if (dmat->lowaddr < ptoa(Maxmem) && map->pagesneeded == 0) {
402                 vm_offset_t     vendaddr;
403
404                 /*
405                  * Count the number of bounce pages
406                  * needed in order to complete this transfer
407                  */
408                 vaddr = trunc_page((vm_offset_t)buf);
409                 vendaddr = (vm_offset_t)buf + buflen;
410
411                 while (vaddr < vendaddr) {
412                         paddr = pmap_kextract(vaddr);
413                         if (run_filter(dmat, paddr) != 0) {
414
415                                 map->pagesneeded++;
416                         }
417                         vaddr += PAGE_SIZE;
418                 }
419         }
420
421         /* Reserve Necessary Bounce Pages */
422         if (map->pagesneeded != 0) {
423                 int s;
424
425                 s = splhigh();
426                 if (reserve_bounce_pages(dmat, map) != 0) {
427
428                         /* Queue us for resources */
429                         map->dmat = dmat;
430                         map->buf = buf;
431                         map->buflen = buflen;
432                         map->callback = callback;
433                         map->callback_arg = callback_arg;
434
435                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
436                         splx(s);
437
438                         return (EINPROGRESS);
439                 }
440                 splx(s);
441         }
442
443         vaddr = (vm_offset_t)buf;
444         sg = &dm_segments[0];
445         seg = 1;
446         sg->ds_len = 0;
447
448         nextpaddr = 0;
449         do {
450                 bus_size_t      size;
451
452                 paddr = pmap_kextract(vaddr);
453                 size = PAGE_SIZE - (paddr & PAGE_MASK);
454                 if (size > buflen)
455                         size = buflen;
456
457                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
458                         paddr = add_bounce_page(dmat, map, vaddr, size);
459                 }
460
461                 if (sg->ds_len == 0) {
462                         sg->ds_addr = paddr;
463                         sg->ds_len = size;
464                 } else if (paddr == nextpaddr) {
465                         sg->ds_len += size;
466                 } else {
467                         /* Go to the next segment */
468                         sg++;
469                         seg++;
470                         if (seg > dmat->nsegments)
471                                 break;
472                         sg->ds_addr = paddr;
473                         sg->ds_len = size;
474                 }
475                 vaddr += size;
476                 nextpaddr = paddr + size;
477                 buflen -= size;
478
479         } while (buflen > 0);
480
481         if (buflen != 0) {
482                 printf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
483                        (u_long)buflen);
484                 error = EFBIG;
485         }
486
487         (*callback)(callback_arg, dm_segments, seg, error);
488
489         return (0);
490 }
491
492 /*
493  * Utility function to load a linear buffer.  lastaddrp holds state
494  * between invocations (for multiple-buffer loads).  segp contains
495  * the starting segment on entrace, and the ending segment on exit.
496  * first indicates if this is the first invocation of this function.
497  */
498 static int
499 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
500                         bus_dma_segment_t segs[],
501                         void *buf, bus_size_t buflen,
502                         struct thread *td,
503                         int flags,
504                         vm_offset_t *lastaddrp,
505                         int *segp,
506                         int first)
507 {
508         bus_size_t sgsize;
509         bus_addr_t curaddr, lastaddr, baddr, bmask;
510         vm_offset_t vaddr = (vm_offset_t)buf;
511         int seg;
512         pmap_t pmap;
513
514         if (td->td_proc != NULL)
515                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
516         else
517                 pmap = NULL;
518
519         lastaddr = *lastaddrp;
520         bmask  = ~(dmat->boundary - 1);
521
522         for (seg = *segp; buflen > 0 ; ) {
523                 /*
524                  * Get the physical address for this segment.
525                  */
526                 if (pmap)
527                         curaddr = pmap_extract(pmap, vaddr);
528                 else
529                         curaddr = pmap_kextract(vaddr);
530
531                 /*
532                  * Compute the segment size, and adjust counts.
533                  */
534                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
535                 if (buflen < sgsize)
536                         sgsize = buflen;
537
538                 /*
539                  * Make sure we don't cross any boundaries.
540                  */
541                 if (dmat->boundary > 0) {
542                         baddr = (curaddr + dmat->boundary) & bmask;
543                         if (sgsize > (baddr - curaddr))
544                                 sgsize = (baddr - curaddr);
545                 }
546
547                 /*
548                  * Insert chunk into a segment, coalescing with
549                  * previous segment if possible.
550                  */
551                 if (first) {
552                         segs[seg].ds_addr = curaddr;
553                         segs[seg].ds_len = sgsize;
554                         first = 0;
555                 } else {
556                         if (curaddr == lastaddr &&
557                             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
558                             (dmat->boundary == 0 ||
559                              (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
560                                 segs[seg].ds_len += sgsize;
561                         else {
562                                 if (++seg >= dmat->nsegments)
563                                         break;
564                                 segs[seg].ds_addr = curaddr;
565                                 segs[seg].ds_len = sgsize;
566                         }
567                 }
568
569                 lastaddr = curaddr + sgsize;
570                 vaddr += sgsize;
571                 buflen -= sgsize;
572         }
573
574         *segp = seg;
575         *lastaddrp = lastaddr;
576
577         /*
578          * Did we fit?
579          */
580         return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
581 }
582
583 /*
584  * Like _bus_dmamap_load(), but for mbufs.
585  */
586 int
587 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
588                      struct mbuf *m0,
589                      bus_dmamap_callback2_t *callback, void *callback_arg,
590                      int flags)
591 {
592 #ifdef __GNUC__
593         bus_dma_segment_t dm_segments[dmat->nsegments];
594 #else
595         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
596 #endif
597         int nsegs, error;
598
599         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
600                 ("bus_dmamap_load_mbuf: No support for bounce pages!"));
601         KASSERT(m0->m_flags & M_PKTHDR,
602                 ("bus_dmamap_load_mbuf: no packet header"));
603
604         nsegs = 0;
605         error = 0;
606         if (m0->m_pkthdr.len <= dmat->maxsize) {
607                 int first = 1;
608                 vm_offset_t lastaddr = 0;
609                 struct mbuf *m;
610
611                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
612                         error = _bus_dmamap_load_buffer(dmat,
613                                         dm_segments,
614                                         m->m_data, m->m_len,
615                                         NULL, flags, &lastaddr, &nsegs, first);
616                         first = 0;
617                 }
618         } else {
619                 error = EINVAL;
620         }
621
622         if (error) {
623                 /* force "no valid mappings" in callback */
624                 (*callback)(callback_arg, dm_segments, 0, 0, error);
625         } else {
626                 (*callback)(callback_arg, dm_segments,
627                             nsegs+1, m0->m_pkthdr.len, error);
628         }
629         return (error);
630 }
631
632 /*
633  * Like _bus_dmamap_load(), but for uios.
634  */
635 int
636 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
637                     struct uio *uio,
638                     bus_dmamap_callback2_t *callback, void *callback_arg,
639                     int flags)
640 {
641         vm_offset_t lastaddr;
642 #ifdef __GNUC__
643         bus_dma_segment_t dm_segments[dmat->nsegments];
644 #else
645         bus_dma_segment_t dm_segments[BUS_DMAMAP_NSEGS];
646 #endif
647         int nsegs, error, first, i;
648         bus_size_t resid;
649         struct iovec *iov;
650         struct thread *td = NULL;
651
652         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
653                 ("bus_dmamap_load_uio: No support for bounce pages!"));
654
655         resid = uio->uio_resid;
656         iov = uio->uio_iov;
657
658         if (uio->uio_segflg == UIO_USERSPACE) {
659                 td = uio->uio_td;
660                 KASSERT(td != NULL && td->td_proc != NULL,
661                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
662         }
663
664         nsegs = 0;
665         error = 0;
666         first = 1;
667         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
668                 /*
669                  * Now at the first iovec to load.  Load each iovec
670                  * until we have exhausted the residual count.
671                  */
672                 bus_size_t minlen =
673                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
674                 caddr_t addr = (caddr_t) iov[i].iov_base;
675
676                 error = _bus_dmamap_load_buffer(dmat,
677                                 dm_segments,
678                                 addr, minlen,
679                                 td, flags, &lastaddr, &nsegs, first);
680                 first = 0;
681
682                 resid -= minlen;
683         }
684
685         if (error) {
686                 /* force "no valid mappings" in callback */
687                 (*callback)(callback_arg, dm_segments, 0, 0, error);
688         } else {
689                 (*callback)(callback_arg, dm_segments,
690                             nsegs+1, uio->uio_resid, error);
691         }
692         return (error);
693 }
694
695 /*
696  * Release the mapping held by map.
697  */
698 void
699 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
700 {
701         struct bounce_page *bpage;
702
703         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
704                 STAILQ_REMOVE_HEAD(&map->bpages, links);
705                 free_bounce_page(dmat, bpage);
706         }
707 }
708
709 void
710 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
711 {
712         struct bounce_page *bpage;
713
714         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
715                 
716                 /*
717                  * Handle data bouncing.  We might also
718                  * want to add support for invalidating
719                  * the caches on broken hardware
720                  */
721                 switch (op) {
722                 case BUS_DMASYNC_PREWRITE:
723                         while (bpage != NULL) {
724                                 bcopy((void *)bpage->datavaddr,
725                                       (void *)bpage->vaddr,
726                                       bpage->datacount);
727                                 bpage = STAILQ_NEXT(bpage, links);
728                         }
729                         break;
730
731                 case BUS_DMASYNC_POSTREAD:
732                         while (bpage != NULL) {
733                                 bcopy((void *)bpage->vaddr,
734                                       (void *)bpage->datavaddr,
735                                       bpage->datacount);
736                                 bpage = STAILQ_NEXT(bpage, links);
737                         }
738                         break;
739                 case BUS_DMASYNC_PREREAD:
740                 case BUS_DMASYNC_POSTWRITE:
741                         /* No-ops */
742                         break;
743                 }
744         }
745 }
746
747 static int
748 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
749 {
750         int count;
751
752         count = 0;
753         if (total_bpages == 0) {
754                 STAILQ_INIT(&bounce_page_list);
755                 STAILQ_INIT(&bounce_map_waitinglist);
756                 STAILQ_INIT(&bounce_map_callbacklist);
757         }
758         
759         while (numpages > 0) {
760                 struct bounce_page *bpage;
761                 int s;
762
763                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
764                                                      M_NOWAIT);
765
766                 if (bpage == NULL)
767                         break;
768                 bzero(bpage, sizeof(*bpage));
769                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
770                                                          M_NOWAIT, 0ul,
771                                                          dmat->lowaddr,
772                                                          PAGE_SIZE,
773                                                          0);
774                 if (bpage->vaddr == NULL) {
775                         free(bpage, M_DEVBUF);
776                         break;
777                 }
778                 bpage->busaddr = pmap_kextract(bpage->vaddr);
779                 s = splhigh();
780                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
781                 total_bpages++;
782                 free_bpages++;
783                 splx(s);
784                 count++;
785                 numpages--;
786         }
787         return (count);
788 }
789
790 static int
791 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
792 {
793         int pages;
794
795         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
796         free_bpages -= pages;
797         reserved_bpages += pages;
798         map->pagesreserved += pages;
799         pages = map->pagesneeded - map->pagesreserved;
800
801         return (pages);
802 }
803
804 static vm_offset_t
805 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
806                 bus_size_t size)
807 {
808         int s;
809         struct bounce_page *bpage;
810
811         if (map->pagesneeded == 0)
812                 panic("add_bounce_page: map doesn't need any pages");
813         map->pagesneeded--;
814
815         if (map->pagesreserved == 0)
816                 panic("add_bounce_page: map doesn't need any pages");
817         map->pagesreserved--;
818
819         s = splhigh();
820         bpage = STAILQ_FIRST(&bounce_page_list);
821         if (bpage == NULL)
822                 panic("add_bounce_page: free page list is empty");
823
824         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
825         reserved_bpages--;
826         active_bpages++;
827         splx(s);
828
829         bpage->datavaddr = vaddr;
830         bpage->datacount = size;
831         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
832         return (bpage->busaddr);
833 }
834
835 static void
836 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
837 {
838         int s;
839         struct bus_dmamap *map;
840
841         bpage->datavaddr = 0;
842         bpage->datacount = 0;
843
844         s = splhigh();
845         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
846         free_bpages++;
847         active_bpages--;
848         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
849                 if (reserve_bounce_pages(map->dmat, map) == 0) {
850                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
851                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
852                                            map, links);
853                         busdma_swi_pending = 1;
854                         setsoftvm();
855                 }
856         }
857         splx(s);
858 }
859
860 void
861 busdma_swi()
862 {
863         int s;
864         struct bus_dmamap *map;
865
866         s = splhigh();
867         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
868                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
869                 splx(s);
870                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
871                                 map->callback, map->callback_arg, /*flags*/0);
872                 s = splhigh();
873         }
874         splx(s);
875 }