Merge from vendor branch GCC:
[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.12 2005/01/18 14:02:05 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 = 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  *
331  * mapp is degenerate.  By definition this allocation should not require
332  * bounce buffers so do not allocate a dma map.
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 (dmat->segments == NULL) {
343                 KKASSERT(dmat->nsegments < 16384);
344                 dmat->segments = malloc(sizeof(bus_dma_segment_t) * 
345                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
346         }
347
348         if (flags & BUS_DMA_NOWAIT)
349                 mflags = M_NOWAIT;
350         else
351                 mflags = M_WAITOK;
352         if (flags & BUS_DMA_ZERO)
353                 mflags |= M_ZERO;
354
355         if ((dmat->maxsize <= PAGE_SIZE) &&
356             dmat->lowaddr >= ptoa(Maxmem)) {
357                 *vaddr = malloc(dmat->maxsize, M_DEVBUF, mflags);
358                 /*
359                  * XXX Check whether the allocation crossed a page boundary
360                  * and retry with power-of-2 alignment in that case.
361                  */
362                 if ((((intptr_t)*vaddr) & PAGE_MASK) !=
363                     (((intptr_t)*vaddr + dmat->maxsize) & PAGE_MASK)) {
364                         size_t size;
365                         free(*vaddr, M_DEVBUF);
366                         /* XXX check for overflow? */
367                         for (size = 1; size <= dmat->maxsize; size <<= 1)
368                                 ;
369                         *vaddr = malloc(size, M_DEVBUF, mflags);
370                 }
371         } else {
372                 /*
373                  * XXX Use Contigmalloc until it is merged into this facility
374                  *     and handles multi-seg allocations.  Nobody is doing
375                  *     multi-seg allocations yet though.
376                  */
377                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
378                     0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
379                     dmat->boundary);
380         }
381         if (*vaddr == NULL)
382                 return (ENOMEM);
383         return (0);
384 }
385
386 /*
387  * Free a piece of memory and it's allociated dmamap, that was allocated
388  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
389  */
390 void
391 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
392 {
393         /*
394          * dmamem does not need to be bounced, so the map should be
395          * NULL
396          */
397         if (map != NULL)
398                 panic("bus_dmamem_free: Invalid map freed\n");
399         if ((dmat->maxsize <= PAGE_SIZE) &&
400             dmat->lowaddr >= ptoa(Maxmem))
401                 free(vaddr, M_DEVBUF);
402         else
403                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
404 }
405
406 #define BUS_DMAMAP_NSEGS ((BUS_SPACE_MAXSIZE / PAGE_SIZE) + 1)
407
408 /*
409  * Map the buffer buf into bus space using the dmamap map.
410  */
411 int
412 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
413                 bus_size_t buflen, bus_dmamap_callback_t *callback,
414                 void *callback_arg, int flags)
415 {
416         vm_offset_t             vaddr;
417         vm_paddr_t              paddr;
418         bus_dma_segment_t      *sg;
419         int                     seg;
420         int                     error;
421         vm_paddr_t              nextpaddr;
422
423         if (map == NULL)
424                 map = &nobounce_dmamap;
425
426         error = 0;
427         /*
428          * If we are being called during a callback, pagesneeded will
429          * be non-zero, so we can avoid doing the work twice.
430          */
431         if (dmat->lowaddr < ptoa(Maxmem) &&
432             map->pagesneeded == 0) {
433                 vm_offset_t     vendaddr;
434
435                 /*
436                  * Count the number of bounce pages
437                  * needed in order to complete this transfer
438                  */
439                 vaddr = trunc_page((vm_offset_t)buf);
440                 vendaddr = (vm_offset_t)buf + buflen;
441
442                 while (vaddr < vendaddr) {
443                         paddr = pmap_kextract(vaddr);
444                         if (run_filter(dmat, paddr) != 0) {
445
446                                 map->pagesneeded++;
447                         }
448                         vaddr += PAGE_SIZE;
449                 }
450         }
451
452         /* Reserve Necessary Bounce Pages */
453         if (map->pagesneeded != 0) {
454                 int s;
455
456                 s = splhigh();
457                 if (reserve_bounce_pages(dmat, map) != 0) {
458
459                         /* Queue us for resources */
460                         map->dmat = dmat;
461                         map->buf = buf;
462                         map->buflen = buflen;
463                         map->callback = callback;
464                         map->callback_arg = callback_arg;
465
466                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
467                         splx(s);
468
469                         return (EINPROGRESS);
470                 }
471                 splx(s);
472         }
473
474         vaddr = (vm_offset_t)buf;
475         sg = dmat->segments;
476         seg = 1;
477         sg->ds_len = 0;
478
479         nextpaddr = 0;
480         do {
481                 bus_size_t      size;
482
483                 paddr = pmap_kextract(vaddr);
484                 size = PAGE_SIZE - (paddr & PAGE_MASK);
485                 if (size > buflen)
486                         size = buflen;
487
488                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
489                         paddr = add_bounce_page(dmat, map, vaddr, size);
490                 }
491
492                 if (sg->ds_len == 0) {
493                         sg->ds_addr = paddr;
494                         sg->ds_len = size;
495                 } else if (paddr == nextpaddr) {
496                         sg->ds_len += size;
497                 } else {
498                         /* Go to the next segment */
499                         sg++;
500                         seg++;
501                         if (seg > dmat->nsegments)
502                                 break;
503                         sg->ds_addr = paddr;
504                         sg->ds_len = size;
505                 }
506                 vaddr += size;
507                 nextpaddr = paddr + size;
508                 buflen -= size;
509         } while (buflen > 0);
510
511         if (buflen != 0) {
512                 printf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
513                        (u_long)buflen);
514                 error = EFBIG;
515         }
516
517         (*callback)(callback_arg, dmat->segments, seg, error);
518
519         return (0);
520 }
521
522 /*
523  * Utility function to load a linear buffer.  lastaddrp holds state
524  * between invocations (for multiple-buffer loads).  segp contains
525  * the starting segment on entrace, and the ending segment on exit.
526  * first indicates if this is the first invocation of this function.
527  */
528 static int
529 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
530                         void *buf, bus_size_t buflen,
531                         struct thread *td,
532                         int flags,
533                         vm_offset_t *lastaddrp,
534                         int *segp,
535                         int first)
536 {
537         bus_dma_segment_t *segs;
538         bus_size_t sgsize;
539         bus_addr_t curaddr, lastaddr, baddr, bmask;
540         vm_offset_t vaddr = (vm_offset_t)buf;
541         int seg;
542         pmap_t pmap;
543
544         if (td->td_proc != NULL)
545                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
546         else
547                 pmap = NULL;
548
549         segs = dmat->segments;
550         lastaddr = *lastaddrp;
551         bmask  = ~(dmat->boundary - 1);
552
553         for (seg = *segp; buflen > 0 ; ) {
554                 /*
555                  * Get the physical address for this segment.
556                  */
557                 if (pmap)
558                         curaddr = pmap_extract(pmap, vaddr);
559                 else
560                         curaddr = pmap_kextract(vaddr);
561
562                 /*
563                  * Compute the segment size, and adjust counts.
564                  */
565                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
566                 if (buflen < sgsize)
567                         sgsize = buflen;
568
569                 /*
570                  * Make sure we don't cross any boundaries.
571                  */
572                 if (dmat->boundary > 0) {
573                         baddr = (curaddr + dmat->boundary) & bmask;
574                         if (sgsize > (baddr - curaddr))
575                                 sgsize = (baddr - curaddr);
576                 }
577
578                 /*
579                  * Insert chunk into a segment, coalescing with
580                  * previous segment if possible.
581                  */
582                 if (first) {
583                         segs[seg].ds_addr = curaddr;
584                         segs[seg].ds_len = sgsize;
585                         first = 0;
586                 } else {
587                         if (curaddr == lastaddr &&
588                             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
589                             (dmat->boundary == 0 ||
590                              (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
591                                 segs[seg].ds_len += sgsize;
592                         else {
593                                 if (++seg >= dmat->nsegments)
594                                         break;
595                                 segs[seg].ds_addr = curaddr;
596                                 segs[seg].ds_len = sgsize;
597                         }
598                 }
599
600                 lastaddr = curaddr + sgsize;
601                 vaddr += sgsize;
602                 buflen -= sgsize;
603         }
604
605         *segp = seg;
606         *lastaddrp = lastaddr;
607
608         /*
609          * Did we fit?
610          */
611         return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
612 }
613
614 /*
615  * Like _bus_dmamap_load(), but for mbufs.
616  */
617 int
618 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
619                      struct mbuf *m0,
620                      bus_dmamap_callback2_t *callback, void *callback_arg,
621                      int flags)
622 {
623         int nsegs, error;
624
625         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
626                 ("bus_dmamap_load_mbuf: No support for bounce pages!"));
627         KASSERT(m0->m_flags & M_PKTHDR,
628                 ("bus_dmamap_load_mbuf: no packet header"));
629
630         nsegs = 0;
631         error = 0;
632         if (m0->m_pkthdr.len <= dmat->maxsize) {
633                 int first = 1;
634                 vm_offset_t lastaddr = 0;
635                 struct mbuf *m;
636
637                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
638                         if ( m->m_len == 0 )
639                                 continue;
640                         error = _bus_dmamap_load_buffer(dmat,
641                                         m->m_data, m->m_len,
642                                         curthread, flags, &lastaddr,
643                                         &nsegs, first);
644                         first = 0;
645                 }
646         } else {
647                 error = EINVAL;
648         }
649
650         if (error) {
651                 /* force "no valid mappings" in callback */
652                 (*callback)(callback_arg, dmat->segments, 0, 0, error);
653         } else {
654                 (*callback)(callback_arg, dmat->segments,
655                             nsegs+1, m0->m_pkthdr.len, error);
656         }
657         return (error);
658 }
659
660 /*
661  * Like _bus_dmamap_load(), but for uios.
662  */
663 int
664 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
665                     struct uio *uio,
666                     bus_dmamap_callback2_t *callback, void *callback_arg,
667                     int flags)
668 {
669         vm_offset_t lastaddr;
670         int nsegs, error, first, i;
671         bus_size_t resid;
672         struct iovec *iov;
673         struct thread *td = NULL;
674
675         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
676                 ("bus_dmamap_load_uio: No support for bounce pages!"));
677
678         resid = uio->uio_resid;
679         iov = uio->uio_iov;
680
681         if (uio->uio_segflg == UIO_USERSPACE) {
682                 td = uio->uio_td;
683                 KASSERT(td != NULL && td->td_proc != NULL,
684                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
685         }
686
687         nsegs = 0;
688         error = 0;
689         first = 1;
690         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
691                 /*
692                  * Now at the first iovec to load.  Load each iovec
693                  * until we have exhausted the residual count.
694                  */
695                 bus_size_t minlen =
696                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
697                 caddr_t addr = (caddr_t) iov[i].iov_base;
698
699                 error = _bus_dmamap_load_buffer(dmat,
700                                 addr, minlen,
701                                 td, flags, &lastaddr, &nsegs, first);
702                 first = 0;
703
704                 resid -= minlen;
705         }
706
707         if (error) {
708                 /* force "no valid mappings" in callback */
709                 (*callback)(callback_arg, dmat->segments, 0, 0, error);
710         } else {
711                 (*callback)(callback_arg, dmat->segments,
712                             nsegs+1, uio->uio_resid, error);
713         }
714         return (error);
715 }
716
717 /*
718  * Release the mapping held by map.
719  */
720 void
721 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
722 {
723         struct bounce_page *bpage;
724
725         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
726                 STAILQ_REMOVE_HEAD(&map->bpages, links);
727                 free_bounce_page(dmat, bpage);
728         }
729 }
730
731 void
732 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
733 {
734         struct bounce_page *bpage;
735
736         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
737                 
738                 /*
739                  * Handle data bouncing.  We might also
740                  * want to add support for invalidating
741                  * the caches on broken hardware
742                  */
743                 switch (op) {
744                 case BUS_DMASYNC_PREWRITE:
745                         while (bpage != NULL) {
746                                 bcopy((void *)bpage->datavaddr,
747                                       (void *)bpage->vaddr,
748                                       bpage->datacount);
749                                 bpage = STAILQ_NEXT(bpage, links);
750                         }
751                         break;
752
753                 case BUS_DMASYNC_POSTREAD:
754                         while (bpage != NULL) {
755                                 bcopy((void *)bpage->vaddr,
756                                       (void *)bpage->datavaddr,
757                                       bpage->datacount);
758                                 bpage = STAILQ_NEXT(bpage, links);
759                         }
760                         break;
761                 case BUS_DMASYNC_PREREAD:
762                 case BUS_DMASYNC_POSTWRITE:
763                         /* No-ops */
764                         break;
765                 }
766         }
767 }
768
769 static int
770 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
771 {
772         int count;
773
774         count = 0;
775         if (total_bpages == 0) {
776                 STAILQ_INIT(&bounce_page_list);
777                 STAILQ_INIT(&bounce_map_waitinglist);
778                 STAILQ_INIT(&bounce_map_callbacklist);
779         }
780         
781         while (numpages > 0) {
782                 struct bounce_page *bpage;
783                 int s;
784
785                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
786                                                      M_INTWAIT);
787
788                 if (bpage == NULL)
789                         break;
790                 bzero(bpage, sizeof(*bpage));
791                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
792                                                          M_NOWAIT, 0ul,
793                                                          dmat->lowaddr,
794                                                          PAGE_SIZE,
795                                                          0);
796                 if (bpage->vaddr == NULL) {
797                         free(bpage, M_DEVBUF);
798                         break;
799                 }
800                 bpage->busaddr = pmap_kextract(bpage->vaddr);
801                 s = splhigh();
802                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
803                 total_bpages++;
804                 free_bpages++;
805                 splx(s);
806                 count++;
807                 numpages--;
808         }
809         return (count);
810 }
811
812 static int
813 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
814 {
815         int pages;
816
817         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
818         free_bpages -= pages;
819         reserved_bpages += pages;
820         map->pagesreserved += pages;
821         pages = map->pagesneeded - map->pagesreserved;
822
823         return (pages);
824 }
825
826 static bus_addr_t
827 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
828                 bus_size_t size)
829 {
830         int s;
831         struct bounce_page *bpage;
832
833         if (map->pagesneeded == 0)
834                 panic("add_bounce_page: map doesn't need any pages");
835         map->pagesneeded--;
836
837         if (map->pagesreserved == 0)
838                 panic("add_bounce_page: map doesn't need any pages");
839         map->pagesreserved--;
840
841         s = splhigh();
842         bpage = STAILQ_FIRST(&bounce_page_list);
843         if (bpage == NULL)
844                 panic("add_bounce_page: free page list is empty");
845
846         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
847         reserved_bpages--;
848         active_bpages++;
849         splx(s);
850
851         bpage->datavaddr = vaddr;
852         bpage->datacount = size;
853         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
854         return (bpage->busaddr);
855 }
856
857 static void
858 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
859 {
860         int s;
861         struct bus_dmamap *map;
862
863         bpage->datavaddr = 0;
864         bpage->datacount = 0;
865
866         s = splhigh();
867         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
868         free_bpages++;
869         active_bpages--;
870         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
871                 if (reserve_bounce_pages(map->dmat, map) == 0) {
872                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
873                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
874                                            map, links);
875                         busdma_swi_pending = 1;
876                         setsoftvm();
877                 }
878         }
879         splx(s);
880 }
881
882 void
883 busdma_swi()
884 {
885         int s;
886         struct bus_dmamap *map;
887
888         s = splhigh();
889         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
890                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
891                 splx(s);
892                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
893                                 map->callback, map->callback_arg, /*flags*/0);
894                 s = splhigh();
895         }
896         splx(s);
897 }