]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/busdma_machdep-v6.c
Merge lld trunk r321017 to contrib/llvm/tools/lld.
[FreeBSD/FreeBSD.git] / sys / arm / arm / busdma_machdep-v6.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012-2015 Ian Lepore
5  * Copyright (c) 2010 Mark Tinguely
6  * Copyright (c) 2004 Olivier Houchard
7  * Copyright (c) 2002 Peter Grehan
8  * Copyright (c) 1997, 1998 Justin T. Gibbs.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions, and the following disclaimer,
16  *    without modification, immediately at the beginning of the file.
17  * 2. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
24  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *  From i386/busdma_machdep.c 191438 2009-04-23 20:24:19Z jhb
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/bus.h>
42 #include <sys/busdma_bufalloc.h>
43 #include <sys/counter.h>
44 #include <sys/interrupt.h>
45 #include <sys/kernel.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/memdesc.h>
49 #include <sys/proc.h>
50 #include <sys/mutex.h>
51 #include <sys/sysctl.h>
52 #include <sys/uio.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_extern.h>
58 #include <vm/vm_kern.h>
59
60 #include <machine/atomic.h>
61 #include <machine/bus.h>
62 #include <machine/cpu.h>
63 #include <machine/md_var.h>
64
65 #define BUSDMA_DCACHE_ALIGN     cpuinfo.dcache_line_size
66 #define BUSDMA_DCACHE_MASK      cpuinfo.dcache_line_mask
67
68 #define MAX_BPAGES              64
69 #define MAX_DMA_SEGMENTS        4096
70 #define BUS_DMA_EXCL_BOUNCE     BUS_DMA_BUS2
71 #define BUS_DMA_ALIGN_BOUNCE    BUS_DMA_BUS3
72 #define BUS_DMA_COULD_BOUNCE    (BUS_DMA_EXCL_BOUNCE | BUS_DMA_ALIGN_BOUNCE)
73 #define BUS_DMA_MIN_ALLOC_COMP  BUS_DMA_BUS4
74
75 struct bounce_zone;
76
77 struct bus_dma_tag {
78         bus_dma_tag_t           parent;
79         bus_size_t              alignment;
80         bus_addr_t              boundary;
81         bus_addr_t              lowaddr;
82         bus_addr_t              highaddr;
83         bus_dma_filter_t        *filter;
84         void                    *filterarg;
85         bus_size_t              maxsize;
86         u_int                   nsegments;
87         bus_size_t              maxsegsz;
88         int                     flags;
89         int                     ref_count;
90         int                     map_count;
91         bus_dma_lock_t          *lockfunc;
92         void                    *lockfuncarg;
93         struct bounce_zone      *bounce_zone;
94 };
95
96 struct bounce_page {
97         vm_offset_t     vaddr;          /* kva of bounce buffer */
98         bus_addr_t      busaddr;        /* Physical address */
99         vm_offset_t     datavaddr;      /* kva of client data */
100         vm_page_t       datapage;       /* physical page of client data */
101         vm_offset_t     dataoffs;       /* page offset of client data */
102         bus_size_t      datacount;      /* client data count */
103         STAILQ_ENTRY(bounce_page) links;
104 };
105
106 struct sync_list {
107         vm_offset_t     vaddr;          /* kva of client data */
108         bus_addr_t      paddr;          /* physical address */
109         vm_page_t       pages;          /* starting page of client data */
110         bus_size_t      datacount;      /* client data count */
111 };
112
113 int busdma_swi_pending;
114
115 struct bounce_zone {
116         STAILQ_ENTRY(bounce_zone) links;
117         STAILQ_HEAD(bp_list, bounce_page) bounce_page_list;
118         int             total_bpages;
119         int             free_bpages;
120         int             reserved_bpages;
121         int             active_bpages;
122         int             total_bounced;
123         int             total_deferred;
124         int             map_count;
125         bus_size_t      alignment;
126         bus_addr_t      lowaddr;
127         char            zoneid[8];
128         char            lowaddrid[20];
129         struct sysctl_ctx_list sysctl_tree;
130         struct sysctl_oid *sysctl_tree_top;
131 };
132
133 static struct mtx bounce_lock;
134 static int total_bpages;
135 static int busdma_zonecount;
136 static uint32_t tags_total;
137 static uint32_t maps_total;
138 static uint32_t maps_dmamem;
139 static uint32_t maps_coherent;
140 static counter_u64_t maploads_total;
141 static counter_u64_t maploads_bounced;
142 static counter_u64_t maploads_coherent;
143 static counter_u64_t maploads_dmamem;
144 static counter_u64_t maploads_mbuf;
145 static counter_u64_t maploads_physmem;
146
147 static STAILQ_HEAD(, bounce_zone) bounce_zone_list;
148
149 SYSCTL_NODE(_hw, OID_AUTO, busdma, CTLFLAG_RD, 0, "Busdma parameters");
150 SYSCTL_UINT(_hw_busdma, OID_AUTO, tags_total, CTLFLAG_RD, &tags_total, 0,
151    "Number of active tags");
152 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_total, CTLFLAG_RD, &maps_total, 0,
153    "Number of active maps");
154 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_dmamem, CTLFLAG_RD, &maps_dmamem, 0,
155    "Number of active maps for bus_dmamem_alloc buffers");
156 SYSCTL_UINT(_hw_busdma, OID_AUTO, maps_coherent, CTLFLAG_RD, &maps_coherent, 0,
157    "Number of active maps with BUS_DMA_COHERENT flag set");
158 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_total, CTLFLAG_RD,
159     &maploads_total, "Number of load operations performed");
160 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_bounced, CTLFLAG_RD,
161     &maploads_bounced, "Number of load operations that used bounce buffers");
162 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_coherent, CTLFLAG_RD,
163     &maploads_dmamem, "Number of load operations on BUS_DMA_COHERENT memory");
164 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_dmamem, CTLFLAG_RD,
165     &maploads_dmamem, "Number of load operations on bus_dmamem_alloc buffers");
166 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_mbuf, CTLFLAG_RD,
167     &maploads_mbuf, "Number of load operations for mbufs");
168 SYSCTL_COUNTER_U64(_hw_busdma, OID_AUTO, maploads_physmem, CTLFLAG_RD,
169     &maploads_physmem, "Number of load operations on physical buffers");
170 SYSCTL_INT(_hw_busdma, OID_AUTO, total_bpages, CTLFLAG_RD, &total_bpages, 0,
171    "Total bounce pages");
172
173 struct bus_dmamap {
174         struct bp_list          bpages;
175         int                     pagesneeded;
176         int                     pagesreserved;
177         bus_dma_tag_t           dmat;
178         struct memdesc          mem;
179         bus_dmamap_callback_t   *callback;
180         void                    *callback_arg;
181         int                     flags;
182 #define DMAMAP_COHERENT         (1 << 0)
183 #define DMAMAP_DMAMEM_ALLOC     (1 << 1)
184 #define DMAMAP_MBUF             (1 << 2)
185         STAILQ_ENTRY(bus_dmamap) links;
186         bus_dma_segment_t       *segments;
187         int                     sync_count;
188         struct sync_list        slist[];
189 };
190
191 static STAILQ_HEAD(, bus_dmamap) bounce_map_waitinglist;
192 static STAILQ_HEAD(, bus_dmamap) bounce_map_callbacklist;
193
194 static void init_bounce_pages(void *dummy);
195 static int alloc_bounce_zone(bus_dma_tag_t dmat);
196 static int alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages);
197 static int reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
198     int commit);
199 static bus_addr_t add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map,
200     vm_offset_t vaddr, bus_addr_t addr, bus_size_t size);
201 static void free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage);
202 static void _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap,
203     bus_dmamap_t map, void *buf, bus_size_t buflen, int flags);
204 static void _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map,
205     vm_paddr_t buf, bus_size_t buflen, int flags);
206 static int _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map,
207     int flags);
208 static void dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size);
209 static void dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op);
210
211 static busdma_bufalloc_t coherent_allocator;    /* Cache of coherent buffers */
212 static busdma_bufalloc_t standard_allocator;    /* Cache of standard buffers */
213
214 MALLOC_DEFINE(M_BUSDMA, "busdma", "busdma metadata");
215 MALLOC_DEFINE(M_BOUNCE, "bounce", "busdma bounce pages");
216
217 static void
218 busdma_init(void *dummy)
219 {
220         int uma_flags;
221
222         maploads_total    = counter_u64_alloc(M_WAITOK);
223         maploads_bounced  = counter_u64_alloc(M_WAITOK);
224         maploads_coherent = counter_u64_alloc(M_WAITOK);
225         maploads_dmamem   = counter_u64_alloc(M_WAITOK);
226         maploads_mbuf     = counter_u64_alloc(M_WAITOK);
227         maploads_physmem  = counter_u64_alloc(M_WAITOK);
228
229         uma_flags = 0;
230
231         /* Create a cache of buffers in standard (cacheable) memory. */
232         standard_allocator = busdma_bufalloc_create("buffer",
233             BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
234             NULL,               /* uma_alloc func */
235             NULL,               /* uma_free func */
236             uma_flags);         /* uma_zcreate_flags */
237
238 #ifdef INVARIANTS
239         /*
240          * Force UMA zone to allocate service structures like
241          * slabs using own allocator. uma_debug code performs
242          * atomic ops on uma_slab_t fields and safety of this
243          * operation is not guaranteed for write-back caches
244          */
245         uma_flags = UMA_ZONE_OFFPAGE;
246 #endif
247         /*
248          * Create a cache of buffers in uncacheable memory, to implement the
249          * BUS_DMA_COHERENT (and potentially BUS_DMA_NOCACHE) flag.
250          */
251         coherent_allocator = busdma_bufalloc_create("coherent",
252             BUSDMA_DCACHE_ALIGN,/* minimum_alignment */
253             busdma_bufalloc_alloc_uncacheable,
254             busdma_bufalloc_free_uncacheable,
255             uma_flags); /* uma_zcreate_flags */
256 }
257
258 /*
259  * This init historically used SI_SUB_VM, but now the init code requires
260  * malloc(9) using M_BUSDMA memory and the pcpu zones for counter(9), which get
261  * set up by SI_SUB_KMEM and SI_ORDER_LAST, so we'll go right after that by
262  * using SI_SUB_KMEM+1.
263  */
264 SYSINIT(busdma, SI_SUB_KMEM+1, SI_ORDER_FIRST, busdma_init, NULL);
265
266 /*
267  * This routine checks the exclusion zone constraints from a tag against the
268  * physical RAM available on the machine.  If a tag specifies an exclusion zone
269  * but there's no RAM in that zone, then we avoid allocating resources to bounce
270  * a request, and we can use any memory allocator (as opposed to needing
271  * kmem_alloc_contig() just because it can allocate pages in an address range).
272  *
273  * Most tags have BUS_SPACE_MAXADDR or BUS_SPACE_MAXADDR_32BIT (they are the
274  * same value on 32-bit architectures) as their lowaddr constraint, and we can't
275  * possibly have RAM at an address higher than the highest address we can
276  * express, so we take a fast out.
277  */
278 static int
279 exclusion_bounce_check(vm_offset_t lowaddr, vm_offset_t highaddr)
280 {
281         int i;
282
283         if (lowaddr >= BUS_SPACE_MAXADDR)
284                 return (0);
285
286         for (i = 0; phys_avail[i] && phys_avail[i + 1]; i += 2) {
287                 if ((lowaddr >= phys_avail[i] && lowaddr < phys_avail[i + 1]) ||
288                     (lowaddr < phys_avail[i] && highaddr >= phys_avail[i]))
289                         return (1);
290         }
291         return (0);
292 }
293
294 /*
295  * Return true if the tag has an exclusion zone that could lead to bouncing.
296  */
297 static __inline int
298 exclusion_bounce(bus_dma_tag_t dmat)
299 {
300
301         return (dmat->flags & BUS_DMA_EXCL_BOUNCE);
302 }
303
304 /*
305  * Return true if the given address does not fall on the alignment boundary.
306  */
307 static __inline int
308 alignment_bounce(bus_dma_tag_t dmat, bus_addr_t addr)
309 {
310
311         return (addr & (dmat->alignment - 1));
312 }
313
314 /*
315  * Return true if the DMA should bounce because the start or end does not fall
316  * on a cacheline boundary (which would require a partial cacheline flush).
317  * COHERENT memory doesn't trigger cacheline flushes.  Memory allocated by
318  * bus_dmamem_alloc() is always aligned to cacheline boundaries, and there's a
319  * strict rule that such memory cannot be accessed by the CPU while DMA is in
320  * progress (or by multiple DMA engines at once), so that it's always safe to do
321  * full cacheline flushes even if that affects memory outside the range of a
322  * given DMA operation that doesn't involve the full allocated buffer.  If we're
323  * mapping an mbuf, that follows the same rules as a buffer we allocated.
324  */
325 static __inline int
326 cacheline_bounce(bus_dmamap_t map, bus_addr_t addr, bus_size_t size)
327 {
328
329         if (map->flags & (DMAMAP_DMAMEM_ALLOC | DMAMAP_COHERENT | DMAMAP_MBUF))
330                 return (0);
331         return ((addr | size) & BUSDMA_DCACHE_MASK);
332 }
333
334 /*
335  * Return true if we might need to bounce the DMA described by addr and size.
336  *
337  * This is used to quick-check whether we need to do the more expensive work of
338  * checking the DMA page-by-page looking for alignment and exclusion bounces.
339  *
340  * Note that the addr argument might be either virtual or physical.  It doesn't
341  * matter because we only look at the low-order bits, which are the same in both
342  * address spaces.
343  */
344 static __inline int
345 might_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t addr,
346     bus_size_t size)
347 {
348
349         return ((dmat->flags & BUS_DMA_EXCL_BOUNCE) ||
350             alignment_bounce(dmat, addr) ||
351             cacheline_bounce(map, addr, size));
352 }
353
354 /*
355  * Return true if we must bounce the DMA described by paddr and size.
356  *
357  * Bouncing can be triggered by DMA that doesn't begin and end on cacheline
358  * boundaries, or doesn't begin on an alignment boundary, or falls within the
359  * exclusion zone of any tag in the ancestry chain.
360  *
361  * For exclusions, walk the chain of tags comparing paddr to the exclusion zone
362  * within each tag.  If the tag has a filter function, use it to decide whether
363  * the DMA needs to bounce, otherwise any DMA within the zone bounces.
364  */
365 static int
366 must_bounce(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t paddr,
367     bus_size_t size)
368 {
369
370         if (cacheline_bounce(map, paddr, size))
371                 return (1);
372
373         /*
374          *  The tag already contains ancestors' alignment restrictions so this
375          *  check doesn't need to be inside the loop.
376          */
377         if (alignment_bounce(dmat, paddr))
378                 return (1);
379
380         /*
381          * Even though each tag has an exclusion zone that is a superset of its
382          * own and all its ancestors' exclusions, the exclusion zone of each tag
383          * up the chain must be checked within the loop, because the busdma
384          * rules say the filter function is called only when the address lies
385          * within the low-highaddr range of the tag that filterfunc belongs to.
386          */
387         while (dmat != NULL && exclusion_bounce(dmat)) {
388                 if ((paddr >= dmat->lowaddr && paddr <= dmat->highaddr) &&
389                     (dmat->filter == NULL ||
390                     dmat->filter(dmat->filterarg, paddr) != 0))
391                         return (1);
392                 dmat = dmat->parent;
393         }
394
395         return (0);
396 }
397
398 /*
399  * Convenience function for manipulating driver locks from busdma (during
400  * busdma_swi, for example).  Drivers that don't provide their own locks
401  * should specify &Giant to dmat->lockfuncarg.  Drivers that use their own
402  * non-mutex locking scheme don't have to use this at all.
403  */
404 void
405 busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
406 {
407         struct mtx *dmtx;
408
409         dmtx = (struct mtx *)arg;
410         switch (op) {
411         case BUS_DMA_LOCK:
412                 mtx_lock(dmtx);
413                 break;
414         case BUS_DMA_UNLOCK:
415                 mtx_unlock(dmtx);
416                 break;
417         default:
418                 panic("Unknown operation 0x%x for busdma_lock_mutex!", op);
419         }
420 }
421
422 /*
423  * dflt_lock should never get called.  It gets put into the dma tag when
424  * lockfunc == NULL, which is only valid if the maps that are associated
425  * with the tag are meant to never be defered.
426  * XXX Should have a way to identify which driver is responsible here.
427  */
428 static void
429 dflt_lock(void *arg, bus_dma_lock_op_t op)
430 {
431
432         panic("driver error: busdma dflt_lock called");
433 }
434
435 /*
436  * Allocate a device specific dma_tag.
437  */
438 int
439 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
440     bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
441     bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize,
442     int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
443     void *lockfuncarg, bus_dma_tag_t *dmat)
444 {
445         bus_dma_tag_t newtag;
446         int error = 0;
447
448         /* Basic sanity checking. */
449         KASSERT(boundary == 0 || powerof2(boundary),
450             ("dma tag boundary %lu, must be a power of 2", boundary));
451         KASSERT(boundary == 0 || boundary >= maxsegsz,
452             ("dma tag boundary %lu is < maxsegsz %lu\n", boundary, maxsegsz));
453         KASSERT(alignment != 0 && powerof2(alignment),
454             ("dma tag alignment %lu, must be non-zero power of 2", alignment));
455         KASSERT(maxsegsz != 0, ("dma tag maxsegsz must not be zero"));
456
457         /* Return a NULL tag on failure */
458         *dmat = NULL;
459
460         newtag = (bus_dma_tag_t)malloc(sizeof(*newtag), M_BUSDMA,
461             M_ZERO | M_NOWAIT);
462         if (newtag == NULL) {
463                 CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
464                     __func__, newtag, 0, error);
465                 return (ENOMEM);
466         }
467
468         newtag->parent = parent;
469         newtag->alignment = alignment;
470         newtag->boundary = boundary;
471         newtag->lowaddr = trunc_page((vm_paddr_t)lowaddr) + (PAGE_SIZE - 1);
472         newtag->highaddr = trunc_page((vm_paddr_t)highaddr) +
473             (PAGE_SIZE - 1);
474         newtag->filter = filter;
475         newtag->filterarg = filterarg;
476         newtag->maxsize = maxsize;
477         newtag->nsegments = nsegments;
478         newtag->maxsegsz = maxsegsz;
479         newtag->flags = flags;
480         newtag->ref_count = 1; /* Count ourself */
481         newtag->map_count = 0;
482         if (lockfunc != NULL) {
483                 newtag->lockfunc = lockfunc;
484                 newtag->lockfuncarg = lockfuncarg;
485         } else {
486                 newtag->lockfunc = dflt_lock;
487                 newtag->lockfuncarg = NULL;
488         }
489
490         /* Take into account any restrictions imposed by our parent tag */
491         if (parent != NULL) {
492                 newtag->lowaddr = MIN(parent->lowaddr, newtag->lowaddr);
493                 newtag->highaddr = MAX(parent->highaddr, newtag->highaddr);
494                 newtag->alignment = MAX(parent->alignment, newtag->alignment);
495                 newtag->flags |= parent->flags & BUS_DMA_COULD_BOUNCE;
496                 newtag->flags |= parent->flags & BUS_DMA_COHERENT;
497                 if (newtag->boundary == 0)
498                         newtag->boundary = parent->boundary;
499                 else if (parent->boundary != 0)
500                         newtag->boundary = MIN(parent->boundary,
501                                                newtag->boundary);
502                 if (newtag->filter == NULL) {
503                         /*
504                          * Short circuit to looking at our parent directly
505                          * since we have encapsulated all of its information
506                          */
507                         newtag->filter = parent->filter;
508                         newtag->filterarg = parent->filterarg;
509                         newtag->parent = parent->parent;
510                 }
511                 if (newtag->parent != NULL)
512                         atomic_add_int(&parent->ref_count, 1);
513         }
514
515         if (exclusion_bounce_check(newtag->lowaddr, newtag->highaddr))
516                 newtag->flags |= BUS_DMA_EXCL_BOUNCE;
517         if (alignment_bounce(newtag, 1))
518                 newtag->flags |= BUS_DMA_ALIGN_BOUNCE;
519
520         /*
521          * Any request can auto-bounce due to cacheline alignment, in addition
522          * to any alignment or boundary specifications in the tag, so if the
523          * ALLOCNOW flag is set, there's always work to do.
524          */
525         if ((flags & BUS_DMA_ALLOCNOW) != 0) {
526                 struct bounce_zone *bz;
527                 /*
528                  * Round size up to a full page, and add one more page because
529                  * there can always be one more boundary crossing than the
530                  * number of pages in a transfer.
531                  */
532                 maxsize = roundup2(maxsize, PAGE_SIZE) + PAGE_SIZE;
533
534                 if ((error = alloc_bounce_zone(newtag)) != 0) {
535                         free(newtag, M_BUSDMA);
536                         return (error);
537                 }
538                 bz = newtag->bounce_zone;
539
540                 if (ptoa(bz->total_bpages) < maxsize) {
541                         int pages;
542
543                         pages = atop(maxsize) - bz->total_bpages;
544
545                         /* Add pages to our bounce pool */
546                         if (alloc_bounce_pages(newtag, pages) < pages)
547                                 error = ENOMEM;
548                 }
549                 /* Performed initial allocation */
550                 newtag->flags |= BUS_DMA_MIN_ALLOC_COMP;
551         } else
552                 newtag->bounce_zone = NULL;
553
554         if (error != 0) {
555                 free(newtag, M_BUSDMA);
556         } else {
557                 atomic_add_32(&tags_total, 1);
558                 *dmat = newtag;
559         }
560         CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
561             __func__, newtag, (newtag != NULL ? newtag->flags : 0), error);
562         return (error);
563 }
564
565 int
566 bus_dma_tag_destroy(bus_dma_tag_t dmat)
567 {
568         bus_dma_tag_t dmat_copy;
569         int error;
570
571         error = 0;
572         dmat_copy = dmat;
573
574         if (dmat != NULL) {
575
576                 if (dmat->map_count != 0) {
577                         error = EBUSY;
578                         goto out;
579                 }
580
581                 while (dmat != NULL) {
582                         bus_dma_tag_t parent;
583
584                         parent = dmat->parent;
585                         atomic_subtract_int(&dmat->ref_count, 1);
586                         if (dmat->ref_count == 0) {
587                                 atomic_subtract_32(&tags_total, 1);
588                                 free(dmat, M_BUSDMA);
589                                 /*
590                                  * Last reference count, so
591                                  * release our reference
592                                  * count on our parent.
593                                  */
594                                 dmat = parent;
595                         } else
596                                 dmat = NULL;
597                 }
598         }
599 out:
600         CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat_copy, error);
601         return (error);
602 }
603
604 static int
605 allocate_bz_and_pages(bus_dma_tag_t dmat, bus_dmamap_t mapp)
606 {
607         struct bounce_zone *bz;
608         int maxpages;
609         int error;
610
611         if (dmat->bounce_zone == NULL)
612                 if ((error = alloc_bounce_zone(dmat)) != 0)
613                         return (error);
614         bz = dmat->bounce_zone;
615         /* Initialize the new map */
616         STAILQ_INIT(&(mapp->bpages));
617
618         /*
619          * Attempt to add pages to our pool on a per-instance basis up to a sane
620          * limit.  Even if the tag isn't flagged as COULD_BOUNCE due to
621          * alignment and boundary constraints, it could still auto-bounce due to
622          * cacheline alignment, which requires at most two bounce pages.
623          */
624         if (dmat->flags & BUS_DMA_COULD_BOUNCE)
625                 maxpages = MAX_BPAGES;
626         else
627                 maxpages = 2 * bz->map_count;
628         if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0 ||
629             (bz->map_count > 0 && bz->total_bpages < maxpages)) {
630                 int pages;
631
632                 pages = atop(roundup2(dmat->maxsize, PAGE_SIZE)) + 1;
633                 pages = MIN(maxpages - bz->total_bpages, pages);
634                 pages = MAX(pages, 2);
635                 if (alloc_bounce_pages(dmat, pages) < pages)
636                         return (ENOMEM);
637
638                 if ((dmat->flags & BUS_DMA_MIN_ALLOC_COMP) == 0)
639                         dmat->flags |= BUS_DMA_MIN_ALLOC_COMP;
640         }
641         bz->map_count++;
642         return (0);
643 }
644
645 static bus_dmamap_t
646 allocate_map(bus_dma_tag_t dmat, int mflags)
647 {
648         int mapsize, segsize;
649         bus_dmamap_t map;
650
651         /*
652          * Allocate the map.  The map structure ends with an embedded
653          * variable-sized array of sync_list structures.  Following that
654          * we allocate enough extra space to hold the array of bus_dma_segments.
655          */
656         KASSERT(dmat->nsegments <= MAX_DMA_SEGMENTS,
657            ("cannot allocate %u dma segments (max is %u)",
658             dmat->nsegments, MAX_DMA_SEGMENTS));
659         segsize = sizeof(struct bus_dma_segment) * dmat->nsegments;
660         mapsize = sizeof(*map) + sizeof(struct sync_list) * dmat->nsegments;
661         map = malloc(mapsize + segsize, M_BUSDMA, mflags | M_ZERO);
662         if (map == NULL) {
663                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
664                 return (NULL);
665         }
666         map->segments = (bus_dma_segment_t *)((uintptr_t)map + mapsize);
667         return (map);
668 }
669
670 /*
671  * Allocate a handle for mapping from kva/uva/physical
672  * address space into bus device space.
673  */
674 int
675 bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
676 {
677         bus_dmamap_t map;
678         int error = 0;
679
680         *mapp = map = allocate_map(dmat, M_NOWAIT);
681         if (map == NULL) {
682                 CTR3(KTR_BUSDMA, "%s: tag %p error %d", __func__, dmat, ENOMEM);
683                 return (ENOMEM);
684         }
685
686         /*
687          * Bouncing might be required if the driver asks for an exclusion
688          * region, a data alignment that is stricter than 1, or DMA that begins
689          * or ends with a partial cacheline.  Whether bouncing will actually
690          * happen can't be known until mapping time, but we need to pre-allocate
691          * resources now because we might not be allowed to at mapping time.
692          */
693         error = allocate_bz_and_pages(dmat, map);
694         if (error != 0) {
695                 free(map, M_BUSDMA);
696                 *mapp = NULL;
697                 return (error);
698         }
699         if (map->flags & DMAMAP_COHERENT)
700                 atomic_add_32(&maps_coherent, 1);
701         atomic_add_32(&maps_total, 1);
702         dmat->map_count++;
703
704         return (0);
705 }
706
707 /*
708  * Destroy a handle for mapping from kva/uva/physical
709  * address space into bus device space.
710  */
711 int
712 bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
713 {
714
715         if (STAILQ_FIRST(&map->bpages) != NULL || map->sync_count != 0) {
716                 CTR3(KTR_BUSDMA, "%s: tag %p error %d",
717                     __func__, dmat, EBUSY);
718                 return (EBUSY);
719         }
720         if (dmat->bounce_zone)
721                 dmat->bounce_zone->map_count--;
722         if (map->flags & DMAMAP_COHERENT)
723                 atomic_subtract_32(&maps_coherent, 1);
724         atomic_subtract_32(&maps_total, 1);
725         free(map, M_BUSDMA);
726         dmat->map_count--;
727         CTR2(KTR_BUSDMA, "%s: tag %p error 0", __func__, dmat);
728         return (0);
729 }
730
731 /*
732  * Allocate a piece of memory that can be efficiently mapped into bus device
733  * space based on the constraints listed in the dma tag.  Returns a pointer to
734  * the allocated memory, and a pointer to an associated bus_dmamap.
735  */
736 int
737 bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
738     bus_dmamap_t *mapp)
739 {
740         busdma_bufalloc_t ba;
741         struct busdma_bufzone *bufzone;
742         bus_dmamap_t map;
743         vm_memattr_t memattr;
744         int mflags;
745
746         if (flags & BUS_DMA_NOWAIT)
747                 mflags = M_NOWAIT;
748         else
749                 mflags = M_WAITOK;
750         if (flags & BUS_DMA_ZERO)
751                 mflags |= M_ZERO;
752
753         *mapp = map = allocate_map(dmat, mflags);
754         if (map == NULL) {
755                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
756                     __func__, dmat, dmat->flags, ENOMEM);
757                 return (ENOMEM);
758         }
759         map->flags = DMAMAP_DMAMEM_ALLOC;
760
761         /* For coherent memory, set the map flag that disables sync ops. */
762         if (flags & BUS_DMA_COHERENT)
763                 map->flags |= DMAMAP_COHERENT;
764
765         /*
766          * Choose a busdma buffer allocator based on memory type flags.
767          * If the tag's COHERENT flag is set, that means normal memory
768          * is already coherent, use the normal allocator.
769          */
770         if ((flags & BUS_DMA_COHERENT) &&
771             ((dmat->flags & BUS_DMA_COHERENT) == 0)) {
772                 memattr = VM_MEMATTR_UNCACHEABLE;
773                 ba = coherent_allocator;
774         } else {
775                 memattr = VM_MEMATTR_DEFAULT;
776                 ba = standard_allocator;
777         }
778
779         /*
780          * Try to find a bufzone in the allocator that holds a cache of buffers
781          * of the right size for this request.  If the buffer is too big to be
782          * held in the allocator cache, this returns NULL.
783          */
784         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
785
786         /*
787          * Allocate the buffer from the uma(9) allocator if...
788          *  - It's small enough to be in the allocator (bufzone not NULL).
789          *  - The alignment constraint isn't larger than the allocation size
790          *    (the allocator aligns buffers to their size boundaries).
791          *  - There's no need to handle lowaddr/highaddr exclusion zones.
792          * else allocate non-contiguous pages if...
793          *  - The page count that could get allocated doesn't exceed
794          *    nsegments also when the maximum segment size is less
795          *    than PAGE_SIZE.
796          *  - The alignment constraint isn't larger than a page boundary.
797          *  - There are no boundary-crossing constraints.
798          * else allocate a block of contiguous pages because one or more of the
799          * constraints is something that only the contig allocator can fulfill.
800          */
801         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
802             !exclusion_bounce(dmat)) {
803                 *vaddr = uma_zalloc(bufzone->umazone, mflags);
804         } else if (dmat->nsegments >=
805             howmany(dmat->maxsize, MIN(dmat->maxsegsz, PAGE_SIZE)) &&
806             dmat->alignment <= PAGE_SIZE &&
807             (dmat->boundary % PAGE_SIZE) == 0) {
808                 *vaddr = (void *)kmem_alloc_attr(kernel_arena, dmat->maxsize,
809                     mflags, 0, dmat->lowaddr, memattr);
810         } else {
811                 *vaddr = (void *)kmem_alloc_contig(kernel_arena, dmat->maxsize,
812                     mflags, 0, dmat->lowaddr, dmat->alignment, dmat->boundary,
813                     memattr);
814         }
815         if (*vaddr == NULL) {
816                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
817                     __func__, dmat, dmat->flags, ENOMEM);
818                 free(map, M_BUSDMA);
819                 *mapp = NULL;
820                 return (ENOMEM);
821         }
822         if (map->flags & DMAMAP_COHERENT)
823                 atomic_add_32(&maps_coherent, 1);
824         atomic_add_32(&maps_dmamem, 1);
825         atomic_add_32(&maps_total, 1);
826         dmat->map_count++;
827
828         CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x error %d",
829             __func__, dmat, dmat->flags, 0);
830         return (0);
831 }
832
833 /*
834  * Free a piece of memory that was allocated via bus_dmamem_alloc, along with
835  * its associated map.
836  */
837 void
838 bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
839 {
840         struct busdma_bufzone *bufzone;
841         busdma_bufalloc_t ba;
842
843         if ((map->flags & DMAMAP_COHERENT) &&
844             ((dmat->flags & BUS_DMA_COHERENT) == 0))
845                 ba = coherent_allocator;
846         else
847                 ba = standard_allocator;
848
849         bufzone = busdma_bufalloc_findzone(ba, dmat->maxsize);
850
851         if (bufzone != NULL && dmat->alignment <= bufzone->size &&
852             !exclusion_bounce(dmat))
853                 uma_zfree(bufzone->umazone, vaddr);
854         else
855                 kmem_free(kernel_arena, (vm_offset_t)vaddr, dmat->maxsize);
856
857         dmat->map_count--;
858         if (map->flags & DMAMAP_COHERENT)
859                 atomic_subtract_32(&maps_coherent, 1);
860         atomic_subtract_32(&maps_total, 1);
861         atomic_subtract_32(&maps_dmamem, 1);
862         free(map, M_BUSDMA);
863         CTR3(KTR_BUSDMA, "%s: tag %p flags 0x%x", __func__, dmat, dmat->flags);
864 }
865
866 static void
867 _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
868     bus_size_t buflen, int flags)
869 {
870         bus_addr_t curaddr;
871         bus_size_t sgsize;
872
873         if (map->pagesneeded == 0) {
874                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
875                     " map= %p, pagesneeded= %d",
876                     dmat->lowaddr, dmat->boundary, dmat->alignment,
877                     map, map->pagesneeded);
878                 /*
879                  * Count the number of bounce pages
880                  * needed in order to complete this transfer
881                  */
882                 curaddr = buf;
883                 while (buflen != 0) {
884                         sgsize = MIN(buflen, dmat->maxsegsz);
885                         if (must_bounce(dmat, map, curaddr, sgsize) != 0) {
886                                 sgsize = MIN(sgsize,
887                                     PAGE_SIZE - (curaddr & PAGE_MASK));
888                                 map->pagesneeded++;
889                         }
890                         curaddr += sgsize;
891                         buflen -= sgsize;
892                 }
893                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
894         }
895 }
896
897 static void
898 _bus_dmamap_count_pages(bus_dma_tag_t dmat, pmap_t pmap, bus_dmamap_t map,
899     void *buf, bus_size_t buflen, int flags)
900 {
901         vm_offset_t vaddr;
902         vm_offset_t vendaddr;
903         bus_addr_t paddr;
904
905         if (map->pagesneeded == 0) {
906                 CTR5(KTR_BUSDMA, "lowaddr= %d, boundary= %d, alignment= %d"
907                     " map= %p, pagesneeded= %d",
908                     dmat->lowaddr, dmat->boundary, dmat->alignment,
909                     map, map->pagesneeded);
910                 /*
911                  * Count the number of bounce pages
912                  * needed in order to complete this transfer
913                  */
914                 vaddr = (vm_offset_t)buf;
915                 vendaddr = (vm_offset_t)buf + buflen;
916
917                 while (vaddr < vendaddr) {
918                         if (__predict_true(pmap == kernel_pmap))
919                                 paddr = pmap_kextract(vaddr);
920                         else
921                                 paddr = pmap_extract(pmap, vaddr);
922                         if (must_bounce(dmat, map, paddr,
923                             min(vendaddr - vaddr, (PAGE_SIZE - ((vm_offset_t)vaddr &
924                             PAGE_MASK)))) != 0) {
925                                 map->pagesneeded++;
926                         }
927                         vaddr += (PAGE_SIZE - ((vm_offset_t)vaddr & PAGE_MASK));
928
929                 }
930                 CTR1(KTR_BUSDMA, "pagesneeded= %d", map->pagesneeded);
931         }
932 }
933
934 static int
935 _bus_dmamap_reserve_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int flags)
936 {
937
938         /* Reserve Necessary Bounce Pages */
939         mtx_lock(&bounce_lock);
940         if (flags & BUS_DMA_NOWAIT) {
941                 if (reserve_bounce_pages(dmat, map, 0) != 0) {
942                         map->pagesneeded = 0;
943                         mtx_unlock(&bounce_lock);
944                         return (ENOMEM);
945                 }
946         } else {
947                 if (reserve_bounce_pages(dmat, map, 1) != 0) {
948                         /* Queue us for resources */
949                         STAILQ_INSERT_TAIL(&bounce_map_waitinglist, map, links);
950                         mtx_unlock(&bounce_lock);
951                         return (EINPROGRESS);
952                 }
953         }
954         mtx_unlock(&bounce_lock);
955
956         return (0);
957 }
958
959 /*
960  * Add a single contiguous physical range to the segment list.
961  */
962 static int
963 _bus_dmamap_addseg(bus_dma_tag_t dmat, bus_dmamap_t map, bus_addr_t curaddr,
964     bus_size_t sgsize, bus_dma_segment_t *segs, int *segp)
965 {
966         bus_addr_t baddr, bmask;
967         int seg;
968
969         /*
970          * Make sure we don't cross any boundaries.
971          */
972         bmask = ~(dmat->boundary - 1);
973         if (dmat->boundary > 0) {
974                 baddr = (curaddr + dmat->boundary) & bmask;
975                 if (sgsize > (baddr - curaddr))
976                         sgsize = (baddr - curaddr);
977         }
978
979         /*
980          * Insert chunk into a segment, coalescing with
981          * previous segment if possible.
982          */
983         seg = *segp;
984         if (seg == -1) {
985                 seg = 0;
986                 segs[seg].ds_addr = curaddr;
987                 segs[seg].ds_len = sgsize;
988         } else {
989                 if (curaddr == segs[seg].ds_addr + segs[seg].ds_len &&
990                     (segs[seg].ds_len + sgsize) <= dmat->maxsegsz &&
991                     (dmat->boundary == 0 ||
992                     (segs[seg].ds_addr & bmask) == (curaddr & bmask)))
993                         segs[seg].ds_len += sgsize;
994                 else {
995                         if (++seg >= dmat->nsegments)
996                                 return (0);
997                         segs[seg].ds_addr = curaddr;
998                         segs[seg].ds_len = sgsize;
999                 }
1000         }
1001         *segp = seg;
1002         return (sgsize);
1003 }
1004
1005 /*
1006  * Utility function to load a physical buffer.  segp contains
1007  * the starting segment on entrace, and the ending segment on exit.
1008  */
1009 int
1010 _bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf,
1011     bus_size_t buflen, int flags, bus_dma_segment_t *segs, int *segp)
1012 {
1013         bus_addr_t curaddr;
1014         bus_addr_t sl_end = 0;
1015         bus_size_t sgsize;
1016         struct sync_list *sl;
1017         int error;
1018
1019         if (segs == NULL)
1020                 segs = map->segments;
1021
1022         counter_u64_add(maploads_total, 1);
1023         counter_u64_add(maploads_physmem, 1);
1024
1025         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1026                 _bus_dmamap_count_phys(dmat, map, buf, buflen, flags);
1027                 if (map->pagesneeded != 0) {
1028                         counter_u64_add(maploads_bounced, 1);
1029                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1030                         if (error)
1031                                 return (error);
1032                 }
1033         }
1034
1035         sl = map->slist + map->sync_count - 1;
1036
1037         while (buflen > 0) {
1038                 curaddr = buf;
1039                 sgsize = MIN(buflen, dmat->maxsegsz);
1040                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1041                     sgsize)) {
1042                         sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK));
1043                         curaddr = add_bounce_page(dmat, map, 0, curaddr,
1044                             sgsize);
1045                 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1046                         if (map->sync_count > 0)
1047                                 sl_end = sl->paddr + sl->datacount;
1048
1049                         if (map->sync_count == 0 || curaddr != sl_end) {
1050                                 if (++map->sync_count > dmat->nsegments)
1051                                         break;
1052                                 sl++;
1053                                 sl->vaddr = 0;
1054                                 sl->paddr = curaddr;
1055                                 sl->datacount = sgsize;
1056                                 sl->pages = PHYS_TO_VM_PAGE(curaddr);
1057                                 KASSERT(sl->pages != NULL,
1058                                     ("%s: page at PA:0x%08lx is not in "
1059                                     "vm_page_array", __func__, curaddr));
1060                         } else
1061                                 sl->datacount += sgsize;
1062                 }
1063                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1064                     segp);
1065                 if (sgsize == 0)
1066                         break;
1067                 buf += sgsize;
1068                 buflen -= sgsize;
1069         }
1070
1071         /*
1072          * Did we fit?
1073          */
1074         if (buflen != 0) {
1075                 bus_dmamap_unload(dmat, map);
1076                 return (EFBIG); /* XXX better return value here? */
1077         }
1078         return (0);
1079 }
1080
1081 int
1082 _bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map,
1083     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
1084     bus_dma_segment_t *segs, int *segp)
1085 {
1086
1087         return (bus_dmamap_load_ma_triv(dmat, map, ma, tlen, ma_offs, flags,
1088             segs, segp));
1089 }
1090
1091 /*
1092  * Utility function to load a linear buffer.  segp contains
1093  * the starting segment on entrance, and the ending segment on exit.
1094  */
1095 int
1096 _bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
1097     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
1098     int *segp)
1099 {
1100         bus_size_t sgsize;
1101         bus_addr_t curaddr;
1102         bus_addr_t sl_pend = 0;
1103         vm_offset_t kvaddr, vaddr, sl_vend = 0;
1104         struct sync_list *sl;
1105         int error;
1106
1107         counter_u64_add(maploads_total, 1);
1108         if (map->flags & DMAMAP_COHERENT)
1109                 counter_u64_add(maploads_coherent, 1);
1110         if (map->flags & DMAMAP_DMAMEM_ALLOC)
1111                 counter_u64_add(maploads_dmamem, 1);
1112
1113         if (segs == NULL)
1114                 segs = map->segments;
1115
1116         if (flags & BUS_DMA_LOAD_MBUF) {
1117                 counter_u64_add(maploads_mbuf, 1);
1118                 map->flags |= DMAMAP_MBUF;
1119         }
1120
1121         if (might_bounce(dmat, map, (bus_addr_t)buf, buflen)) {
1122                 _bus_dmamap_count_pages(dmat, pmap, map, buf, buflen, flags);
1123                 if (map->pagesneeded != 0) {
1124                         counter_u64_add(maploads_bounced, 1);
1125                         error = _bus_dmamap_reserve_pages(dmat, map, flags);
1126                         if (error)
1127                                 return (error);
1128                 }
1129         }
1130
1131         sl = map->slist + map->sync_count - 1;
1132         vaddr = (vm_offset_t)buf;
1133
1134         while (buflen > 0) {
1135                 /*
1136                  * Get the physical address for this segment.
1137                  */
1138                 if (__predict_true(pmap == kernel_pmap)) {
1139                         curaddr = pmap_kextract(vaddr);
1140                         kvaddr = vaddr;
1141                 } else {
1142                         curaddr = pmap_extract(pmap, vaddr);
1143                         kvaddr = 0;
1144                 }
1145
1146                 /*
1147                  * Compute the segment size, and adjust counts.
1148                  */
1149                 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
1150                 if (sgsize > dmat->maxsegsz)
1151                         sgsize = dmat->maxsegsz;
1152                 if (buflen < sgsize)
1153                         sgsize = buflen;
1154
1155                 if (map->pagesneeded != 0 && must_bounce(dmat, map, curaddr,
1156                     sgsize)) {
1157                         curaddr = add_bounce_page(dmat, map, kvaddr, curaddr,
1158                             sgsize);
1159                 } else if ((dmat->flags & BUS_DMA_COHERENT) == 0) {
1160                         if (map->sync_count > 0) {
1161                                 sl_pend = sl->paddr + sl->datacount;
1162                                 sl_vend = sl->vaddr + sl->datacount;
1163                         }
1164
1165                         if (map->sync_count == 0 ||
1166                             (kvaddr != 0 && kvaddr != sl_vend) ||
1167                             (curaddr != sl_pend)) {
1168
1169                                 if (++map->sync_count > dmat->nsegments)
1170                                         goto cleanup;
1171                                 sl++;
1172                                 sl->vaddr = kvaddr;
1173                                 sl->paddr = curaddr;
1174                                 if (kvaddr != 0) {
1175                                         sl->pages = NULL;
1176                                 } else {
1177                                         sl->pages = PHYS_TO_VM_PAGE(curaddr);
1178                                         KASSERT(sl->pages != NULL,
1179                                             ("%s: page at PA:0x%08lx is not "
1180                                             "in vm_page_array", __func__,
1181                                             curaddr));
1182                                 }
1183                                 sl->datacount = sgsize;
1184                         } else
1185                                 sl->datacount += sgsize;
1186                 }
1187                 sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs,
1188                     segp);
1189                 if (sgsize == 0)
1190                         break;
1191                 vaddr += sgsize;
1192                 buflen -= sgsize;
1193         }
1194
1195 cleanup:
1196         /*
1197          * Did we fit?
1198          */
1199         if (buflen != 0) {
1200                 bus_dmamap_unload(dmat, map);
1201                 return (EFBIG); /* XXX better return value here? */
1202         }
1203         return (0);
1204 }
1205
1206 void
1207 _bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map, struct memdesc *mem,
1208     bus_dmamap_callback_t *callback, void *callback_arg)
1209 {
1210
1211         map->mem = *mem;
1212         map->dmat = dmat;
1213         map->callback = callback;
1214         map->callback_arg = callback_arg;
1215 }
1216
1217 bus_dma_segment_t *
1218 _bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map,
1219     bus_dma_segment_t *segs, int nsegs, int error)
1220 {
1221
1222         if (segs == NULL)
1223                 segs = map->segments;
1224         return (segs);
1225 }
1226
1227 /*
1228  * Release the mapping held by map.
1229  */
1230 void
1231 bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)
1232 {
1233         struct bounce_page *bpage;
1234         struct bounce_zone *bz;
1235
1236         if ((bz = dmat->bounce_zone) != NULL) {
1237                 while ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1238                         STAILQ_REMOVE_HEAD(&map->bpages, links);
1239                         free_bounce_page(dmat, bpage);
1240                 }
1241
1242                 bz = dmat->bounce_zone;
1243                 bz->free_bpages += map->pagesreserved;
1244                 bz->reserved_bpages -= map->pagesreserved;
1245                 map->pagesreserved = 0;
1246                 map->pagesneeded = 0;
1247         }
1248         map->sync_count = 0;
1249         map->flags &= ~DMAMAP_MBUF;
1250 }
1251
1252 static void
1253 dma_preread_safe(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
1254 {
1255         /*
1256          * Write back any partial cachelines immediately before and
1257          * after the DMA region.  We don't need to round the address
1258          * down to the nearest cacheline or specify the exact size,
1259          * as dcache_wb_poc() will do the rounding for us and works
1260          * at cacheline granularity.
1261          */
1262         if (va & BUSDMA_DCACHE_MASK)
1263                 dcache_wb_poc(va, pa, 1);
1264         if ((va + size) & BUSDMA_DCACHE_MASK)
1265                 dcache_wb_poc(va + size, pa + size, 1);
1266
1267         dcache_inv_poc_dma(va, pa, size);
1268 }
1269
1270 static void
1271 dma_dcache_sync(struct sync_list *sl, bus_dmasync_op_t op)
1272 {
1273         uint32_t len, offset;
1274         vm_page_t m;
1275         vm_paddr_t pa;
1276         vm_offset_t va, tempva;
1277         bus_size_t size;
1278
1279         offset = sl->paddr & PAGE_MASK;
1280         m = sl->pages;
1281         size = sl->datacount;
1282         pa = sl->paddr;
1283
1284         for ( ; size != 0; size -= len, pa += len, offset = 0, ++m) {
1285                 tempva = 0;
1286                 if (sl->vaddr == 0) {
1287                         len = min(PAGE_SIZE - offset, size);
1288                         tempva = pmap_quick_enter_page(m);
1289                         va = tempva | offset;
1290                         KASSERT(pa == (VM_PAGE_TO_PHYS(m) | offset),
1291                             ("unexpected vm_page_t phys: 0x%08x != 0x%08x",
1292                             VM_PAGE_TO_PHYS(m) | offset, pa));
1293                 } else {
1294                         len = sl->datacount;
1295                         va = sl->vaddr;
1296                 }
1297
1298                 switch (op) {
1299                 case BUS_DMASYNC_PREWRITE:
1300                 case BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD:
1301                         dcache_wb_poc(va, pa, len);
1302                         break;
1303                 case BUS_DMASYNC_PREREAD:
1304                         /*
1305                          * An mbuf may start in the middle of a cacheline. There
1306                          * will be no cpu writes to the beginning of that line
1307                          * (which contains the mbuf header) while dma is in
1308                          * progress.  Handle that case by doing a writeback of
1309                          * just the first cacheline before invalidating the
1310                          * overall buffer.  Any mbuf in a chain may have this
1311                          * misalignment.  Buffers which are not mbufs bounce if
1312                          * they are not aligned to a cacheline.
1313                          */
1314                         dma_preread_safe(va, pa, len);
1315                         break;
1316                 case BUS_DMASYNC_POSTREAD:
1317                 case BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE:
1318                         dcache_inv_poc(va, pa, len);
1319                         break;
1320                 default:
1321                         panic("unsupported combination of sync operations: "
1322                               "0x%08x\n", op);
1323                 }
1324
1325                 if (tempva != 0)
1326                         pmap_quick_remove_page(tempva);
1327         }
1328 }
1329
1330 void
1331 bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)
1332 {
1333         struct bounce_page *bpage;
1334         struct sync_list *sl, *end;
1335         vm_offset_t datavaddr, tempvaddr;
1336
1337         if (op == BUS_DMASYNC_POSTWRITE)
1338                 return;
1339
1340         /*
1341          * If the buffer was from user space, it is possible that this is not
1342          * the same vm map, especially on a POST operation.  It's not clear that
1343          * dma on userland buffers can work at all right now.  To be safe, until
1344          * we're able to test direct userland dma, panic on a map mismatch.
1345          */
1346         if ((bpage = STAILQ_FIRST(&map->bpages)) != NULL) {
1347
1348                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1349                     "performing bounce", __func__, dmat, dmat->flags, op);
1350
1351                 /*
1352                  * For PREWRITE do a writeback.  Clean the caches from the
1353                  * innermost to the outermost levels.
1354                  */
1355                 if (op & BUS_DMASYNC_PREWRITE) {
1356                         while (bpage != NULL) {
1357                                 tempvaddr = 0;
1358                                 datavaddr = bpage->datavaddr;
1359                                 if (datavaddr == 0) {
1360                                         tempvaddr = pmap_quick_enter_page(
1361                                             bpage->datapage);
1362                                         datavaddr = tempvaddr | bpage->dataoffs;
1363                                 }
1364                                 bcopy((void *)datavaddr, (void *)bpage->vaddr,
1365                                     bpage->datacount);
1366                                 if (tempvaddr != 0)
1367                                         pmap_quick_remove_page(tempvaddr);
1368                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1369                                         dcache_wb_poc(bpage->vaddr,
1370                                             bpage->busaddr, bpage->datacount);
1371                                 bpage = STAILQ_NEXT(bpage, links);
1372                         }
1373                         dmat->bounce_zone->total_bounced++;
1374                 }
1375
1376                 /*
1377                  * Do an invalidate for PREREAD unless a writeback was already
1378                  * done above due to PREWRITE also being set.  The reason for a
1379                  * PREREAD invalidate is to prevent dirty lines currently in the
1380                  * cache from being evicted during the DMA.  If a writeback was
1381                  * done due to PREWRITE also being set there will be no dirty
1382                  * lines and the POSTREAD invalidate handles the rest. The
1383                  * invalidate is done from the innermost to outermost level. If
1384                  * L2 were done first, a dirty cacheline could be automatically
1385                  * evicted from L1 before we invalidated it, re-dirtying the L2.
1386                  */
1387                 if ((op & BUS_DMASYNC_PREREAD) && !(op & BUS_DMASYNC_PREWRITE)) {
1388                         bpage = STAILQ_FIRST(&map->bpages);
1389                         while (bpage != NULL) {
1390                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1391                                         dcache_inv_poc_dma(bpage->vaddr,
1392                                             bpage->busaddr, bpage->datacount);
1393                                 bpage = STAILQ_NEXT(bpage, links);
1394                         }
1395                 }
1396
1397                 /*
1398                  * Re-invalidate the caches on a POSTREAD, even though they were
1399                  * already invalidated at PREREAD time.  Aggressive prefetching
1400                  * due to accesses to other data near the dma buffer could have
1401                  * brought buffer data into the caches which is now stale.  The
1402                  * caches are invalidated from the outermost to innermost; the
1403                  * prefetches could be happening right now, and if L1 were
1404                  * invalidated first, stale L2 data could be prefetched into L1.
1405                  */
1406                 if (op & BUS_DMASYNC_POSTREAD) {
1407                         while (bpage != NULL) {
1408                                 if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1409                                         dcache_inv_poc(bpage->vaddr,
1410                                             bpage->busaddr, bpage->datacount);
1411                                 tempvaddr = 0;
1412                                 datavaddr = bpage->datavaddr;
1413                                 if (datavaddr == 0) {
1414                                         tempvaddr = pmap_quick_enter_page(
1415                                             bpage->datapage);
1416                                         datavaddr = tempvaddr | bpage->dataoffs;
1417                                 }
1418                                 bcopy((void *)bpage->vaddr, (void *)datavaddr,
1419                                     bpage->datacount);
1420                                 if (tempvaddr != 0)
1421                                         pmap_quick_remove_page(tempvaddr);
1422                                 bpage = STAILQ_NEXT(bpage, links);
1423                         }
1424                         dmat->bounce_zone->total_bounced++;
1425                 }
1426         }
1427
1428         /*
1429          * For COHERENT memory no cache maintenance is necessary, but ensure all
1430          * writes have reached memory for the PREWRITE case.  No action is
1431          * needed for a PREREAD without PREWRITE also set, because that would
1432          * imply that the cpu had written to the COHERENT buffer and expected
1433          * the dma device to see that change, and by definition a PREWRITE sync
1434          * is required to make that happen.
1435          */
1436         if (map->flags & DMAMAP_COHERENT) {
1437                 if (op & BUS_DMASYNC_PREWRITE) {
1438                         dsb();
1439                         if ((dmat->flags & BUS_DMA_COHERENT) == 0)
1440                                 cpu_l2cache_drain_writebuf();
1441                 }
1442                 return;
1443         }
1444
1445         /*
1446          * Cache maintenance for normal (non-COHERENT non-bounce) buffers.  All
1447          * the comments about the sequences for flushing cache levels in the
1448          * bounce buffer code above apply here as well.  In particular, the fact
1449          * that the sequence is inner-to-outer for PREREAD invalidation and
1450          * outer-to-inner for POSTREAD invalidation is not a mistake.
1451          */
1452         if (map->sync_count != 0) {
1453                 sl = &map->slist[0];
1454                 end = &map->slist[map->sync_count];
1455                 CTR4(KTR_BUSDMA, "%s: tag %p tag flags 0x%x op 0x%x "
1456                     "performing sync", __func__, dmat, dmat->flags, op);
1457
1458                 for ( ; sl != end; ++sl)
1459                         dma_dcache_sync(sl, op);
1460         }
1461 }
1462
1463 static void
1464 init_bounce_pages(void *dummy __unused)
1465 {
1466
1467         total_bpages = 0;
1468         STAILQ_INIT(&bounce_zone_list);
1469         STAILQ_INIT(&bounce_map_waitinglist);
1470         STAILQ_INIT(&bounce_map_callbacklist);
1471         mtx_init(&bounce_lock, "bounce pages lock", NULL, MTX_DEF);
1472 }
1473 SYSINIT(bpages, SI_SUB_LOCK, SI_ORDER_ANY, init_bounce_pages, NULL);
1474
1475 static struct sysctl_ctx_list *
1476 busdma_sysctl_tree(struct bounce_zone *bz)
1477 {
1478
1479         return (&bz->sysctl_tree);
1480 }
1481
1482 static struct sysctl_oid *
1483 busdma_sysctl_tree_top(struct bounce_zone *bz)
1484 {
1485
1486         return (bz->sysctl_tree_top);
1487 }
1488
1489 static int
1490 alloc_bounce_zone(bus_dma_tag_t dmat)
1491 {
1492         struct bounce_zone *bz;
1493
1494         /* Check to see if we already have a suitable zone */
1495         STAILQ_FOREACH(bz, &bounce_zone_list, links) {
1496                 if ((dmat->alignment <= bz->alignment) &&
1497                     (dmat->lowaddr >= bz->lowaddr)) {
1498                         dmat->bounce_zone = bz;
1499                         return (0);
1500                 }
1501         }
1502
1503         if ((bz = (struct bounce_zone *)malloc(sizeof(*bz), M_BUSDMA,
1504             M_NOWAIT | M_ZERO)) == NULL)
1505                 return (ENOMEM);
1506
1507         STAILQ_INIT(&bz->bounce_page_list);
1508         bz->free_bpages = 0;
1509         bz->reserved_bpages = 0;
1510         bz->active_bpages = 0;
1511         bz->lowaddr = dmat->lowaddr;
1512         bz->alignment = MAX(dmat->alignment, PAGE_SIZE);
1513         bz->map_count = 0;
1514         snprintf(bz->zoneid, 8, "zone%d", busdma_zonecount);
1515         busdma_zonecount++;
1516         snprintf(bz->lowaddrid, 18, "%#jx", (uintmax_t)bz->lowaddr);
1517         STAILQ_INSERT_TAIL(&bounce_zone_list, bz, links);
1518         dmat->bounce_zone = bz;
1519
1520         sysctl_ctx_init(&bz->sysctl_tree);
1521         bz->sysctl_tree_top = SYSCTL_ADD_NODE(&bz->sysctl_tree,
1522             SYSCTL_STATIC_CHILDREN(_hw_busdma), OID_AUTO, bz->zoneid,
1523             CTLFLAG_RD, 0, "");
1524         if (bz->sysctl_tree_top == NULL) {
1525                 sysctl_ctx_free(&bz->sysctl_tree);
1526                 return (0);     /* XXX error code? */
1527         }
1528
1529         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1530             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1531             "total_bpages", CTLFLAG_RD, &bz->total_bpages, 0,
1532             "Total bounce pages");
1533         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1534             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1535             "free_bpages", CTLFLAG_RD, &bz->free_bpages, 0,
1536             "Free bounce pages");
1537         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1538             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1539             "reserved_bpages", CTLFLAG_RD, &bz->reserved_bpages, 0,
1540             "Reserved bounce pages");
1541         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1542             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1543             "active_bpages", CTLFLAG_RD, &bz->active_bpages, 0,
1544             "Active bounce pages");
1545         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1546             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1547             "total_bounced", CTLFLAG_RD, &bz->total_bounced, 0,
1548             "Total bounce requests (pages bounced)");
1549         SYSCTL_ADD_INT(busdma_sysctl_tree(bz),
1550             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1551             "total_deferred", CTLFLAG_RD, &bz->total_deferred, 0,
1552             "Total bounce requests that were deferred");
1553         SYSCTL_ADD_STRING(busdma_sysctl_tree(bz),
1554             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1555             "lowaddr", CTLFLAG_RD, bz->lowaddrid, 0, "");
1556         SYSCTL_ADD_ULONG(busdma_sysctl_tree(bz),
1557             SYSCTL_CHILDREN(busdma_sysctl_tree_top(bz)), OID_AUTO,
1558             "alignment", CTLFLAG_RD, &bz->alignment, "");
1559
1560         return (0);
1561 }
1562
1563 static int
1564 alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
1565 {
1566         struct bounce_zone *bz;
1567         int count;
1568
1569         bz = dmat->bounce_zone;
1570         count = 0;
1571         while (numpages > 0) {
1572                 struct bounce_page *bpage;
1573
1574                 bpage = (struct bounce_page *)malloc(sizeof(*bpage), M_BUSDMA,
1575                     M_NOWAIT | M_ZERO);
1576
1577                 if (bpage == NULL)
1578                         break;
1579                 bpage->vaddr = (vm_offset_t)contigmalloc(PAGE_SIZE, M_BOUNCE,
1580                     M_NOWAIT, 0ul, bz->lowaddr, PAGE_SIZE, 0);
1581                 if (bpage->vaddr == 0) {
1582                         free(bpage, M_BUSDMA);
1583                         break;
1584                 }
1585                 bpage->busaddr = pmap_kextract(bpage->vaddr);
1586                 mtx_lock(&bounce_lock);
1587                 STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
1588                 total_bpages++;
1589                 bz->total_bpages++;
1590                 bz->free_bpages++;
1591                 mtx_unlock(&bounce_lock);
1592                 count++;
1593                 numpages--;
1594         }
1595         return (count);
1596 }
1597
1598 static int
1599 reserve_bounce_pages(bus_dma_tag_t dmat, bus_dmamap_t map, int commit)
1600 {
1601         struct bounce_zone *bz;
1602         int pages;
1603
1604         mtx_assert(&bounce_lock, MA_OWNED);
1605         bz = dmat->bounce_zone;
1606         pages = MIN(bz->free_bpages, map->pagesneeded - map->pagesreserved);
1607         if (commit == 0 && map->pagesneeded > (map->pagesreserved + pages))
1608                 return (map->pagesneeded - (map->pagesreserved + pages));
1609         bz->free_bpages -= pages;
1610         bz->reserved_bpages += pages;
1611         map->pagesreserved += pages;
1612         pages = map->pagesneeded - map->pagesreserved;
1613
1614         return (pages);
1615 }
1616
1617 static bus_addr_t
1618 add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr,
1619     bus_addr_t addr, bus_size_t size)
1620 {
1621         struct bounce_zone *bz;
1622         struct bounce_page *bpage;
1623
1624         KASSERT(dmat->bounce_zone != NULL, ("no bounce zone in dma tag"));
1625         KASSERT(map != NULL, ("add_bounce_page: bad map %p", map));
1626
1627         bz = dmat->bounce_zone;
1628         if (map->pagesneeded == 0)
1629                 panic("add_bounce_page: map doesn't need any pages");
1630         map->pagesneeded--;
1631
1632         if (map->pagesreserved == 0)
1633                 panic("add_bounce_page: map doesn't need any pages");
1634         map->pagesreserved--;
1635
1636         mtx_lock(&bounce_lock);
1637         bpage = STAILQ_FIRST(&bz->bounce_page_list);
1638         if (bpage == NULL)
1639                 panic("add_bounce_page: free page list is empty");
1640
1641         STAILQ_REMOVE_HEAD(&bz->bounce_page_list, links);
1642         bz->reserved_bpages--;
1643         bz->active_bpages++;
1644         mtx_unlock(&bounce_lock);
1645
1646         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1647                 /* Page offset needs to be preserved. */
1648                 bpage->vaddr |= addr & PAGE_MASK;
1649                 bpage->busaddr |= addr & PAGE_MASK;
1650         }
1651         bpage->datavaddr = vaddr;
1652         bpage->datapage = PHYS_TO_VM_PAGE(addr);
1653         bpage->dataoffs = addr & PAGE_MASK;
1654         bpage->datacount = size;
1655         STAILQ_INSERT_TAIL(&(map->bpages), bpage, links);
1656         return (bpage->busaddr);
1657 }
1658
1659 static void
1660 free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage)
1661 {
1662         struct bus_dmamap *map;
1663         struct bounce_zone *bz;
1664
1665         bz = dmat->bounce_zone;
1666         bpage->datavaddr = 0;
1667         bpage->datacount = 0;
1668         if (dmat->flags & BUS_DMA_KEEP_PG_OFFSET) {
1669                 /*
1670                  * Reset the bounce page to start at offset 0.  Other uses
1671                  * of this bounce page may need to store a full page of
1672                  * data and/or assume it starts on a page boundary.
1673                  */
1674                 bpage->vaddr &= ~PAGE_MASK;
1675                 bpage->busaddr &= ~PAGE_MASK;
1676         }
1677
1678         mtx_lock(&bounce_lock);
1679         STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links);
1680         bz->free_bpages++;
1681         bz->active_bpages--;
1682         if ((map = STAILQ_FIRST(&bounce_map_waitinglist)) != NULL) {
1683                 if (reserve_bounce_pages(map->dmat, map, 1) == 0) {
1684                         STAILQ_REMOVE_HEAD(&bounce_map_waitinglist, links);
1685                         STAILQ_INSERT_TAIL(&bounce_map_callbacklist,
1686                             map, links);
1687                         busdma_swi_pending = 1;
1688                         bz->total_deferred++;
1689                         swi_sched(vm_ih, 0);
1690                 }
1691         }
1692         mtx_unlock(&bounce_lock);
1693 }
1694
1695 void
1696 busdma_swi(void)
1697 {
1698         bus_dma_tag_t dmat;
1699         struct bus_dmamap *map;
1700
1701         mtx_lock(&bounce_lock);
1702         while ((map = STAILQ_FIRST(&bounce_map_callbacklist)) != NULL) {
1703                 STAILQ_REMOVE_HEAD(&bounce_map_callbacklist, links);
1704                 mtx_unlock(&bounce_lock);
1705                 dmat = map->dmat;
1706                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_LOCK);
1707                 bus_dmamap_load_mem(map->dmat, map, &map->mem, map->callback,
1708                     map->callback_arg, BUS_DMA_WAITOK);
1709                 dmat->lockfunc(dmat->lockfuncarg, BUS_DMA_UNLOCK);
1710                 mtx_lock(&bounce_lock);
1711         }
1712         mtx_unlock(&bounce_lock);
1713 }