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