Use lwkt_token to protect bounce_zone_list
[dragonfly.git] / sys / platform / pc32 / i386 / busdma_machdep.c
1 /*
2  * Copyright (c) 1997, 1998 Justin T. Gibbs.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/i386/i386/busdma_machdep.c,v 1.16.2.2 2003/01/23 00:55:27 scottl Exp $
27  * $DragonFly: src/sys/platform/pc32/i386/busdma_machdep.c,v 1.23 2008/06/05 18:06:32 swildner Exp $
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/mbuf.h>
34 #include <sys/uio.h>
35 #include <sys/thread2.h>
36 #include <sys/bus_dma.h>
37 #include <sys/kernel.h>
38 #include <sys/sysctl.h>
39
40 #include <vm/vm.h>
41 #include <vm/vm_page.h>
42
43 /* XXX needed for to access pmap to convert per-proc virtual to physical */
44 #include <sys/proc.h>
45 #include <sys/lock.h>
46 #include <vm/vm_map.h>
47
48 #include <machine/md_var.h>
49
50 #define MAX_BPAGES      1024
51
52 struct bounce_zone;
53 struct bus_dmamap;
54
55 struct bus_dma_tag {
56         bus_dma_tag_t   parent;
57         bus_size_t      alignment;
58         bus_size_t      boundary;
59         bus_addr_t      lowaddr;
60         bus_addr_t      highaddr;
61         bus_dma_filter_t *filter;
62         void            *filterarg;
63         bus_size_t      maxsize;
64         u_int           nsegments;
65         bus_size_t      maxsegsz;
66         int             flags;
67         int             ref_count;
68         int             map_count;
69         bus_dma_segment_t *segments;
70         struct bounce_zone *bounce_zone;
71 };
72
73 /*
74  * bus_dma_tag private flags
75  */
76 #define BUS_DMA_COULD_BOUNCE    BUS_DMA_BUS3
77 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
78
79 struct bounce_page {
80         vm_offset_t     vaddr;          /* kva of bounce buffer */
81         bus_addr_t      busaddr;        /* Physical address */
82         vm_offset_t     datavaddr;      /* kva of client data */
83         bus_size_t      datacount;      /* client data count */
84         STAILQ_ENTRY(bounce_page) links;
85 };
86
87 struct bounce_zone {
88         STAILQ_ENTRY(bounce_zone) links;
89         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
90         STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
91         int             total_bpages;
92         int             free_bpages;
93         int             reserved_bpages;
94         int             active_bpages;
95         int             total_bounced;
96         int             total_deferred;
97         int             reserve_failed;
98         bus_size_t      alignment;
99         bus_size_t      boundary;
100         bus_addr_t      lowaddr;
101         char            zoneid[8];
102         char            lowaddrid[20];
103         struct sysctl_ctx_list sysctl_ctx;
104         struct sysctl_oid *sysctl_tree;
105 };
106
107 static struct lwkt_token bounce_zone_tok =
108         LWKT_TOKEN_INITIALIZER(bounce_zone_tok);
109 static int busdma_zonecount;
110 static STAILQ_HEAD(, bounce_zone) bounce_zone_list =
111         STAILQ_HEAD_INITIALIZER(bounce_zone_list);
112
113 int busdma_swi_pending;
114 static int total_bounce_pages;
115 static bus_addr_t bounce_lowaddr = BUS_SPACE_MAXADDR;
116
117 struct bus_dmamap {
118         struct bp_list  bpages;
119         int             pagesneeded;
120         int             pagesreserved;
121         bus_dma_tag_t   dmat;
122         void            *buf;           /* unmapped buffer pointer */
123         bus_size_t      buflen;         /* unmapped buffer length */
124         bus_dmamap_callback_t *callback;
125         void            *callback_arg;
126         STAILQ_ENTRY(bus_dmamap) links;
127 };
128
129 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist =
130         STAILQ_HEAD_INITIALIZER(bounce_map_callbacklist);
131
132 static struct bus_dmamap nobounce_dmamap;
133
134 static int              alloc_bounce_zone(bus_dma_tag_t);
135 static int              alloc_bounce_pages(bus_dma_tag_t, u_int);
136 static int              reserve_bounce_pages(bus_dma_tag_t, bus_dmamap_t, int);
137 static bus_addr_t       add_bounce_page(bus_dma_tag_t, bus_dmamap_t,
138                             vm_offset_t, bus_size_t);
139 static void             free_bounce_page(bus_dma_tag_t, struct bounce_page *);
140
141 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
142 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bounce_pages,
143            0, "Total bounce pages");
144
145 static __inline int
146 run_filter(bus_dma_tag_t dmat, bus_addr_t paddr)
147 {
148         int retval;
149
150         retval = 0;
151         do {
152                 if (paddr > dmat->lowaddr
153                  && paddr <= dmat->highaddr
154                  && (dmat->filter == NULL
155                   || (*dmat->filter)(dmat->filterarg, paddr) != 0))
156                         retval = 1;
157
158                 dmat = dmat->parent;
159         } while (retval == 0 && dmat != NULL);
160         return (retval);
161 }
162
163 /*
164  * Allocate a device specific dma_tag.
165  */
166 int
167 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
168                    bus_size_t boundary, bus_addr_t lowaddr,
169                    bus_addr_t highaddr, bus_dma_filter_t *filter,
170                    void *filterarg, bus_size_t maxsize, int nsegments,
171                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)
172 {
173         bus_dma_tag_t newtag;
174         int error = 0;
175
176         if (alignment == 0)
177                 alignment = 1;
178
179         /* Return a NULL tag on failure */
180         *dmat = NULL;
181
182         newtag = kmalloc(sizeof(*newtag), M_DEVBUF, M_INTWAIT);
183
184         newtag->parent = parent;
185         newtag->alignment = alignment;
186         newtag->boundary = boundary;
187         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
188         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) + (PAGE_SIZE - 1);
189         newtag->filter = filter;
190         newtag->filterarg = filterarg;
191         newtag->maxsize = maxsize;
192         newtag->nsegments = nsegments;
193         newtag->maxsegsz = maxsegsz;
194         newtag->flags = flags;
195         newtag->ref_count = 1; /* Count ourself */
196         newtag->map_count = 0;
197         newtag->segments = NULL;
198         newtag->bounce_zone = NULL;
199
200         /* Take into account any restrictions imposed by our parent tag */
201         if (parent != NULL) {
202                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
203                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
204
205                 if (newtag->boundary == 0) {
206                         newtag->boundary = parent->boundary;
207                 } else if (parent->boundary != 0) {
208                         newtag->boundary = MIN(parent->boundary,
209                                                newtag->boundary);
210                 }
211
212 #ifdef notyet
213                 newtag->alignment = MAX(parent->alignment, newtag->alignment);
214 #endif
215
216                 if (newtag->filter == NULL) {
217                         /*
218                          * Short circuit looking at our parent directly
219                          * since we have encapsulated all of its information
220                          */
221                         newtag->filter = parent->filter;
222                         newtag->filterarg = parent->filterarg;
223                         newtag->parent = parent->parent;
224                 }
225                 if (newtag->parent != NULL)
226                         parent->ref_count++;
227         }
228
229         if (newtag->lowaddr < ptoa(Maxmem))
230                 newtag->flags |= BUS_DMA_COULD_BOUNCE;
231
232         if ((newtag->flags & BUS_DMA_COULD_BOUNCE) &&
233             (flags & BUS_DMA_ALLOCNOW) != 0) {
234                 struct bounce_zone *bz;
235
236                 /* Must bounce */
237
238                 if (lowaddr > bounce_lowaddr) {
239                         /*
240                          * Go through the pool and kill any pages
241                          * that don't reside below lowaddr.
242                          */
243                         panic("bus_dma_tag_create: page reallocation "
244                               "not implemented");
245                 }
246
247                 error = alloc_bounce_zone(newtag);
248                 if (error)
249                         goto back;
250                 bz = newtag->bounce_zone;
251
252                 if (ptoa(bz->total_bpages) < maxsize) {
253                         int pages;
254
255                         pages = atop(maxsize) - bz->total_bpages;
256
257                         /* Add pages to our bounce pool */
258                         if (alloc_bounce_pages(newtag, pages) < pages)
259                                 error = ENOMEM;
260                 }
261                 /* Performed initial allocation */
262                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
263         }
264 back:
265         if (error)
266                 kfree(newtag, M_DEVBUF);
267         else
268                 *dmat = newtag;
269         return error;
270 }
271
272 int
273 bus_dma_tag_destroy(bus_dma_tag_t dmat)
274 {
275         if (dmat != NULL) {
276                 if (dmat->map_count != 0)
277                         return (EBUSY);
278
279                 while (dmat != NULL) {
280                         bus_dma_tag_t parent;
281
282                         parent = dmat->parent;
283                         dmat->ref_count--;
284                         if (dmat->ref_count == 0) {
285                                 if (dmat->segments != NULL)
286                                         kfree(dmat->segments, M_DEVBUF);
287                                 kfree(dmat, M_DEVBUF);
288                                 /*
289                                  * Last reference count, so
290                                  * release our reference
291                                  * count on our parent.
292                                  */
293                                 dmat = parent;
294                         } else
295                                 dmat = NULL;
296                 }
297         }
298         return (0);
299 }
300
301 /*
302  * Allocate a handle for mapping from kva/uva/physical
303  * address space into bus device space.
304  */
305 int
306 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
307 {
308         int error;
309
310         error = 0;
311
312         if (dmat->segments == NULL) {
313                 KKASSERT(dmat->nsegments && dmat->nsegments < 16384);
314                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
315                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
316         }
317
318         if (dmat->flags & BUS_DMA_COULD_BOUNCE) {
319                 struct bounce_zone *bz;
320                 int maxpages;
321
322                 /* Must bounce */
323
324                 if (dmat->bounce_zone == NULL) {
325                         error = alloc_bounce_zone(dmat);
326                         if (error)
327                                 return error;
328                 }
329                 bz = dmat->bounce_zone;
330
331                 *mapp = kmalloc(sizeof(**mapp), M_DEVBUF, M_INTWAIT | M_ZERO);
332
333                 /* Initialize the new map */
334                 STAILQ_INIT(&((*mapp)->bpages));
335                 /*
336                  * Attempt to add pages to our pool on a per-instance
337                  * basis up to a sane limit.
338                  */
339                 maxpages = MIN(MAX_BPAGES, Maxmem - atop(dmat->lowaddr));
340                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0
341                  || (dmat->map_count > 0
342                   && bz->total_bpages < maxpages)) {
343                         int pages;
344
345                         if (dmat->lowaddr > bounce_lowaddr) {
346                                 /*
347                                  * Go through the pool and kill any pages
348                                  * that don't reside below lowaddr.
349                                  */
350                                 panic("bus_dmamap_create: page reallocation "
351                                       "not implemented");
352                         }
353
354                         pages = MAX(atop(dmat->maxsize), 1);
355                         pages = MIN(maxpages - bz->total_bpages, pages);
356                         pages = MAX(pages, 1);
357                         if (alloc_bounce_pages(dmat, pages) < pages)
358                                 error = ENOMEM;
359
360                         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0) {
361                                 if (!error)
362                                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
363                         } else {
364                                 error = 0;
365                         }
366                 }
367         } else {
368                 *mapp = NULL;
369         }
370         if (!error)
371                 dmat->map_count++;
372         return error;
373 }
374
375 /*
376  * Destroy a handle for mapping from kva/uva/physical
377  * address space into bus device space.
378  */
379 int
380 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
381 {
382         if (map != NULL) {
383                 if (STAILQ_FIRST(&map->bpages) != NULL)
384                         return (EBUSY);
385                 kfree(map, M_DEVBUF);
386         }
387         dmat->map_count--;
388         return (0);
389 }
390
391 /*
392  * Allocate a piece of memory that can be efficiently mapped into
393  * bus device space based on the constraints lited in the dma tag.
394  *
395  * mapp is degenerate.  By definition this allocation should not require
396  * bounce buffers so do not allocate a dma map.
397  */
398 int
399 bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
400                  bus_dmamap_t *mapp)
401 {
402         int mflags;
403
404         /* If we succeed, no mapping/bouncing will be required */
405         *mapp = NULL;
406
407         if (dmat->segments == NULL) {
408                 KKASSERT(dmat->nsegments < 16384);
409                 dmat->segments = kmalloc(sizeof(bus_dma_segment_t) * 
410                                         dmat->nsegments, M_DEVBUF, M_INTWAIT);
411         }
412
413         if (flags & BUS_DMA_NOWAIT)
414                 mflags = M_NOWAIT;
415         else
416                 mflags = M_WAITOK;
417         if (flags & BUS_DMA_ZERO)
418                 mflags |= M_ZERO;
419
420         if ((dmat->maxsize <= PAGE_SIZE) &&
421             dmat->lowaddr >= ptoa(Maxmem)) {
422                 *vaddr = kmalloc(dmat->maxsize, M_DEVBUF, mflags);
423                 /*
424                  * XXX Check whether the allocation crossed a page boundary
425                  * and retry with power-of-2 alignment in that case.
426                  */
427                 if ((((intptr_t)*vaddr) & PAGE_MASK) !=
428                     (((intptr_t)*vaddr + dmat->maxsize) & PAGE_MASK)) {
429                         size_t size;
430
431                         kfree(*vaddr, M_DEVBUF);
432                         /* XXX check for overflow? */
433                         for (size = 1; size <= dmat->maxsize; size <<= 1)
434                                 ;
435                         *vaddr = kmalloc(size, M_DEVBUF, mflags);
436                 }
437         } else {
438                 /*
439                  * XXX Use Contigmalloc until it is merged into this facility
440                  *     and handles multi-seg allocations.  Nobody is doing
441                  *     multi-seg allocations yet though.
442                  */
443                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
444                     0ul, dmat->lowaddr, dmat->alignment, dmat->boundary);
445         }
446         if (*vaddr == NULL)
447                 return (ENOMEM);
448         return (0);
449 }
450
451 /*
452  * Free a piece of memory and it's allociated dmamap, that was allocated
453  * via bus_dmamem_alloc.  Make the same choice for free/contigfree.
454  */
455 void
456 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
457 {
458         /*
459          * dmamem does not need to be bounced, so the map should be
460          * NULL
461          */
462         if (map != NULL)
463                 panic("bus_dmamem_free: Invalid map freed\n");
464         if ((dmat->maxsize <= PAGE_SIZE) &&
465             dmat->lowaddr >= ptoa(Maxmem))
466                 kfree(vaddr, M_DEVBUF);
467         else
468                 contigfree(vaddr, dmat->maxsize, M_DEVBUF);
469 }
470
471 static __inline vm_paddr_t
472 _bus_dma_extract(pmap_t pmap, vm_offset_t vaddr)
473 {
474         if (pmap)
475                 return pmap_extract(pmap, vaddr);
476         else
477                 return pmap_kextract(vaddr);
478 }
479
480 /*
481  * Utility function to load a linear buffer.  lastaddrp holds state
482  * between invocations (for multiple-buffer loads).  segp contains
483  * the segment following the starting one on entrace, and the ending
484  * segment on exit.  first indicates if this is the first invocation
485  * of this function.
486  */
487 static int
488 _bus_dmamap_load_buffer(bus_dma_tag_t dmat,
489                         bus_dmamap_t map,
490                         void *buf, bus_size_t buflen,
491                         pmap_t pmap,
492                         int flags,
493                         vm_paddr_t *lastpaddrp,
494                         int *segp,
495                         int first)
496 {
497         vm_offset_t vaddr;
498         vm_paddr_t paddr, nextpaddr;
499         bus_dma_segment_t *sg;
500         bus_addr_t bmask;
501         int seg, error = 0;
502
503         if (map == NULL)
504                 map = &nobounce_dmamap;
505
506         /*
507          * If we are being called during a callback, pagesneeded will
508          * be non-zero, so we can avoid doing the work twice.
509          */
510         if ((dmat->flags & BUS_DMA_COULD_BOUNCE) &&
511             map != &nobounce_dmamap && 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 = (vm_offset_t)buf;
519                 vendaddr = (vm_offset_t)buf + buflen;
520
521                 while (vaddr < vendaddr) {
522                         paddr = _bus_dma_extract(pmap, vaddr);
523                         if (run_filter(dmat, paddr) != 0)
524                                 map->pagesneeded++;
525                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
526                 }
527         }
528
529         /* Reserve Necessary Bounce Pages */
530         if (map->pagesneeded != 0) {
531                 crit_enter();
532                 if (flags & BUS_DMA_NOWAIT) {
533                         if (reserve_bounce_pages(dmat, map, 0) != 0) {
534                                 crit_exit();
535                                 return (ENOMEM);
536                         }
537                 } else {
538                         if (reserve_bounce_pages(dmat, map, 1) != 0) {
539                                 /* Queue us for resources */
540                                 map->dmat = dmat;
541                                 map->buf = buf;
542                                 map->buflen = buflen;
543
544                                 STAILQ_INSERT_TAIL(
545                                     &dmat->bounce_zone->bounce_map_waitinglist,
546                                     map, links);
547                                 crit_exit();
548
549                                 return (EINPROGRESS);
550                         }
551                 }
552                 crit_exit();
553         }
554
555         KKASSERT(*segp >= 1);
556         seg = *segp;
557         sg = &dmat->segments[seg - 1];
558
559         vaddr = (vm_offset_t)buf;
560         nextpaddr = *lastpaddrp;
561         bmask = ~(dmat->boundary - 1);  /* note: will be 0 if boundary is 0 */
562
563         /* force at least one segment */
564         do {
565                 bus_size_t size;
566
567                 /*
568                  * Per-page main loop
569                  */
570                 paddr = _bus_dma_extract(pmap, vaddr);
571                 size = PAGE_SIZE - (paddr & PAGE_MASK);
572                 if (size > buflen)
573                         size = buflen;
574                 if (map->pagesneeded != 0 && run_filter(dmat, paddr)) {
575                         /*
576                          * note: this paddr has the same in-page offset
577                          * as vaddr and thus the paddr above, so the
578                          * size does not have to be recalculated
579                          */
580                         paddr = add_bounce_page(dmat, map, vaddr, size);
581                 }
582
583                 /*
584                  * Fill in the bus_dma_segment
585                  */
586                 if (first) {
587                         sg->ds_addr = paddr;
588                         sg->ds_len = size;
589                         first = 0;
590                 } else if (paddr == nextpaddr) {
591                         sg->ds_len += size;
592                 } else {
593                         sg++;
594                         seg++;
595                         if (seg > dmat->nsegments)
596                                 break;
597                         sg->ds_addr = paddr;
598                         sg->ds_len = size;
599                 }
600                 nextpaddr = paddr + size;
601
602                 /*
603                  * Handle maxsegsz and boundary issues with a nested loop
604                  */
605                 for (;;) {
606                         bus_size_t tmpsize;
607
608                         /*
609                          * Limit to the boundary and maximum segment size
610                          */
611                         if (((nextpaddr - 1) ^ sg->ds_addr) & bmask) {
612                                 tmpsize = dmat->boundary -
613                                           (sg->ds_addr & ~bmask);
614                                 if (tmpsize > dmat->maxsegsz)
615                                         tmpsize = dmat->maxsegsz;
616                                 KKASSERT(tmpsize < sg->ds_len);
617                         } else if (sg->ds_len > dmat->maxsegsz) {
618                                 tmpsize = dmat->maxsegsz;
619                         } else {
620                                 break;
621                         }
622
623                         /*
624                          * Futz, split the data into a new segment.
625                          */
626                         if (seg >= dmat->nsegments)
627                                 goto fail;
628                         sg[1].ds_len = sg[0].ds_len - tmpsize;
629                         sg[1].ds_addr = sg[0].ds_addr + tmpsize;
630                         sg[0].ds_len = tmpsize;
631                         sg++;
632                         seg++;
633                 }
634
635                 /*
636                  * Adjust for loop
637                  */
638                 buflen -= size;
639                 vaddr += size;
640         } while (buflen > 0);
641 fail:
642         if (buflen != 0) {
643                 kprintf("bus_dmamap_load: Too many segs! buf_len = 0x%lx\n",
644                        (u_long)buflen);
645                 error = EFBIG;
646         }
647
648         *segp = seg;
649         *lastpaddrp = nextpaddr;
650
651         return error;
652 }
653
654 /*
655  * Map the buffer buf into bus space using the dmamap map.
656  */
657 int
658 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
659                 bus_size_t buflen, bus_dmamap_callback_t *callback,
660                 void *callback_arg, int flags)
661 {
662         vm_paddr_t lastaddr = 0;
663         int error, nsegs = 1;
664
665         if (map != NULL) {
666                 /*
667                  * XXX
668                  * Follow old semantics.  Once all of the callers are fixed,
669                  * we should get rid of these internal flag "adjustment".
670                  */
671                 flags &= ~BUS_DMA_NOWAIT;
672                 flags |= BUS_DMA_WAITOK;
673
674                 map->callback = callback;
675                 map->callback_arg = callback_arg;
676         }
677
678         error = _bus_dmamap_load_buffer(dmat, map, buf, buflen,
679                         NULL, flags, &lastaddr, &nsegs, 1);
680         if (error == EINPROGRESS)
681                 return error;
682
683         callback(callback_arg, dmat->segments, nsegs, error);
684         return 0;
685 }
686
687 /*
688  * Like _bus_dmamap_load(), but for mbufs.
689  */
690 int
691 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
692                      struct mbuf *m0,
693                      bus_dmamap_callback2_t *callback, void *callback_arg,
694                      int flags)
695 {
696         int nsegs, error;
697
698         M_ASSERTPKTHDR(m0);
699
700         /*
701          * XXX
702          * Follow old semantics.  Once all of the callers are fixed,
703          * we should get rid of these internal flag "adjustment".
704          */
705         flags &= ~BUS_DMA_WAITOK;
706         flags |= BUS_DMA_NOWAIT;
707
708         if (m0->m_pkthdr.len <= dmat->maxsize) {
709                 int first = 1;
710                 vm_paddr_t lastaddr = 0;
711                 struct mbuf *m;
712
713                 nsegs = 1;
714                 error = 0;
715                 for (m = m0; m != NULL && error == 0; m = m->m_next) {
716                         if (m->m_len == 0)
717                                 continue;
718
719                         error = _bus_dmamap_load_buffer(dmat, map,
720                                         m->m_data, m->m_len,
721                                         NULL, flags, &lastaddr,
722                                         &nsegs, first);
723                         first = 0;
724                 }
725         } else {
726                 nsegs = 0;
727                 error = EINVAL;
728         }
729
730         if (error) {
731                 /* force "no valid mappings" in callback */
732                 callback(callback_arg, dmat->segments, 0, 0, error);
733         } else {
734                 callback(callback_arg, dmat->segments, nsegs,
735                          m0->m_pkthdr.len, error);
736         }
737         return error;
738 }
739
740 /*
741  * Like _bus_dmamap_load(), but for uios.
742  */
743 int
744 bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
745                     struct uio *uio,
746                     bus_dmamap_callback2_t *callback, void *callback_arg,
747                     int flags)
748 {
749         vm_paddr_t lastaddr;
750         int nsegs, error, first, i;
751         bus_size_t resid;
752         struct iovec *iov;
753         pmap_t pmap;
754
755         /*
756          * XXX
757          * Follow old semantics.  Once all of the callers are fixed,
758          * we should get rid of these internal flag "adjustment".
759          */
760         flags &= ~BUS_DMA_WAITOK;
761         flags |= BUS_DMA_NOWAIT;
762
763         resid = uio->uio_resid;
764         iov = uio->uio_iov;
765
766         if (uio->uio_segflg == UIO_USERSPACE) {
767                 struct thread *td;
768
769                 td = uio->uio_td;
770                 KASSERT(td != NULL && td->td_proc != NULL,
771                         ("bus_dmamap_load_uio: USERSPACE but no proc"));
772                 pmap = vmspace_pmap(td->td_proc->p_vmspace);
773         } else {
774                 pmap = NULL;
775         }
776
777         error = 0;
778         nsegs = 1;
779         first = 1;
780         lastaddr = 0;
781         for (i = 0; i < uio->uio_iovcnt && resid != 0 && !error; i++) {
782                 /*
783                  * Now at the first iovec to load.  Load each iovec
784                  * until we have exhausted the residual count.
785                  */
786                 bus_size_t minlen =
787                         resid < iov[i].iov_len ? resid : iov[i].iov_len;
788                 caddr_t addr = (caddr_t) iov[i].iov_base;
789
790                 error = _bus_dmamap_load_buffer(dmat, map, addr, minlen,
791                                 pmap, flags, &lastaddr, &nsegs, first);
792                 first = 0;
793
794                 resid -= minlen;
795         }
796
797         if (error) {
798                 /* force "no valid mappings" in callback */
799                 callback(callback_arg, dmat->segments, 0, 0, error);
800         } else {
801                 callback(callback_arg, dmat->segments, nsegs,
802                          uio->uio_resid, error);
803         }
804         return error;
805 }
806
807 /*
808  * Release the mapping held by map.
809  */
810 void
811 _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
812 {
813         struct bounce_page *bpage;
814
815         while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
816                 STAILQ_REMOVE_HEAD(&map->bpages, links);
817                 free_bounce_page(dmat, bpage);
818         }
819 }
820
821 void
822 _bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
823 {
824         struct bounce_page *bpage;
825
826         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
827                 /*
828                  * Handle data bouncing.  We might also
829                  * want to add support for invalidating
830                  * the caches on broken hardware
831                  */
832                 switch (op) {
833                 case BUS_DMASYNC_PREWRITE:
834                         while (bpage != NULL) {
835                                 bcopy((void *)bpage->datavaddr,
836                                       (void *)bpage->vaddr,
837                                       bpage->datacount);
838                                 bpage = STAILQ_NEXT(bpage, links);
839                         }
840                         dmat->bounce_zone->total_bounced++;
841                         break;
842
843                 case BUS_DMASYNC_POSTREAD:
844                         while (bpage != NULL) {
845                                 bcopy((void *)bpage->vaddr,
846                                       (void *)bpage->datavaddr,
847                                       bpage->datacount);
848                                 bpage = STAILQ_NEXT(bpage, links);
849                         }
850                         dmat->bounce_zone->total_bounced++;
851                         break;
852
853                 case BUS_DMASYNC_PREREAD:
854                 case BUS_DMASYNC_POSTWRITE:
855                         /* No-ops */
856                         break;
857                 }
858         }
859 }
860
861 static int
862 alloc_bounce_zone(bus_dma_tag_t dmat)
863 {
864         struct bounce_zone *bz, *new_bz;
865         lwkt_tokref ref;
866
867         KASSERT(dmat->bounce_zone == NULL,
868                 ("bounce zone was already assigned\n"));
869
870         new_bz = kmalloc(sizeof(*new_bz), M_DEVBUF, M_INTWAIT | M_ZERO);
871
872         lwkt_gettoken(&ref, &bounce_zone_tok);
873
874         /* Check to see if we already have a suitable zone */
875         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
876                 if (dmat->alignment <= bz->alignment &&
877                     dmat->boundary <= bz->boundary &&
878                     dmat->lowaddr >= bz->lowaddr) {
879                         lwkt_reltoken(&ref);
880
881                         dmat->bounce_zone = bz;
882                         kfree(new_bz, M_DEVBUF);
883                         return 0;
884                 }
885         }
886         bz = new_bz;
887
888         STAILQ_INIT(&bz->bounce_page_list);
889         STAILQ_INIT(&bz->bounce_map_waitinglist);
890         bz->free_bpages = 0;
891         bz->reserved_bpages = 0;
892         bz->active_bpages = 0;
893         bz->lowaddr = dmat->lowaddr;
894         bz->alignment = dmat->alignment;
895         bz->boundary = dmat->boundary;
896         ksnprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
897         busdma_zonecount++;
898         ksnprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
899         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
900
901         lwkt_reltoken(&ref);
902
903         dmat->bounce_zone = bz;
904
905         sysctl_ctx_init(&bz->sysctl_ctx);
906         bz->sysctl_tree = SYSCTL_ADD_NODE(&bz->sysctl_ctx,
907             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
908             CTLFLAG_RD, 0, "");
909         if (bz->sysctl_tree == NULL) {
910                 sysctl_ctx_free(&bz->sysctl_ctx);
911                 return 0;       /* XXX error code? */
912         }
913
914         SYSCTL_ADD_INT(&bz->sysctl_ctx,
915             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
916             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
917             "Total bounce pages");
918         SYSCTL_ADD_INT(&bz->sysctl_ctx,
919             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
920             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
921             "Free bounce pages");
922         SYSCTL_ADD_INT(&bz->sysctl_ctx,
923             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
924             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
925             "Reserved bounce pages");
926         SYSCTL_ADD_INT(&bz->sysctl_ctx,
927             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
928             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
929             "Active bounce pages");
930         SYSCTL_ADD_INT(&bz->sysctl_ctx,
931             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
932             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
933             "Total bounce requests");
934         SYSCTL_ADD_INT(&bz->sysctl_ctx,
935             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
936             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
937             "Total bounce requests that were deferred");
938         SYSCTL_ADD_INT(&bz->sysctl_ctx,
939             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
940             "reserve_failed", CTLFLAG_RD, &bz->reserve_failed, 0,
941             "Total bounce page reservations that were failed");
942         SYSCTL_ADD_STRING(&bz->sysctl_ctx,
943             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
944             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
945         SYSCTL_ADD_INT(&bz->sysctl_ctx,
946             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
947             "alignment", CTLFLAG_RD, &bz->alignment, 0, "");
948         SYSCTL_ADD_INT(&bz->sysctl_ctx,
949             SYSCTL_CHILDREN(bz->sysctl_tree), OID_AUTO,
950             "boundary", CTLFLAG_RD, &bz->boundary, 0, "");
951
952         return 0;
953 }
954
955 static int
956 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
957 {
958         struct bounce_zone *bz = dmat->bounce_zone;
959         int count = 0;
960
961         while (numpages > 0) {
962                 struct bounce_page *bpage;
963
964                 bpage = kmalloc(sizeof(*bpage), M_DEVBUF, M_INTWAIT | M_ZERO);
965
966                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_DEVBUF,
967                                                          M_NOWAIT, 0ul,
968                                                          dmat->lowaddr,
969                                                          PAGE_SIZE,
970                                                          0);
971                 if (bpage->vaddr == 0) {
972                         kfree(bpage, M_DEVBUF);
973                         break;
974                 }
975                 bpage->busaddr = pmap_kextract(bpage->vaddr);
976
977                 crit_enter();
978                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
979                 total_bounce_pages++;
980                 bz->total_bpages++;
981                 bz->free_bpages++;
982                 crit_exit();
983
984                 count++;
985                 numpages--;
986         }
987         return count;
988 }
989
990 static int
991 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
992 {
993         struct bounce_zone *bz = dmat->bounce_zone;
994         int pages;
995
996         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
997         if (!commit && map->pagesneeded > (map->pagesreserved + pages)) {
998                 bz->reserve_failed++;
999                 return (map->pagesneeded - (map->pagesreserved + pages));
1000         }
1001         bz->free_bpages -= pages;
1002         bz->reserved_bpages += pages;
1003         map->pagesreserved += pages;
1004         pages = map->pagesneeded - map->pagesreserved;
1005
1006         return pages;
1007 }
1008
1009 static bus_addr_t
1010 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1011                 bus_size_t size)
1012 {
1013         struct bounce_zone *bz = dmat->bounce_zone;
1014         struct bounce_page *bpage;
1015
1016         if (map->pagesneeded == 0)
1017                 panic("add_bounce_page: map doesn't need any pages");
1018         map->pagesneeded--;
1019
1020         if (map->pagesreserved == 0)
1021                 panic("add_bounce_page: map doesn't need any pages");
1022         map->pagesreserved--;
1023
1024         crit_enter();
1025         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1026         if (bpage == NULL)
1027                 panic("add_bounce_page: free page list is empty");
1028
1029         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1030         bz->reserved_bpages--;
1031         bz->active_bpages++;
1032         crit_exit();
1033
1034         bpage->datavaddr = vaddr;
1035         bpage->datacount = size;
1036         STAILQ_INSERT_TAIL(&map->bpages, bpage, links);
1037         return bpage->busaddr;
1038 }
1039
1040 static void
1041 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1042 {
1043         struct bounce_zone *bz = dmat->bounce_zone;
1044         struct bus_dmamap *map;
1045
1046         bpage->datavaddr = 0;
1047         bpage->datacount = 0;
1048
1049         crit_enter();
1050         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1051         bz->free_bpages++;
1052         bz->active_bpages--;
1053         if ((map = STAILQ_FIRST(&bz->bounce_map_waitinglist)) != NULL) {
1054                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1055                         STAILQ_REMOVE_HEAD(&bz->bounce_map_waitinglist, links);
1056                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1057                                            map, links);
1058                         busdma_swi_pending = 1;
1059                         bz->total_deferred++;
1060                         setsoftvm();
1061                 }
1062         }
1063         crit_exit();
1064 }
1065
1066 void
1067 busdma_swi(void)
1068 {
1069         struct bus_dmamap *map;
1070
1071         crit_enter();
1072         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1073                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1074                 crit_exit();
1075                 bus_dmamap_load(map->dmat, map, map->buf, map->buflen,
1076                                 map->callback, map->callback_arg, /*flags*/0);
1077                 crit_enter();
1078         }
1079         crit_exit();
1080 }