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