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