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