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