]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - sys/ia64/ia64/busdma_machdep.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / sys / ia64 / ia64 / busdma_machdep.c
1 /*-
2  * Copyright (c) 1997 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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/malloc.h>
34 #include <sys/mbuf.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/bus.h>
38 #include <sys/interrupt.h>
39 #include <sys/proc.h>
40 #include <sys/uio.h>
41 #include <sys/sysctl.h>
42
43 #include <vm/vm.h>
44 #include <vm/vm_page.h>
45 #include <vm/vm_map.h>
46
47 #include <machine/atomic.h>
48 #include <machine/bus.h>
49 #include <machine/md_var.h>
50
51 #define MAX_BPAGES      1024
52
53 struct bus_dma_tag {
54         bus_dma_tag_t   parent;
55         bus_size_t      alignment;
56         bus_size_t      boundary;
57         bus_addr_t      lowaddr;
58         bus_addr_t      highaddr;
59         bus_dma_filter_t *filter;
60         void            *filterarg;
61         bus_size_t      maxsize;
62         u_int           nsegments;
63         bus_size_t      maxsegsz;
64         int             flags;
65         int             ref_count;
66         int             map_count;
67         bus_dma_lock_t  *lockfunc;
68         void            *lockfuncarg;
69         bus_dma_segment_t *segments;
70 };
71
72 struct bounce_page {
73         vm_offset_t     vaddr;          /* kva of bounce buffer */
74         bus_addr_t      busaddr;        /* Physical address */
75         vm_offset_t     datavaddr;      /* kva of client data */
76         bus_size_t      datacount;      /* client data count */
77         STAILQ_ENTRY(bounce_page) links;
78 };
79
80 u_int busdma_swi_pending;
81
82 static struct mtx bounce_lock;
83 static STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
84 static int free_bpages;
85 static int reserved_bpages;
86 static int active_bpages;
87 static int total_bpages;
88 static int total_bounced;
89 static int total_deferred;
90
91 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
92 SYSCTL_INT(_hw_busdma, OID_AUTO, free_bpages, CTLFLAG_RD, &free_bpages, 0,
93     "Free bounce pages");
94 SYSCTL_INT(_hw_busdma, OID_AUTO, reserved_bpages, CTLFLAG_RD, &reserved_bpages,
95     0, "Reserved bounce pages");
96 SYSCTL_INT(_hw_busdma, OID_AUTO, active_bpages, CTLFLAG_RD, &active_bpages, 0,
97     "Active bounce pages");
98 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
99     "Total bounce pages");
100 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bounced, CTLFLAG_RD, &total_bounced, 0,
101     "Total bounce requests");
102 SYSCTL_INT(_hw_busdma, OID_AUTO, total_deferred, CTLFLAG_RD, &total_deferred,
103     0, "Total bounce requests that were deferred");
104
105 struct bus_dmamap {
106         struct bp_list  bpages;
107         int             pagesneeded;
108         int             pagesreserved;
109         bus_dma_tag_t   dmat;
110         void            *buf;           /* unmapped buffer pointer */
111         bus_size_t      buflen;         /* unmapped buffer length */
112         bus_dmamap_callback_t *callback;
113         void            *callback_arg;
114         STAILQ_ENTRY(bus_dmamap) links;
115 };
116
117 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
118 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
119 static struct bus_dmamap nobounce_dmamap;
120
121 static void init_bounce_pages(void *dummy);
122 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
123 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
124     int commit);
125 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
126     vm_offset_t vaddr, bus_size_t size);
127 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
128 static __inline int run_filter(bus_dma_tag_t dmat, bus_addr_t paddr,
129     bus_size_t len);
130
131 /*
132  * Return true if a match is made.
133  *
134  * To find a match walk the chain of bus_dma_tag_t's looking for 'paddr'.
135  *
136  * If paddr is within the bounds of the dma tag then call the filter callback
137  * to check for a match, if there is no filter callback then assume a match.
138  */
139 static __inline int
140 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr, bus_size_t len)
141 {
142         bus_size_t bndy;
143         int retval;
144
145         retval = 0;
146         bndy = dmat->boundary;
147         do {
148                 if (((paddr > dmat->lowaddr && paddr <= dmat->highaddr) ||
149                     (paddr & (dmat->alignment - 1)) != 0 ||
150                     (paddr & bndy) != ((paddr + len) & bndy)) &&
151                     (dmat->filter == NULL ||
152                     (*dmat->filter)(dmat->filterarg, paddr) != 0))
153                         retval = 1;
154                 dmat = dmat->parent;
155         } while (retval == 0 && dmat != NULL);
156         return (retval);
157 }
158
159 /*
160  * Convenience function for manipulating driver locks from busdma (during
161  * busdma_swi, for example).  Drivers that don't provide their own locks
162  * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
163  * non-mutex locking scheme don't have to use this at all.
164  */
165 void
166 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
167 {
168         struct mtx *dmtx;
169
170         dmtx = (struct mtx *)arg;
171         switch (op) {
172         case BUS_DMA_LOCK:
173                 mtx_lock(dmtx);
174                 break;
175         case BUS_DMA_UNLOCK:
176                 mtx_unlock(dmtx);
177                 break;
178         default:
179                 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
180         }
181 }
182
183 /*
184  * dflt_lock should never get called.  It gets put into the dma tag when
185  * lockfunc == NULL, which is only valid if the maps that are associated
186  * with the tag are meant to never be defered.
187  * XXX Should have a way to identify which driver is responsible here.
188  */
189 static void
190 dflt_lock(void *arg, bus_dma_lock_op_t op)
191 {
192         panic("driver error: busdma dflt_lock called");
193 }
194
195 #define BUS_DMA_MIN_ALLOC_COMP BUS_DMA_BUS4
196
197 /*
198  * Allocate a device specific dma_tag.
199  */
200 int
201 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
202     bus_size_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
203     bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
204     int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
205     void *lockfuncarg, bus_dma_tag_t *dmat)
206 {
207         bus_dma_tag_t newtag;
208         int error = 0;
209
210         /* Basic sanity checking */
211         if (boundary != 0 && boundary < maxsegsz)
212                 maxsegsz = boundary;
213
214         /* Return a NULL tag on failure */
215         *dmat = NULL;
216
217         newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_DEVBUF, M_NOWAIT);
218         if (newtag == NULL)
219                 return (ENOMEM);
220
221         newtag->parent = parent;
222         newtag->alignment = alignment;
223         newtag->boundary = boundary;
224         newtag->lowaddr = trunc_page(lowaddr) + (PAGE_SIZE - 1);
225         newtag->highaddr = trunc_page(highaddr) + (PAGE_SIZE - 1);
226         newtag->filter = filter;
227         newtag->filterarg = filterarg;
228         newtag->maxsize = maxsize;
229         newtag->nsegments = nsegments;
230         newtag->maxsegsz = maxsegsz;
231         newtag->flags = flags;
232         newtag->ref_count = 1; /* Count ourself */
233         newtag->map_count = 0;
234         if (lockfunc != NULL) {
235                 newtag->lockfunc = lockfunc;
236                 newtag->lockfuncarg = lockfuncarg;
237         } else {
238                 newtag->lockfunc = dflt_lock;
239                 newtag->lockfuncarg = NULL;
240         }
241         newtag->segments = NULL;
242
243         /* Take into account any restrictions imposed by our parent tag */
244         if (parent != NULL) {
245                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
246                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
247                 if (newtag->boundary == 0)
248                         newtag->boundary = parent->boundary;
249                 else if (parent->boundary != 0)
250                         newtag->boundary = MIN(parent->boundary,
251                             newtag->boundary);
252                 if (newtag->filter == NULL) {
253                         /*
254                          * Short circuit looking at our parent directly
255                          * since we have encapsulated all of its information
256                          */
257                         newtag->filter = parent->filter;
258                         newtag->filterarg = parent->filterarg;
259                         newtag->parent = parent->parent;
260                 }
261                 if (newtag->parent != NULL)
262                         atomic_add_int(&parent->ref_count, 1);
263         }
264
265         if (newtag->lowaddr < ptoa(Maxmem) && (flags & BUS_DMA_ALLOCNOW) != 0) {
266                 /* Must bounce */
267
268                 if (ptoa(total_bpages) < maxsize) {
269                         int pages;
270
271                         pages = atop(maxsize) - total_bpages;
272
273                         /* Add pages to our bounce pool */
274                         if (alloc_bounce_pages(newtag, pages) < pages)
275                                 error = ENOMEM;
276                 }
277                 /* Performed initial allocation */
278                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
279         }
280
281         if (error != 0) {
282                 free(newtag, M_DEVBUF);
283         } else {
284                 *dmat = newtag;
285         }
286         return (error);
287 }
288
289 int
290 bus_dma_tag_destroy(bus_dma_tag_t dmat)
291 {
292         if (dmat != NULL) {
293
294                 if (dmat->map_count != 0)
295                         return (EBUSY);
296
297                 while (dmat != NULL) {
298                         bus_dma_tag_t parent;
299
300                         parent = dmat->parent;
301                         atomic_subtract_int(&dmat->ref_count, 1);
302                         if (dmat->ref_count == 0) {
303                                 if (dmat->segments != NULL)
304                                         free(dmat->segments, M_DEVBUF);
305                                 free(dmat, M_DEVBUF);
306                                 /*
307                                  * Last reference count, so
308                                  * release our reference
309                                  * count on our parent.
310                                  */
311                                 dmat = parent;
312                         } else
313                                 dmat = NULL;
314                 }
315         }
316         return (0);
317 }
318
319 /*
320  * Allocate a handle for mapping from kva/uva/physical
321  * address space into bus device space.
322  */
323 int
324 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
325 {
326         int error;
327
328         error = 0;
329
330         if (dmat->segments == NULL) {
331                 dmat->segments = (bus_dma_segment_t *)malloc(
332                     sizeof(bus_dma_segment_t) * dmat->nsegments, M_DEVBUF,
333                     M_NOWAIT);
334                 if (dmat->segments == NULL)
335                         return (ENOMEM);
336         }
337
338         /*
339          * Bouncing might be required if the driver asks for an active
340          * exclusion region, a data alignment that is stricter than 1, and/or
341          * an active address boundary.
342          */
343         if (dmat->lowaddr < ptoa(Maxmem)) {
344                 /* Must bounce */
345                 int maxpages;
346
347                 *mapp = (bus_dmamap_t)malloc(sizeof(**mapp), M_DEVBUF,
348                     M_NOWAIT | M_ZERO);
349                 if (*mapp == NULL)
350                         return (ENOMEM);
351
352                 /* Initialize the new map */
353                 STAILQ_INIT(&((*mapp)->bpages));
354
355                 /*
356                  * Attempt to add pages to our pool on a per-instance
357                  * basis up to a sane limit.
358                  */
359                 maxpages = MIN(MAX_BPAGES, Maxmem - atop(dmat->lowaddr));
360                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
361                  || (dmat->map_count > 0 && total_bpages < maxpages)) {
362                         int pages;
363
364                         pages = MAX(atop(dmat->maxsize), 1);
365                         pages = MIN(maxpages - total_bpages, pages);
366                         if (alloc_bounce_pages(dmat, pages) < pages)
367                                 error = ENOMEM;
368
369                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
370                                 if (error == 0)
371                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
372                         } else {
373                                 error = 0;
374                         }
375                 }
376         } else {
377                 *mapp = NULL;
378         }
379         if (error == 0)
380                 dmat->map_count++;
381         return (error);
382 }
383
384 /*
385  * Destroy a handle for mapping from kva/uva/physical
386  * address space into bus device space.
387  */
388 int
389 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
390 {
391
392         if (map != NULL && map != &nobounce_dmamap) {
393                 if (STAILQ_FIRST(&map->bpages) != NULL)
394                         return (EBUSY);
395                 free(map, M_DEVBUF);
396         }
397         dmat->map_count--;
398         return (0);
399 }
400
401
402 /*
403  * Allocate a piece of memory that can be efficiently mapped into
404  * bus device space based on the constraints lited in the dma tag.
405  * A dmamap to for use with dmamap_load is also allocated.
406  */
407 int
408 bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
409     bus_dmamap_t *mapp)
410 {
411         int mflags;
412
413         if (flags & BUS_DMA_NOWAIT)
414                 mflags = M_NOWAIT;
415         else
416                 mflags = M_WAITOK;
417
418         /* If we succeed, no mapping/bouncing will be required */
419         *mapp = NULL;
420
421         if (dmat->segments == NULL) {
422                 dmat->segments = (bus_dma_segment_t *)malloc(
423                     sizeof(bus_dma_segment_t) * dmat->nsegments, M_DEVBUF,
424                     mflags);
425                 if (dmat->segments == NULL)
426                         return (ENOMEM);
427         }
428         if (flags & BUS_DMA_ZERO)
429                 mflags |= M_ZERO;
430
431         /*
432          * XXX:
433          * (dmat->alignment < dmat->maxsize) is just a quick hack; the exact
434          * alignment guarantees of malloc need to be nailed down, and the
435          * code below should be rewritten to take that into account.
436          *
437          * In the meantime, we'll warn the user if malloc gets it wrong.
438          */
439         if ((dmat->maxsize <= PAGE_SIZE) &&
440            (dmat->alignment < dmat->maxsize) &&
441             dmat->lowaddr >= ptoa(Maxmem)) {
442                 *vaddr = malloc(dmat->maxsize, M_DEVBUF, mflags);
443         } else {
444                 /*
445                  * XXX Use Contigmalloc until it is merged into this facility
446                  *     and handles multi-seg allocations.  Nobody is doing
447                  *     multi-seg allocations yet though.
448                  * XXX Certain AGP hardware does.
449                  */
450                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
451                     0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
452                     dmat->boundary);
453         }
454         if (*vaddr == NULL)
455                 return (ENOMEM);
456         else if (vtophys(*vaddr) & (dmat->alignment - 1))
457                 printf("bus_dmamem_alloc failed to align memory properly.\n");
458         return (0);
459 }
460
461 /*
462  * Free a piece of memory and it's allociated dmamap, that was allocated
463  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
464  */
465 void
466 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
467 {
468         /*
469          * dmamem does not need to be bounced, so the map should be
470          * NULL
471          */
472         if (map != NULL)
473                 panic("bus_dmamem_free: Invalid map freed\n");
474         if ((dmat->maxsize <= PAGE_SIZE) &&
475            (dmat->alignment < dmat->maxsize) &&
476             dmat->lowaddr >= ptoa(Maxmem))
477                 free(vaddr, M_DEVBUF);
478         else {
479                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
480         }
481 }
482
483 /*
484  * Utility function to load a linear buffer.  lastaddrp holds state
485  * between invocations (for multiple-buffer loads).  segp contains
486  * the starting segment on entrace, and the ending segment on exit.
487  * first indicates if this is the first invocation of this function.
488  */
489 static int
490 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
491     bus_size_t buflen, struct thread *td, int flags, bus_addr_t *lastaddrp,
492     bus_dma_segment_t *segs, int *segp, int first)
493 {
494         bus_size_t sgsize;
495         bus_addr_t curaddr, lastaddr, baddr, bmask;
496         vm_offset_t vaddr;
497         bus_addr_t paddr;
498         int seg;
499         pmap_t pmap;
500
501         if (map == NULL)
502                 map = &nobounce_dmamap;
503
504         if (td != NULL)
505                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
506         else
507                 pmap = NULL;
508
509         if ((dmat->lowaddr < ptoa(Maxmem) || dmat->boundary > 0 ||
510             dmat->alignment > 1) && map != &nobounce_dmamap &&
511             map->pagesneeded == 0) {
512                 vm_offset_t vendaddr;
513
514                 /*
515                  * Count the number of bounce pages
516                  * needed in order to complete this transfer
517                  */
518                 vaddr = trunc_page((vm_offset_t)buf);
519                 vendaddr = (vm_offset_t)buf + buflen;
520
521                 while (vaddr < vendaddr) {
522                         if (pmap != NULL)
523                                 paddr = pmap_extract(pmap, vaddr);
524                         else
525                                 paddr = pmap_kextract(vaddr);
526                         if (run_filter(dmat, paddr, 0) != 0)
527                                 map->pagesneeded++;
528                         vaddr += PAGE_SIZE;
529                 }
530         }
531
532         vaddr = (vm_offset_t)buf;
533
534         /* Reserve Necessary Bounce Pages */
535         if (map->pagesneeded != 0) {
536                 mtx_lock(&bounce_lock);
537                 if (flags & BUS_DMA_NOWAIT) {
538                         if (reserve_bounce_pages(dmat, map, 0) != 0) {
539                                 mtx_unlock(&bounce_lock);
540                                 return (ENOMEM);
541                         }
542                 } else {
543                         if (reserve_bounce_pages(dmat, map, 1) != 0) {
544                                 /* Queue us for resources */
545                                 map->dmat = dmat;
546                                 map->buf = buf;
547                                 map->buflen = buflen;
548                                 STAILQ_INSERT_TAIL(&bounce_map_waitinglist,
549                                     map, links);
550                                 mtx_unlock(&bounce_lock);
551                                 return (EINPROGRESS);
552                         }
553                 }
554                 mtx_unlock(&bounce_lock);
555         }
556
557         lastaddr = *lastaddrp;
558         bmask = ~(dmat->boundary - 1);
559
560         for (seg = *segp; buflen > 0 ; ) {
561                 /*
562                  * Get the physical address for this segment.
563                  */
564                 if (pmap)
565                         curaddr = pmap_extract(pmap, vaddr);
566                 else
567                         curaddr = pmap_kextract(vaddr);
568
569                 /*
570                  * Compute the segment size, and adjust counts.
571                  */
572                 sgsize = PAGE_SIZE - ((u_long)curaddr & PAGE_MASK);
573                 if (sgsize > dmat->maxsegsz)
574                         sgsize = dmat->maxsegsz;
575                 if (buflen < sgsize)
576                         sgsize = buflen;
577
578                 /*
579                  * Make sure we don't cross any boundaries.
580                  */
581                 if (dmat->boundary > 0) {
582                         baddr = (curaddr + dmat->boundary) & bmask;
583                         if (sgsize > (baddr - curaddr))
584                                 sgsize = (baddr - curaddr);
585                 }
586
587                 if (map->pagesneeded != 0 && run_filter(dmat, curaddr, sgsize))
588                         curaddr = add_bounce_page(dmat, map, vaddr, sgsize);
589
590                 /*
591                  * Insert chunk into a segment, coalescing with
592                  * previous segment if possible.
593                  */
594                 if (first) {
595                         segs[seg].ds_addr = curaddr;
596                         segs[seg].ds_len = sgsize;
597                         first = 0;
598                 } else {
599                         if (curaddr == lastaddr &&
600                             (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
601                             (dmat->boundary == 0 ||
602                             (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
603                                 segs[seg].ds_len += sgsize;
604                         else {
605                                 if (++seg >= dmat->nsegments)
606                                         break;
607                                 segs[seg].ds_addr = curaddr;
608                                 segs[seg].ds_len = sgsize;
609                         }
610                 }
611
612                 lastaddr = curaddr + sgsize;
613                 vaddr += sgsize;
614                 buflen -= sgsize;
615         }
616
617         *segp = seg;
618         *lastaddrp = lastaddr;
619
620         /*
621          * Did we fit?
622          */
623         return (buflen != 0 ? EFBIG : 0); /* XXX better return value here? */
624 }
625
626 /*
627  * Map the buffer buf into bus space using the dmamap map.
628  */
629 int
630 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
631     bus_size_t buflen, bus_dmamap_callback_t *callback, void *callback_arg,
632     int flags)
633 {
634         bus_addr_t lastaddr = 0;
635         int error, nsegs = 0;
636
637         if (map != NULL) {
638                 flags |= BUS_DMA_WAITOK;
639                 map->callback = callback;
640                 map->callback_arg = callback_arg;
641         }
642
643         error = _bus_dmamap_load_buffer(dmat, map, buf, buflen, NULL, flags,
644             &lastaddr, dmat->segments, &nsegs, 1);
645
646         if (error == EINPROGRESS)
647                 return (error);
648
649         if (error)
650                 (*callback)(callback_arg, dmat->segments, 0, error);
651         else
652                 (*callback)(callback_arg, dmat->segments, nsegs + 1, 0);
653
654         return (0);
655 }
656
657 /*
658  * Like _bus_dmamap_load(), but for mbufs.
659  */
660 int
661 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map, struct mbuf *m0,
662     bus_dmamap_callback2_t *callback, void *callback_arg, int flags)
663 {
664         int nsegs, error;
665
666         M_ASSERTPKTHDR(m0);
667
668         flags |= BUS_DMA_NOWAIT;
669         nsegs = 0;
670         error = 0;
671         if (m0->m_pkthdr.len <= dmat->maxsize) {
672                 int first = 1;
673                 bus_addr_t lastaddr = 0;
674                 struct mbuf *m;
675
676                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
677                         if (m->m_len > 0) {
678                                 error = _bus_dmamap_load_buffer(dmat, map,
679                                     m->m_data, m->m_len, NULL, flags,
680                                     &lastaddr, dmat->segments, &nsegs, first);
681                                 first = 0;
682                         }
683                 }
684         } else {
685                 error = EINVAL;
686         }
687
688         if (error) {
689                 /* force "no valid mappings" in callback */
690                 (*callback)(callback_arg, dmat->segments, 0, 0, error);
691         } else {
692                 (*callback)(callback_arg, dmat->segments, nsegs + 1,
693                     m0->m_pkthdr.len, error);
694         }
695         return (error);
696 }
697
698 int
699 bus_dmamap_load_mbuf_sg(bus_dma_tag_t dmat, bus_dmamap_t map, struct mbuf *m0,
700     bus_dma_segment_t *segs, int *nsegs, int flags)
701 {
702         int error;
703
704         M_ASSERTPKTHDR(m0);
705
706         flags |= BUS_DMA_NOWAIT;
707         *nsegs = 0;
708         error = 0;
709         if (m0->m_pkthdr.len <= dmat->maxsize) {
710                 int first = 1;
711                 bus_addr_t lastaddr = 0;
712                 struct mbuf *m;
713
714                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
715                         if (m->m_len > 0) {
716                                 error = _bus_dmamap_load_buffer(dmat, map,
717                                     m->m_data, m->m_len, NULL, flags,
718                                     &lastaddr, segs, nsegs, first);
719                                 first = 0;
720                         }
721                 }
722                 ++*nsegs;
723         } else {
724                 error = EINVAL;
725         }
726
727         return (error);
728 }
729
730 /*
731  * Like _bus_dmamap_load(), but for uios.
732  */
733 int
734 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map, struct uio *uio,
735     bus_dmamap_callback2_t *callback, void *callback_arg, int flags)
736 {
737         bus_addr_t lastaddr;
738         int nsegs, error, first, i;
739         bus_size_t resid;
740         struct iovec *iov;
741         struct thread *td = NULL;
742
743         flags |= BUS_DMA_NOWAIT;
744         resid = uio->uio_resid;
745         iov = uio->uio_iov;
746
747         if (uio->uio_segflg == UIO_USERSPACE) {
748                 td = uio->uio_td;
749                 KASSERT(td != NULL,
750                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
751         }
752
753         nsegs = 0;
754         error = 0;
755         first = 1;
756         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
757                 /*
758                  * Now at the first iovec to load.  Load each iovec
759                  * until we have exhausted the residual count.
760                  */
761                 bus_size_t minlen =
762                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
763                 caddr_t addr = (caddr_t) iov[i].iov_base;
764
765                 if (minlen > 0) {
766                         error = _bus_dmamap_load_buffer(dmat, map, addr,
767                             minlen, td, flags, &lastaddr, dmat->segments,
768                             &nsegs, first);
769                         first = 0;
770
771                         resid -= minlen;
772                 }
773         }
774
775         if (error) {
776                 /* force "no valid mappings" in callback */
777                 (*callback)(callback_arg, dmat->segments, 0, 0, error);
778         } else {
779                 (*callback)(callback_arg, dmat->segments, nsegs + 1,
780                     uio->uio_resid, error);
781         }
782         return (error);
783 }
784
785 /*
786  * Release the mapping held by map.
787  */
788 void
789 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
790 {
791         struct bounce_page *bpage;
792
793         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
794                 STAILQ_REMOVE_HEAD(&map->bpages, links);
795                 free_bounce_page(dmat, bpage);
796         }
797 }
798
799 void
800 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
801 {
802         struct bounce_page *bpage;
803
804         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
805                 /*
806                  * Handle data bouncing.  We might also
807                  * want to add support for invalidating
808                  * the caches on broken hardware
809                  */
810
811                 if (op & BUS_DMASYNC_PREWRITE) {
812                         while (bpage != NULL) {
813                                 bcopy((void *)bpage->datavaddr,
814                                     (void *)bpage->vaddr, bpage->datacount);
815                                 bpage = STAILQ_NEXT(bpage, links);
816                         }
817                         total_bounced++;
818                 }
819
820                 if (op & BUS_DMASYNC_POSTREAD) {
821                         while (bpage != NULL) {
822                                 bcopy((void *)bpage->vaddr,
823                                     (void *)bpage->datavaddr, bpage->datacount);
824                                 bpage = STAILQ_NEXT(bpage, links);
825                         }
826                         total_bounced++;
827                 }
828         }
829 }
830
831 static void
832 init_bounce_pages(void *dummy __unused)
833 {
834
835         free_bpages = 0;
836         reserved_bpages = 0;
837         active_bpages = 0;
838         total_bpages = 0;
839         STAILQ_INIT(&bounce_page_list);
840         STAILQ_INIT(&bounce_map_waitinglist);
841         STAILQ_INIT(&bounce_map_callbacklist);
842         mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
843 }
844 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
845
846 static int
847 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
848 {
849         int count;
850
851         count = 0;
852         while (numpages > 0) {
853                 struct bounce_page *bpage;
854
855                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_DEVBUF,
856                     M_NOWAIT | M_ZERO);
857                 if (bpage == NULL)
858                         break;
859                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
860                     M_NOWAIT, 0ul, dmat->lowaddr, PAGE_SIZE, dmat->boundary);
861                 if (bpage->vaddr == 0) {
862                         free(bpage, M_DEVBUF);
863                         break;
864                 }
865                 bpage->busaddr = pmap_kextract(bpage->vaddr);
866                 mtx_lock(&bounce_lock);
867                 STAILQ_INSERT_TAIL(&bounce_page_list, bpage, links);
868                 total_bpages++;
869                 free_bpages++;
870                 mtx_unlock(&bounce_lock);
871                 count++;
872                 numpages--;
873         }
874         return (count);
875 }
876
877 static int
878 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
879 {
880         int pages;
881
882         mtx_assert(&bounce_lock, MA_OWNED);
883         pages = MIN(free_bpages, map->pagesneeded - map->pagesreserved);
884         if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
885                 return (map->pagesneeded - (map->pagesreserved + pages));
886         free_bpages -= pages;
887         reserved_bpages += pages;
888         map->pagesreserved += pages;
889         pages = map->pagesneeded - map->pagesreserved;
890
891         return (pages);
892 }
893
894 static bus_addr_t
895 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
896     bus_size_t size)
897 {
898         struct bounce_page *bpage;
899
900         KASSERT(map != NULL && map != &nobounce_dmamap,
901             ("add_bounce_page: bad map %p", map));
902
903         if (map->pagesneeded == 0)
904                 panic("add_bounce_page: map doesn't need any pages");
905         map->pagesneeded--;
906
907         if (map->pagesreserved == 0)
908                 panic("add_bounce_page: map doesn't need any pages");
909         map->pagesreserved--;
910
911         mtx_lock(&bounce_lock);
912         bpage = STAILQ_FIRST(&bounce_page_list);
913         if (bpage == NULL)
914                 panic("add_bounce_page: free page list is empty");
915
916         STAILQ_REMOVE_HEAD(&bounce_page_list, links);
917         reserved_bpages--;
918         active_bpages++;
919         mtx_unlock(&bounce_lock);
920
921         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
922                 /* Page offset needs to be preserved. */
923                 bpage->vaddr |= vaddr & PAGE_MASK;
924                 bpage->busaddr |= vaddr & PAGE_MASK;
925         }
926         bpage->datavaddr = vaddr;
927         bpage->datacount = size;
928         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
929         return (bpage->busaddr);
930 }
931
932 static void
933 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
934 {
935         struct bus_dmamap *map;
936
937         bpage->datavaddr = 0;
938         bpage->datacount = 0;
939         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
940                 /*
941                  * Reset the bounce page to start at offset 0.  Other uses
942                  * of this bounce page may need to store a full page of
943                  * data and/or assume it starts on a page boundary.
944                  */
945                 bpage->vaddr &= ~PAGE_MASK;
946                 bpage->busaddr &= ~PAGE_MASK;
947         }
948
949         mtx_lock(&bounce_lock);
950         STAILQ_INSERT_HEAD(&bounce_page_list, bpage, links);
951         free_bpages++;
952         active_bpages--;
953         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
954                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
955                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
956                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist, map,
957                             links);
958                         busdma_swi_pending = 1;
959                         total_deferred++;
960                         swi_sched(vm_ih, 0);
961                 }
962         }
963         mtx_unlock(&bounce_lock);
964 }
965
966 void
967 busdma_swi(void)
968 {
969         bus_dma_tag_t dmat;
970         struct bus_dmamap *map;
971
972         mtx_lock(&bounce_lock);
973         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
974                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
975                 mtx_unlock(&bounce_lock);
976                 dmat = map->dmat;
977                 (dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_LOCK);
978                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
979                     map->callback, map->callback_arg, /*flags*/0);
980                 (dmat->lockfunc)(dmat->lockfuncarg, BUS_DMA_UNLOCK);
981                 mtx_lock(&bounce_lock);
982         }
983         mtx_unlock(&bounce_lock);
984 }