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