For kmalloc(), MALLOC() and contigmalloc(), use M_ZERO instead of
[games.git] / sys / platform / pc64 / amd64 / 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/pc64/amd64/busdma_machdep.c,v 1.3 2008/01/05 14:02:41 swildner 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 #include <sys/thread2.h>
36 #include <sys/bus_dma.h>
37
38 #include <vm/vm.h>
39 #include <vm/vm_page.h>
40
41 /* XXX needed for to access pmap to convert per-proc virtual to physical */
42 #include <sys/proc.h>
43 #include <sys/lock.h>
44 #include <vm/vm_map.h>
45
46 #include <machine/md_var.h>
47
48 #define MAX_BPAGES 128
49
50 struct bus_dma_tag {
51         bus_dma_tag_t     parent;
52         bus_size_t        alignment;
53         bus_size_t        boundary;
54         bus_addr_t        lowaddr;
55         bus_addr_t        highaddr;
56         bus_dma_filter_t *filter;
57         void             *filterarg;
58         bus_size_t        maxsize;
59         u_int             nsegments;
60         bus_size_t        maxsegsz;
61         int               flags;
62         int               ref_count;
63         int               map_count;
64         bus_dma_segment_t *segments;
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 bus_addr_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 = kmalloc(sizeof(*newtag), M_DEVBUF, M_INTWAIT);
143
144         newtag->parent = parent;
145         newtag->alignment = alignment;
146         newtag->boundary = boundary;
147         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
148         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) + (PAGE_SIZE - 1);
149         newtag->filter = filter;
150         newtag->filterarg = filterarg;
151         newtag->maxsize = maxsize;
152         newtag->nsegments = nsegments;
153         newtag->maxsegsz = maxsegsz;
154         newtag->flags = flags;
155         newtag->ref_count = 1; /* Count ourself */
156         newtag->map_count = 0;
157         newtag->segments = NULL;
158         
159         /* Take into account any restrictions imposed by our parent tag */
160         if (parent != NULL) {
161                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
162                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
163                 /*
164                  * XXX Not really correct??? Probably need to honor boundary
165                  *     all the way up the inheritence chain.
166                  */
167                 newtag->boundary = MAX(parent->boundary, newtag->boundary);
168                 if (newtag->filter == NULL) {
169                         /*
170                          * Short circuit looking at our parent directly
171                          * since we have encapsulated all of its information
172                          */
173                         newtag->filter = parent->filter;
174                         newtag->filterarg = parent->filterarg;
175                         newtag->parent = parent->parent;
176                 }
177                 if (newtag->parent != NULL) {
178                         parent->ref_count++;
179                 }
180         }
181         
182         if (newtag->lowaddr < ptoa(Maxmem) &&
183             (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                 kfree(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                                 if (dmat->segments != NULL)
230                                         kfree(dmat->segments, M_DEVBUF);
231                                 kfree(dmat, M_DEVBUF);
232                                 /*
233                                  * Last reference count, so
234                                  * release our reference
235                                  * count on our parent.
236                                  */
237                                 dmat = parent;
238                         } else
239                                 dmat = NULL;
240                 }
241         }
242         return (0);
243 }
244
245 /*
246  * Allocate a handle for mapping from kva/uva/physical
247  * address space into bus device space.
248  */
249 int
250 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
251 {
252         int error;
253
254         error = 0;
255
256         if (dmat->segments == NULL) {
257                 KKASSERT(dmat->nsegments && dmat->nsegments < 16384);
258                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
259                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
260         }
261
262         if (dmat->lowaddr < ptoa(Maxmem)) {
263                 /* Must bounce */
264                 int maxpages;
265
266                 *mapp = kmalloc(sizeof(**mapp), M_DEVBUF, M_INTWAIT | M_ZERO);
267                 if (*mapp == NULL)
268                         return (ENOMEM);
269                 /* Initialize the new map */
270                 STAILQ_INIT(&((*mapp)->bpages));
271                 /*
272                  * Attempt to add pages to our pool on a per-instance
273                  * basis up to a sane limit.
274                  */
275                 maxpages = MIN(MAX_BPAGES, Maxmem - atop(dmat->lowaddr));
276                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
277                  || (dmat->map_count > 0
278                   && total_bpages < maxpages)) {
279                         int pages;
280
281                         if (dmat->lowaddr > bounce_lowaddr) {
282                                 /*
283                                  * Go through the pool and kill any pages
284                                  * that don't reside below lowaddr.
285                                  */
286                                 panic("bus_dmamap_create: page reallocation "
287                                       "not implemented");
288                         }
289                         pages = atop(dmat->maxsize);
290                         pages = MIN(maxpages - total_bpages, pages);
291                         error = alloc_bounce_pages(dmat, pages);
292
293                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
294                                 if (error == 0)
295                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
296                         } else {
297                                 error = 0;
298                         }
299                 }
300         } else {
301                 *mapp = NULL;
302         }
303         if (error == 0)
304                 dmat->map_count++;
305         return (error);
306 }
307
308 /*
309  * Destroy a handle for mapping from kva/uva/physical
310  * address space into bus device space.
311  */
312 int
313 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
314 {
315         if (map != NULL) {
316                 if (STAILQ_FIRST(&map->bpages) != NULL)
317                         return (EBUSY);
318                 kfree(map, M_DEVBUF);
319         }
320         dmat->map_count--;
321         return (0);
322 }
323
324
325 /*
326  * Allocate a piece of memory that can be efficiently mapped into
327  * bus device space based on the constraints lited in the dma tag.
328  *
329  * mapp is degenerate.  By definition this allocation should not require
330  * bounce buffers so do not allocate a dma map.
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 = kmalloc(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 = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
356                 /*
357                  * XXX Check whether 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                         kfree(*vaddr, M_DEVBUF);
364                         /* XXX check for overflow? */
365                         for (size = 1; size <= dmat->maxsize; size <<= 1)
366                                 ;
367                         *vaddr = kmalloc(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                 kfree(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                 crit_enter();
453                 if (reserve_bounce_pages(dmat, map) != 0) {
454
455                         /* Queue us for resources */
456                         map->dmat = dmat;
457                         map->buf = buf;
458                         map->buflen = buflen;
459                         map->callback = callback;
460                         map->callback_arg = callback_arg;
461
462                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
463                         crit_exit();
464
465                         return (EINPROGRESS);
466                 }
467                 crit_exit();
468         }
469
470         vaddr = (vm_offset_t)buf;
471         sg = dmat->segments;
472         seg = 1;
473         sg->ds_len = 0;
474
475         nextpaddr = 0;
476         do {
477                 bus_size_t      size;
478
479                 paddr = pmap_kextract(vaddr);
480                 size = PAGE_SIZE - (paddr & PAGE_MASK);
481                 if (size > buflen)
482                         size = buflen;
483
484                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
485                         paddr = add_bounce_page(dmat, map, vaddr, size);
486                 }
487
488                 if (sg->ds_len == 0) {
489                         sg->ds_addr = paddr;
490                         sg->ds_len = size;
491                 } else if (paddr == nextpaddr) {
492                         sg->ds_len += size;
493                 } else {
494                         /* Go to the next segment */
495                         sg++;
496                         seg++;
497                         if (seg > dmat->nsegments)
498                                 break;
499                         sg->ds_addr = paddr;
500                         sg->ds_len = size;
501                 }
502                 vaddr += size;
503                 nextpaddr = paddr + size;
504                 buflen -= size;
505         } while (buflen > 0);
506
507         if (buflen != 0) {
508                 kprintf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
509                        (u_long)buflen);
510                 error = EFBIG;
511         }
512
513         (*callback)(callback_arg, dmat->segments, seg, error);
514
515         return (0);
516 }
517
518 /*
519  * Utility function to load a linear buffer.  lastaddrp holds state
520  * between invocations (for multiple-buffer loads).  segp contains
521  * the starting segment on entrace, and the ending segment on exit.
522  * first indicates if this is the first invocation of this function.
523  */
524 static int
525 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
526                         void *buf, bus_size_t buflen,
527                         struct thread *td,
528                         int flags,
529                         vm_offset_t *lastaddrp,
530                         int *segp,
531                         int first)
532 {
533         bus_dma_segment_t *segs;
534         bus_size_t sgsize;
535         bus_addr_t curaddr, lastaddr, baddr, bmask;
536         vm_offset_t vaddr = (vm_offset_t)buf;
537         int seg;
538         pmap_t pmap;
539
540         if (td->td_proc != NULL)
541                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
542         else
543                 pmap = NULL;
544
545         segs = dmat->segments;
546         lastaddr = *lastaddrp;
547         bmask  = ~(dmat->boundary - 1);
548
549         for (seg = *segp; buflen > 0 ; ) {
550                 /*
551                  * Get the physical address for this segment.
552                  */
553                 if (pmap)
554                         curaddr = pmap_extract(pmap, vaddr);
555                 else
556                         curaddr = pmap_kextract(vaddr);
557
558                 /*
559                  * Compute the segment size, and adjust counts.
560                  */
561                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
562                 if (buflen < sgsize)
563                         sgsize = buflen;
564
565                 /*
566                  * Make sure we don't cross any boundaries.
567                  */
568                 if (dmat->boundary > 0) {
569                         baddr = (curaddr + dmat->boundary) & bmask;
570                         if (sgsize > (baddr - curaddr))
571                                 sgsize = (baddr - curaddr);
572                 }
573
574                 /*
575                  * Insert chunk into a segment, coalescing with
576                  * previous segment if possible.
577                  */
578                 if (first) {
579                         segs[seg].ds_addr = curaddr;
580                         segs[seg].ds_len = sgsize;
581                         first = 0;
582                 } else {
583                         if (curaddr == lastaddr &&
584                             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
585                             (dmat->boundary == 0 ||
586                              (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
587                                 segs[seg].ds_len += sgsize;
588                         else {
589                                 if (++seg >= dmat->nsegments)
590                                         break;
591                                 segs[seg].ds_addr = curaddr;
592                                 segs[seg].ds_len = sgsize;
593                         }
594                 }
595
596                 lastaddr = curaddr + sgsize;
597                 vaddr += sgsize;
598                 buflen -= sgsize;
599         }
600
601         *segp = seg;
602         *lastaddrp = lastaddr;
603
604         /*
605          * Did we fit?
606          */
607         return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
608 }
609
610 /*
611  * Like _bus_dmamap_load(), but for mbufs.
612  */
613 int
614 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
615                      struct mbuf *m0,
616                      bus_dmamap_callback2_t *callback, void *callback_arg,
617                      int flags)
618 {
619         int nsegs, error;
620
621         KASSERT(dmat->lowaddr >= ptoa(Maxmem) || map != NULL,
622                 ("bus_dmamap_load_mbuf: No support for bounce pages!"));
623         KASSERT(m0->m_flags & M_PKTHDR,
624                 ("bus_dmamap_load_mbuf: no packet header"));
625
626         nsegs = 0;
627         error = 0;
628         if (m0->m_pkthdr.len <= dmat->maxsize) {
629                 int first = 1;
630                 vm_offset_t lastaddr = 0;
631                 struct mbuf *m;
632
633                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
634                         if ( m->m_len == 0 )
635                                 continue;
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
780                 bpage = (struct bounce_page *)kmalloc(sizeof(*bpage), M_DEVBUF,
781                                                      M_INTWAIT | M_ZERO);
782
783                 if (bpage == NULL)
784                         break;
785                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
786                                                          M_NOWAIT, 0ul,
787                                                          dmat->lowaddr,
788                                                          PAGE_SIZE,
789                                                          0);
790                 if (bpage->vaddr == NULL) {
791                         kfree(bpage, M_DEVBUF);
792                         break;
793                 }
794                 bpage->busaddr = pmap_kextract(bpage->vaddr);
795                 crit_enter();
796                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
797                 total_bpages++;
798                 free_bpages++;
799                 crit_exit();
800                 count++;
801                 numpages--;
802         }
803         return (count);
804 }
805
806 static int
807 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map)
808 {
809         int pages;
810
811         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
812         free_bpages -= pages;
813         reserved_bpages += pages;
814         map->pagesreserved += pages;
815         pages = map->pagesneeded - map->pagesreserved;
816
817         return (pages);
818 }
819
820 static bus_addr_t
821 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
822                 bus_size_t size)
823 {
824         struct bounce_page *bpage;
825
826         if (map->pagesneeded == 0)
827                 panic("add_bounce_page: map doesn't need any pages");
828         map->pagesneeded--;
829
830         if (map->pagesreserved == 0)
831                 panic("add_bounce_page: map doesn't need any pages");
832         map->pagesreserved--;
833
834         crit_enter();
835         bpage = STAILQ_FIRST(&bounce_page_list);
836         if (bpage == NULL)
837                 panic("add_bounce_page: free page list is empty");
838
839         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
840         reserved_bpages--;
841         active_bpages++;
842         crit_exit();
843
844         bpage->datavaddr = vaddr;
845         bpage->datacount = size;
846         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
847         return (bpage->busaddr);
848 }
849
850 static void
851 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
852 {
853         struct bus_dmamap *map;
854
855         bpage->datavaddr = 0;
856         bpage->datacount = 0;
857
858         crit_enter();
859         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
860         free_bpages++;
861         active_bpages--;
862         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
863                 if (reserve_bounce_pages(map->dmat, map) == 0) {
864                         panic("free_bounce_pages: uncoded\n");
865 #if 0
866                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
867                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
868                                            map, links);
869                         busdma_swi_pending = 1;
870                         setsoftvm();
871 #endif
872                 }
873         }
874         crit_exit();
875 }
876
877 #if 0
878
879 void
880 busdma_swi(void)
881 {
882         struct bus_dmamap *map;
883
884         crit_enter();
885         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
886                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
887                 crit_exit();
888                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
889                                 map->callback, map->callback_arg, /*flags*/0);
890                 crit_enter();
891         }
892         crit_exit();
893 }
894
895 #endif
896