Home | History | Annotate | Line # | Download | only in arm32
bus_dma.c revision 1.89.2.2
      1 /*	$NetBSD: bus_dma.c,v 1.89.2.2 2015/09/22 12:05:37 skrll Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996, 1997, 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     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  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 #define _ARM32_BUS_DMA_PRIVATE
     34 
     35 #include "opt_arm_bus_space.h"
     36 
     37 #include <sys/cdefs.h>
     38 __KERNEL_RCSID(0, "$NetBSD: bus_dma.c,v 1.89.2.2 2015/09/22 12:05:37 skrll Exp $");
     39 
     40 #include <sys/param.h>
     41 #include <sys/systm.h>
     42 #include <sys/kernel.h>
     43 #include <sys/proc.h>
     44 #include <sys/buf.h>
     45 #include <sys/bus.h>
     46 #include <sys/cpu.h>
     47 #include <sys/reboot.h>
     48 #include <sys/conf.h>
     49 #include <sys/file.h>
     50 #include <sys/kmem.h>
     51 #include <sys/mbuf.h>
     52 #include <sys/vnode.h>
     53 #include <sys/device.h>
     54 
     55 #include <uvm/uvm.h>
     56 
     57 #include <arm/cpufunc.h>
     58 
     59 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
     60 #include <dev/mm.h>
     61 #endif
     62 
     63 #ifdef BUSDMA_COUNTERS
     64 static struct evcnt bus_dma_creates =
     65 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "creates");
     66 static struct evcnt bus_dma_bounced_creates =
     67 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "bounced creates");
     68 static struct evcnt bus_dma_loads =
     69 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "loads");
     70 static struct evcnt bus_dma_bounced_loads =
     71 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "bounced loads");
     72 static struct evcnt bus_dma_coherent_loads =
     73 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "coherent loads");
     74 static struct evcnt bus_dma_read_bounces =
     75 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "read bounces");
     76 static struct evcnt bus_dma_write_bounces =
     77 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "write bounces");
     78 static struct evcnt bus_dma_bounced_unloads =
     79 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "bounced unloads");
     80 static struct evcnt bus_dma_unloads =
     81 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "unloads");
     82 static struct evcnt bus_dma_bounced_destroys =
     83 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "bounced destroys");
     84 static struct evcnt bus_dma_destroys =
     85 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "destroys");
     86 static struct evcnt bus_dma_sync_prereadwrite =
     87 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync prereadwrite");
     88 static struct evcnt bus_dma_sync_preread_begin =
     89 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync preread begin");
     90 static struct evcnt bus_dma_sync_preread =
     91 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync preread");
     92 static struct evcnt bus_dma_sync_preread_tail =
     93 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync preread tail");
     94 static struct evcnt bus_dma_sync_prewrite =
     95 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync prewrite");
     96 static struct evcnt bus_dma_sync_postread =
     97 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync postread");
     98 static struct evcnt bus_dma_sync_postreadwrite =
     99 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync postreadwrite");
    100 static struct evcnt bus_dma_sync_postwrite =
    101 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "busdma", "sync postwrite");
    102 
    103 EVCNT_ATTACH_STATIC(bus_dma_creates);
    104 EVCNT_ATTACH_STATIC(bus_dma_bounced_creates);
    105 EVCNT_ATTACH_STATIC(bus_dma_loads);
    106 EVCNT_ATTACH_STATIC(bus_dma_bounced_loads);
    107 EVCNT_ATTACH_STATIC(bus_dma_coherent_loads);
    108 EVCNT_ATTACH_STATIC(bus_dma_read_bounces);
    109 EVCNT_ATTACH_STATIC(bus_dma_write_bounces);
    110 EVCNT_ATTACH_STATIC(bus_dma_unloads);
    111 EVCNT_ATTACH_STATIC(bus_dma_bounced_unloads);
    112 EVCNT_ATTACH_STATIC(bus_dma_destroys);
    113 EVCNT_ATTACH_STATIC(bus_dma_bounced_destroys);
    114 EVCNT_ATTACH_STATIC(bus_dma_sync_prereadwrite);
    115 EVCNT_ATTACH_STATIC(bus_dma_sync_preread_begin);
    116 EVCNT_ATTACH_STATIC(bus_dma_sync_preread);
    117 EVCNT_ATTACH_STATIC(bus_dma_sync_preread_tail);
    118 EVCNT_ATTACH_STATIC(bus_dma_sync_prewrite);
    119 EVCNT_ATTACH_STATIC(bus_dma_sync_postread);
    120 EVCNT_ATTACH_STATIC(bus_dma_sync_postreadwrite);
    121 EVCNT_ATTACH_STATIC(bus_dma_sync_postwrite);
    122 
    123 #define	STAT_INCR(x)	(bus_dma_ ## x.ev_count++)
    124 #else
    125 #define	STAT_INCR(x)	/*(bus_dma_ ## x.ev_count++)*/
    126 #endif
    127 
    128 int	_bus_dmamap_load_buffer(bus_dma_tag_t, bus_dmamap_t, void *,
    129 	    bus_size_t, struct vmspace *, int);
    130 static struct arm32_dma_range *
    131 	_bus_dma_paddr_inrange(struct arm32_dma_range *, int, paddr_t);
    132 
    133 /*
    134  * Check to see if the specified page is in an allowed DMA range.
    135  */
    136 inline struct arm32_dma_range *
    137 _bus_dma_paddr_inrange(struct arm32_dma_range *ranges, int nranges,
    138     bus_addr_t curaddr)
    139 {
    140 	struct arm32_dma_range *dr;
    141 	int i;
    142 
    143 	for (i = 0, dr = ranges; i < nranges; i++, dr++) {
    144 		if (curaddr >= dr->dr_sysbase &&
    145 		    curaddr < (dr->dr_sysbase + dr->dr_len))
    146 			return (dr);
    147 	}
    148 
    149 	return (NULL);
    150 }
    151 
    152 /*
    153  * Check to see if the specified busaddr is in an allowed DMA range.
    154  */
    155 static inline paddr_t
    156 _bus_dma_busaddr_to_paddr(bus_dma_tag_t t, bus_addr_t curaddr)
    157 {
    158 	struct arm32_dma_range *dr;
    159 	u_int i;
    160 
    161 	if (t->_nranges == 0)
    162 		return curaddr;
    163 
    164 	for (i = 0, dr = t->_ranges; i < t->_nranges; i++, dr++) {
    165 		if (dr->dr_busbase <= curaddr
    166 		    && curaddr < dr->dr_busbase + dr->dr_len)
    167 			return curaddr - dr->dr_busbase + dr->dr_sysbase;
    168 	}
    169 	panic("%s: curaddr %#lx not in range", __func__, curaddr);
    170 }
    171 
    172 /*
    173  * Common function to load the specified physical address into the
    174  * DMA map, coalescing segments and boundary checking as necessary.
    175  */
    176 static int
    177 _bus_dmamap_load_paddr(bus_dma_tag_t t, bus_dmamap_t map,
    178     bus_addr_t paddr, bus_size_t size, bool coherent)
    179 {
    180 	bus_dma_segment_t * const segs = map->dm_segs;
    181 	int nseg = map->dm_nsegs;
    182 	bus_addr_t lastaddr;
    183 	bus_addr_t bmask = ~(map->_dm_boundary - 1);
    184 	bus_addr_t curaddr;
    185 	bus_size_t sgsize;
    186 	uint32_t _ds_flags = coherent ? _BUS_DMAMAP_COHERENT : 0;
    187 
    188 	if (nseg > 0)
    189 		lastaddr = segs[nseg-1].ds_addr + segs[nseg-1].ds_len;
    190 	else
    191 		lastaddr = 0xdead;
    192 
    193  again:
    194 	sgsize = size;
    195 
    196 	/* Make sure we're in an allowed DMA range. */
    197 	if (t->_ranges != NULL) {
    198 		/* XXX cache last result? */
    199 		const struct arm32_dma_range * const dr =
    200 		    _bus_dma_paddr_inrange(t->_ranges, t->_nranges, paddr);
    201 		if (dr == NULL)
    202 			return (EINVAL);
    203 
    204 		/*
    205 		 * If this region is coherent, mark the segment as coherent.
    206 		 */
    207 		_ds_flags |= dr->dr_flags & _BUS_DMAMAP_COHERENT;
    208 
    209 		/*
    210 		 * In a valid DMA range.  Translate the physical
    211 		 * memory address to an address in the DMA window.
    212 		 */
    213 		curaddr = (paddr - dr->dr_sysbase) + dr->dr_busbase;
    214 #if 0
    215 		printf("%p: %#lx: range %#lx/%#lx/%#lx/%#x: %#x <-- %#lx\n",
    216 		    t, paddr, dr->dr_sysbase, dr->dr_busbase,
    217 		    dr->dr_len, dr->dr_flags, _ds_flags, curaddr);
    218 #endif
    219 	} else
    220 		curaddr = paddr;
    221 
    222 	/*
    223 	 * Make sure we don't cross any boundaries.
    224 	 */
    225 	if (map->_dm_boundary > 0) {
    226 		bus_addr_t baddr;	/* next boundary address */
    227 
    228 		baddr = (curaddr + map->_dm_boundary) & bmask;
    229 		if (sgsize > (baddr - curaddr))
    230 			sgsize = (baddr - curaddr);
    231 	}
    232 
    233 	/*
    234 	 * Insert chunk into a segment, coalescing with the
    235 	 * previous segment if possible.
    236 	 */
    237 	if (nseg > 0 && curaddr == lastaddr &&
    238 	    segs[nseg-1].ds_len + sgsize <= map->dm_maxsegsz &&
    239 	    ((segs[nseg-1]._ds_flags ^ _ds_flags) & _BUS_DMAMAP_COHERENT) == 0 &&
    240 	    (map->_dm_boundary == 0 ||
    241 	     (segs[nseg-1].ds_addr & bmask) == (curaddr & bmask))) {
    242 	     	/* coalesce */
    243 		segs[nseg-1].ds_len += sgsize;
    244 	} else if (nseg >= map->_dm_segcnt) {
    245 		return (EFBIG);
    246 	} else {
    247 		/* new segment */
    248 		segs[nseg].ds_addr = curaddr;
    249 		segs[nseg].ds_len = sgsize;
    250 		segs[nseg]._ds_flags = _ds_flags;
    251 		nseg++;
    252 	}
    253 
    254 	lastaddr = curaddr + sgsize;
    255 
    256 	paddr += sgsize;
    257 	size -= sgsize;
    258 	if (size > 0)
    259 		goto again;
    260 
    261 	map->_dm_flags &= (_ds_flags & _BUS_DMAMAP_COHERENT);
    262 	map->dm_nsegs = nseg;
    263 	return (0);
    264 }
    265 
    266 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    267 static int _bus_dma_alloc_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map,
    268 	    bus_size_t size, int flags);
    269 static void _bus_dma_free_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map);
    270 static int _bus_dma_uiomove(void *buf, struct uio *uio, size_t n,
    271 	    int direction);
    272 
    273 static int
    274 _bus_dma_load_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map, void *buf,
    275 	size_t buflen, int buftype, int flags)
    276 {
    277 	struct arm32_bus_dma_cookie * const cookie = map->_dm_cookie;
    278 	struct vmspace * const vm = vmspace_kernel();
    279 	int error;
    280 
    281 	KASSERT(cookie != NULL);
    282 	KASSERT(cookie->id_flags & _BUS_DMA_MIGHT_NEED_BOUNCE);
    283 
    284 	/*
    285 	 * Allocate bounce pages, if necessary.
    286 	 */
    287 	if ((cookie->id_flags & _BUS_DMA_HAS_BOUNCE) == 0) {
    288 		error = _bus_dma_alloc_bouncebuf(t, map, buflen, flags);
    289 		if (error)
    290 			return (error);
    291 	}
    292 
    293 	/*
    294 	 * Cache a pointer to the caller's buffer and load the DMA map
    295 	 * with the bounce buffer.
    296 	 */
    297 	cookie->id_origbuf = buf;
    298 	cookie->id_origbuflen = buflen;
    299 	error = _bus_dmamap_load_buffer(t, map, cookie->id_bouncebuf,
    300 	    buflen, vm, flags);
    301 	if (error)
    302 		return (error);
    303 
    304 	STAT_INCR(bounced_loads);
    305 	map->dm_mapsize = buflen;
    306 	map->_dm_vmspace = vm;
    307 	map->_dm_buftype = buftype;
    308 
    309 	/* ...so _bus_dmamap_sync() knows we're bouncing */
    310 	map->_dm_flags |= _BUS_DMAMAP_IS_BOUNCING;
    311 	cookie->id_flags |= _BUS_DMA_IS_BOUNCING;
    312 	return 0;
    313 }
    314 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
    315 
    316 /*
    317  * Common function for DMA map creation.  May be called by bus-specific
    318  * DMA map creation functions.
    319  */
    320 int
    321 _bus_dmamap_create(bus_dma_tag_t t, bus_size_t size, int nsegments,
    322     bus_size_t maxsegsz, bus_size_t boundary, int flags, bus_dmamap_t *dmamp)
    323 {
    324 	struct arm32_bus_dmamap *map;
    325 	void *mapstore;
    326 
    327 #ifdef DEBUG_DMA
    328 	printf("dmamap_create: t=%p size=%lx nseg=%x msegsz=%lx boundary=%lx flags=%x\n",
    329 	    t, size, nsegments, maxsegsz, boundary, flags);
    330 #endif	/* DEBUG_DMA */
    331 
    332 	/*
    333 	 * Allocate and initialize the DMA map.  The end of the map
    334 	 * is a variable-sized array of segments, so we allocate enough
    335 	 * room for them in one shot.
    336 	 *
    337 	 * Note we don't preserve the WAITOK or NOWAIT flags.  Preservation
    338 	 * of ALLOCNOW notifies others that we've reserved these resources,
    339 	 * and they are not to be freed.
    340 	 *
    341 	 * The bus_dmamap_t includes one bus_dma_segment_t, hence
    342 	 * the (nsegments - 1).
    343 	 */
    344 	const size_t mapsize = sizeof(struct arm32_bus_dmamap) +
    345 	    (sizeof(bus_dma_segment_t) * (nsegments - 1));
    346 	const int zallocflags = (flags & BUS_DMA_NOWAIT) ? KM_NOSLEEP : KM_SLEEP;
    347 	if ((mapstore = kmem_intr_zalloc(mapsize, zallocflags)) == NULL)
    348 		return (ENOMEM);
    349 
    350 	map = (struct arm32_bus_dmamap *)mapstore;
    351 	map->_dm_size = size;
    352 	map->_dm_segcnt = nsegments;
    353 	map->_dm_maxmaxsegsz = maxsegsz;
    354 	map->_dm_boundary = boundary;
    355 	map->_dm_flags = flags & ~(BUS_DMA_WAITOK|BUS_DMA_NOWAIT);
    356 	map->_dm_origbuf = NULL;
    357 	map->_dm_buftype = _BUS_DMA_BUFTYPE_INVALID;
    358 	map->_dm_vmspace = vmspace_kernel();
    359 	map->_dm_cookie = NULL;
    360 	map->dm_maxsegsz = maxsegsz;
    361 	map->dm_mapsize = 0;		/* no valid mappings */
    362 	map->dm_nsegs = 0;
    363 
    364 	*dmamp = map;
    365 
    366 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    367 	struct arm32_bus_dma_cookie *cookie;
    368 	int cookieflags;
    369 	void *cookiestore;
    370 	int error;
    371 
    372 	cookieflags = 0;
    373 
    374 	if (t->_may_bounce != NULL) {
    375 		error = (*t->_may_bounce)(t, map, flags, &cookieflags);
    376 		if (error != 0)
    377 			goto out;
    378 	}
    379 
    380 	if (t->_ranges != NULL)
    381 		cookieflags |= _BUS_DMA_MIGHT_NEED_BOUNCE;
    382 
    383 	if ((cookieflags & _BUS_DMA_MIGHT_NEED_BOUNCE) == 0) {
    384 		STAT_INCR(creates);
    385 		return 0;
    386 	}
    387 
    388 	const size_t cookiesize = sizeof(struct arm32_bus_dma_cookie) +
    389 	    (sizeof(bus_dma_segment_t) * map->_dm_segcnt);
    390 
    391 	/*
    392 	 * Allocate our cookie.
    393 	 */
    394 	if ((cookiestore = kmem_intr_zalloc(cookiesize, zallocflags)) == NULL) {
    395 		error = ENOMEM;
    396 		goto out;
    397 	}
    398 	cookie = (struct arm32_bus_dma_cookie *)cookiestore;
    399 	cookie->id_flags = cookieflags;
    400 	map->_dm_cookie = cookie;
    401 	STAT_INCR(bounced_creates);
    402 
    403 	error = _bus_dma_alloc_bouncebuf(t, map, size, flags);
    404  out:
    405 	if (error)
    406 		_bus_dmamap_destroy(t, map);
    407 #else
    408 	STAT_INCR(creates);
    409 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
    410 
    411 #ifdef DEBUG_DMA
    412 	printf("dmamap_create:map=%p\n", map);
    413 #endif	/* DEBUG_DMA */
    414 	return (0);
    415 }
    416 
    417 /*
    418  * Common function for DMA map destruction.  May be called by bus-specific
    419  * DMA map destruction functions.
    420  */
    421 void
    422 _bus_dmamap_destroy(bus_dma_tag_t t, bus_dmamap_t map)
    423 {
    424 
    425 #ifdef DEBUG_DMA
    426 	printf("dmamap_destroy: t=%p map=%p\n", t, map);
    427 #endif	/* DEBUG_DMA */
    428 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    429 	struct arm32_bus_dma_cookie *cookie = map->_dm_cookie;
    430 
    431 	/*
    432 	 * Free any bounce pages this map might hold.
    433 	 */
    434 	if (cookie != NULL) {
    435 		const size_t cookiesize = sizeof(struct arm32_bus_dma_cookie) +
    436 		    (sizeof(bus_dma_segment_t) * map->_dm_segcnt);
    437 
    438 		if (cookie->id_flags & _BUS_DMA_IS_BOUNCING)
    439 			STAT_INCR(bounced_unloads);
    440 		map->dm_nsegs = 0;
    441 		if (cookie->id_flags & _BUS_DMA_HAS_BOUNCE)
    442 			_bus_dma_free_bouncebuf(t, map);
    443 		STAT_INCR(bounced_destroys);
    444 		kmem_intr_free(cookie, cookiesize);
    445 	} else
    446 #endif
    447 	STAT_INCR(destroys);
    448 
    449 	if (map->dm_nsegs > 0)
    450 		STAT_INCR(unloads);
    451 
    452 	const size_t mapsize = sizeof(struct arm32_bus_dmamap) +
    453 	    (sizeof(bus_dma_segment_t) * (map->_dm_segcnt - 1));
    454 	kmem_intr_free(map, mapsize);
    455 }
    456 
    457 /*
    458  * Common function for loading a DMA map with a linear buffer.  May
    459  * be called by bus-specific DMA map load functions.
    460  */
    461 int
    462 _bus_dmamap_load(bus_dma_tag_t t, bus_dmamap_t map, void *buf,
    463     bus_size_t buflen, struct proc *p, int flags)
    464 {
    465 	struct vmspace *vm;
    466 	int error;
    467 
    468 #ifdef DEBUG_DMA
    469 	printf("dmamap_load: t=%p map=%p buf=%p len=%lx p=%p f=%d\n",
    470 	    t, map, buf, buflen, p, flags);
    471 #endif	/* DEBUG_DMA */
    472 
    473 	if (map->dm_nsegs > 0) {
    474 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    475 		struct arm32_bus_dma_cookie *cookie = map->_dm_cookie;
    476 		if (cookie != NULL) {
    477 			if (cookie->id_flags & _BUS_DMA_IS_BOUNCING) {
    478 				STAT_INCR(bounced_unloads);
    479 				cookie->id_flags &= ~_BUS_DMA_IS_BOUNCING;
    480 				map->_dm_flags &= ~_BUS_DMAMAP_IS_BOUNCING;
    481 			}
    482 		} else
    483 #endif
    484 		STAT_INCR(unloads);
    485 	}
    486 
    487 	/*
    488 	 * Make sure that on error condition we return "no valid mappings".
    489 	 */
    490 	map->dm_mapsize = 0;
    491 	map->dm_nsegs = 0;
    492 	map->_dm_buftype = _BUS_DMA_BUFTYPE_INVALID;
    493 	KASSERTMSG(map->dm_maxsegsz <= map->_dm_maxmaxsegsz,
    494 	    "dm_maxsegsz %lu _dm_maxmaxsegsz %lu",
    495 	    map->dm_maxsegsz, map->_dm_maxmaxsegsz);
    496 
    497 	if (buflen > map->_dm_size)
    498 		return (EINVAL);
    499 
    500 	if (p != NULL) {
    501 		vm = p->p_vmspace;
    502 	} else {
    503 		vm = vmspace_kernel();
    504 	}
    505 
    506 	/* _bus_dmamap_load_buffer() clears this if we're not... */
    507 	map->_dm_flags |= _BUS_DMAMAP_COHERENT;
    508 
    509 	error = _bus_dmamap_load_buffer(t, map, buf, buflen, vm, flags);
    510 	if (error == 0) {
    511 		map->dm_mapsize = buflen;
    512 		map->_dm_vmspace = vm;
    513 		map->_dm_origbuf = buf;
    514 		map->_dm_buftype = _BUS_DMA_BUFTYPE_LINEAR;
    515 		if (map->_dm_flags & _BUS_DMAMAP_COHERENT) {
    516 			STAT_INCR(coherent_loads);
    517 		} else {
    518 			STAT_INCR(loads);
    519 		}
    520 		return 0;
    521 	}
    522 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    523 	struct arm32_bus_dma_cookie * const cookie = map->_dm_cookie;
    524 	if (cookie != NULL && (cookie->id_flags & _BUS_DMA_MIGHT_NEED_BOUNCE)) {
    525 		error = _bus_dma_load_bouncebuf(t, map, buf, buflen,
    526 		    _BUS_DMA_BUFTYPE_LINEAR, flags);
    527 	}
    528 #endif
    529 	return (error);
    530 }
    531 
    532 /*
    533  * Like _bus_dmamap_load(), but for mbufs.
    534  */
    535 int
    536 _bus_dmamap_load_mbuf(bus_dma_tag_t t, bus_dmamap_t map, struct mbuf *m0,
    537     int flags)
    538 {
    539 	int error;
    540 	struct mbuf *m;
    541 
    542 #ifdef DEBUG_DMA
    543 	printf("dmamap_load_mbuf: t=%p map=%p m0=%p f=%d\n",
    544 	    t, map, m0, flags);
    545 #endif	/* DEBUG_DMA */
    546 
    547 	if (map->dm_nsegs > 0) {
    548 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    549 		struct arm32_bus_dma_cookie *cookie = map->_dm_cookie;
    550 		if (cookie != NULL) {
    551 			if (cookie->id_flags & _BUS_DMA_IS_BOUNCING) {
    552 				STAT_INCR(bounced_unloads);
    553 				cookie->id_flags &= ~_BUS_DMA_IS_BOUNCING;
    554 				map->_dm_flags &= ~_BUS_DMAMAP_IS_BOUNCING;
    555 			}
    556 		} else
    557 #endif
    558 		STAT_INCR(unloads);
    559 	}
    560 
    561 	/*
    562 	 * Make sure that on error condition we return "no valid mappings."
    563 	 */
    564 	map->dm_mapsize = 0;
    565 	map->dm_nsegs = 0;
    566 	map->_dm_buftype = _BUS_DMA_BUFTYPE_INVALID;
    567 	KASSERTMSG(map->dm_maxsegsz <= map->_dm_maxmaxsegsz,
    568 	    "dm_maxsegsz %lu _dm_maxmaxsegsz %lu",
    569 	    map->dm_maxsegsz, map->_dm_maxmaxsegsz);
    570 
    571 	KASSERT(m0->m_flags & M_PKTHDR);
    572 
    573 	if (m0->m_pkthdr.len > map->_dm_size)
    574 		return (EINVAL);
    575 
    576 	/* _bus_dmamap_load_paddr() clears this if we're not... */
    577 	map->_dm_flags |= _BUS_DMAMAP_COHERENT;
    578 
    579 	error = 0;
    580 	for (m = m0; m != NULL && error == 0; m = m->m_next) {
    581 		int offset;
    582 		int remainbytes;
    583 		const struct vm_page * const *pgs;
    584 		paddr_t paddr;
    585 		int size;
    586 
    587 		if (m->m_len == 0)
    588 			continue;
    589 		/*
    590 		 * Don't allow reads in read-only mbufs.
    591 		 */
    592 		if (M_ROMAP(m) && (flags & BUS_DMA_READ)) {
    593 			error = EFAULT;
    594 			break;
    595 		}
    596 		switch (m->m_flags & (M_EXT|M_CLUSTER|M_EXT_PAGES)) {
    597 		case M_EXT|M_CLUSTER:
    598 			/* XXX KDASSERT */
    599 			KASSERT(m->m_ext.ext_paddr != M_PADDR_INVALID);
    600 			paddr = m->m_ext.ext_paddr +
    601 			    (m->m_data - m->m_ext.ext_buf);
    602 			size = m->m_len;
    603 			error = _bus_dmamap_load_paddr(t, map, paddr, size,
    604 			    false);
    605 			break;
    606 
    607 		case M_EXT|M_EXT_PAGES:
    608 			KASSERT(m->m_ext.ext_buf <= m->m_data);
    609 			KASSERT(m->m_data <=
    610 			    m->m_ext.ext_buf + m->m_ext.ext_size);
    611 
    612 			offset = (vaddr_t)m->m_data -
    613 			    trunc_page((vaddr_t)m->m_ext.ext_buf);
    614 			remainbytes = m->m_len;
    615 
    616 			/* skip uninteresting pages */
    617 			pgs = (const struct vm_page * const *)
    618 			    m->m_ext.ext_pgs + (offset >> PAGE_SHIFT);
    619 
    620 			offset &= PAGE_MASK;	/* offset in the first page */
    621 
    622 			/* load each page */
    623 			while (remainbytes > 0) {
    624 				const struct vm_page *pg;
    625 
    626 				size = MIN(remainbytes, PAGE_SIZE - offset);
    627 
    628 				pg = *pgs++;
    629 				KASSERT(pg);
    630 				paddr = VM_PAGE_TO_PHYS(pg) + offset;
    631 
    632 				error = _bus_dmamap_load_paddr(t, map,
    633 				    paddr, size, false);
    634 				if (error)
    635 					break;
    636 				offset = 0;
    637 				remainbytes -= size;
    638 			}
    639 			break;
    640 
    641 		case 0:
    642 			paddr = m->m_paddr + M_BUFOFFSET(m) +
    643 			    (m->m_data - M_BUFADDR(m));
    644 			size = m->m_len;
    645 			error = _bus_dmamap_load_paddr(t, map, paddr, size,
    646 			    false);
    647 			break;
    648 
    649 		default:
    650 			error = _bus_dmamap_load_buffer(t, map, m->m_data,
    651 			    m->m_len, vmspace_kernel(), flags);
    652 		}
    653 	}
    654 	if (error == 0) {
    655 		map->dm_mapsize = m0->m_pkthdr.len;
    656 		map->_dm_origbuf = m0;
    657 		map->_dm_buftype = _BUS_DMA_BUFTYPE_MBUF;
    658 		map->_dm_vmspace = vmspace_kernel();	/* always kernel */
    659 		if (map->_dm_flags & _BUS_DMAMAP_COHERENT) {
    660 			STAT_INCR(coherent_loads);
    661 		} else {
    662 			STAT_INCR(loads);
    663 		}
    664 		return 0;
    665 	}
    666 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    667 	struct arm32_bus_dma_cookie * const cookie = map->_dm_cookie;
    668 	if (cookie != NULL && (cookie->id_flags & _BUS_DMA_MIGHT_NEED_BOUNCE)) {
    669 		error = _bus_dma_load_bouncebuf(t, map, m0, m0->m_pkthdr.len,
    670 		    _BUS_DMA_BUFTYPE_MBUF, flags);
    671 	}
    672 #endif
    673 	return (error);
    674 }
    675 
    676 /*
    677  * Like _bus_dmamap_load(), but for uios.
    678  */
    679 int
    680 _bus_dmamap_load_uio(bus_dma_tag_t t, bus_dmamap_t map, struct uio *uio,
    681     int flags)
    682 {
    683 	int i, error;
    684 	bus_size_t minlen, resid;
    685 	struct iovec *iov;
    686 	void *addr;
    687 
    688 	/*
    689 	 * Make sure that on error condition we return "no valid mappings."
    690 	 */
    691 	map->dm_mapsize = 0;
    692 	map->dm_nsegs = 0;
    693 	KASSERTMSG(map->dm_maxsegsz <= map->_dm_maxmaxsegsz,
    694 	    "dm_maxsegsz %lu _dm_maxmaxsegsz %lu",
    695 	    map->dm_maxsegsz, map->_dm_maxmaxsegsz);
    696 
    697 	resid = uio->uio_resid;
    698 	iov = uio->uio_iov;
    699 
    700 	/* _bus_dmamap_load_buffer() clears this if we're not... */
    701 	map->_dm_flags |= _BUS_DMAMAP_COHERENT;
    702 
    703 	error = 0;
    704 	for (i = 0; i < uio->uio_iovcnt && resid != 0 && error == 0; i++) {
    705 		/*
    706 		 * Now at the first iovec to load.  Load each iovec
    707 		 * until we have exhausted the residual count.
    708 		 */
    709 		minlen = resid < iov[i].iov_len ? resid : iov[i].iov_len;
    710 		addr = (void *)iov[i].iov_base;
    711 
    712 		error = _bus_dmamap_load_buffer(t, map, addr, minlen,
    713 		    uio->uio_vmspace, flags);
    714 
    715 		resid -= minlen;
    716 	}
    717 	if (error == 0) {
    718 		map->dm_mapsize = uio->uio_resid;
    719 		map->_dm_origbuf = uio;
    720 		map->_dm_buftype = _BUS_DMA_BUFTYPE_UIO;
    721 		map->_dm_vmspace = uio->uio_vmspace;
    722 		if (map->_dm_flags & _BUS_DMAMAP_COHERENT) {
    723 			STAT_INCR(coherent_loads);
    724 		} else {
    725 			STAT_INCR(loads);
    726 		}
    727 	}
    728 	return (error);
    729 }
    730 
    731 /*
    732  * Like _bus_dmamap_load(), but for raw memory allocated with
    733  * bus_dmamem_alloc().
    734  */
    735 int
    736 _bus_dmamap_load_raw(bus_dma_tag_t t, bus_dmamap_t map,
    737     bus_dma_segment_t *segs, int nsegs, bus_size_t size, int flags)
    738 {
    739 
    740 	panic("_bus_dmamap_load_raw: not implemented");
    741 }
    742 
    743 /*
    744  * Common function for unloading a DMA map.  May be called by
    745  * bus-specific DMA map unload functions.
    746  */
    747 void
    748 _bus_dmamap_unload(bus_dma_tag_t t, bus_dmamap_t map)
    749 {
    750 
    751 #ifdef DEBUG_DMA
    752 	printf("dmamap_unload: t=%p map=%p\n", t, map);
    753 #endif	/* DEBUG_DMA */
    754 
    755 	/*
    756 	 * No resources to free; just mark the mappings as
    757 	 * invalid.
    758 	 */
    759 	map->dm_mapsize = 0;
    760 	map->dm_nsegs = 0;
    761 	map->_dm_origbuf = NULL;
    762 	map->_dm_buftype = _BUS_DMA_BUFTYPE_INVALID;
    763 	map->_dm_vmspace = NULL;
    764 }
    765 
    766 static void
    767 _bus_dmamap_sync_segment(vaddr_t va, paddr_t pa, vsize_t len, int ops, bool readonly_p)
    768 {
    769 	KASSERTMSG((va & PAGE_MASK) == (pa & PAGE_MASK),
    770 	    "va %#lx pa %#lx", va, pa);
    771 #if 0
    772 	printf("sync_segment: va=%#lx pa=%#lx len=%#lx ops=%#x ro=%d\n",
    773 	    va, pa, len, ops, readonly_p);
    774 #endif
    775 
    776 	switch (ops) {
    777 	case BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE:
    778 #ifdef ARM_MMU_EXTENDED
    779 		(void)readonly_p;
    780 #else
    781 		if (!readonly_p) {
    782 #endif
    783 			STAT_INCR(sync_prereadwrite);
    784 			cpu_dcache_wbinv_range(va, len);
    785 			cpu_sdcache_wbinv_range(va, pa, len);
    786 			break;
    787 #ifndef ARM_MMU_EXTENDED
    788 		}
    789 		/* FALLTHROUGH */
    790 #endif
    791 
    792 	case BUS_DMASYNC_PREREAD: {
    793 		const size_t line_size = arm_dcache_align;
    794 		const size_t line_mask = arm_dcache_align_mask;
    795 		vsize_t misalignment = va & line_mask;
    796 		if (misalignment) {
    797 			va -= misalignment;
    798 			pa -= misalignment;
    799 			len += misalignment;
    800 			STAT_INCR(sync_preread_begin);
    801 			cpu_dcache_wbinv_range(va, line_size);
    802 			cpu_sdcache_wbinv_range(va, pa, line_size);
    803 			if (len <= line_size)
    804 				break;
    805 			va += line_size;
    806 			pa += line_size;
    807 			len -= line_size;
    808 		}
    809 		misalignment = len & line_mask;
    810 		len -= misalignment;
    811 		if (len > 0) {
    812 			STAT_INCR(sync_preread);
    813 			cpu_dcache_inv_range(va, len);
    814 			cpu_sdcache_inv_range(va, pa, len);
    815 		}
    816 		if (misalignment) {
    817 			va += len;
    818 			pa += len;
    819 			STAT_INCR(sync_preread_tail);
    820 			cpu_dcache_wbinv_range(va, line_size);
    821 			cpu_sdcache_wbinv_range(va, pa, line_size);
    822 		}
    823 		break;
    824 	}
    825 
    826 	case BUS_DMASYNC_PREWRITE:
    827 		STAT_INCR(sync_prewrite);
    828 		cpu_dcache_wb_range(va, len);
    829 		cpu_sdcache_wb_range(va, pa, len);
    830 		break;
    831 
    832 #ifdef CPU_CORTEX
    833 	/*
    834 	 * Cortex CPUs can do speculative loads so we need to clean the cache
    835 	 * after a DMA read to deal with any speculatively loaded cache lines.
    836 	 * Since these can't be dirty, we can just invalidate them and don't
    837 	 * have to worry about having to write back their contents.
    838 	 */
    839 	case BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE:
    840 		STAT_INCR(sync_postreadwrite);
    841 		arm_dmb();
    842 		cpu_dcache_inv_range(va, len);
    843 		cpu_sdcache_inv_range(va, pa, len);
    844 		break;
    845 	case BUS_DMASYNC_POSTREAD:
    846 		STAT_INCR(sync_postread);
    847 		arm_dmb();
    848 		cpu_dcache_inv_range(va, len);
    849 		cpu_sdcache_inv_range(va, pa, len);
    850 		break;
    851 #endif
    852 	}
    853 }
    854 
    855 static inline void
    856 _bus_dmamap_sync_linear(bus_dma_tag_t t, bus_dmamap_t map, bus_addr_t offset,
    857     bus_size_t len, int ops)
    858 {
    859 	bus_dma_segment_t *ds = map->dm_segs;
    860 	vaddr_t va = (vaddr_t) map->_dm_origbuf;
    861 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
    862 	if (map->_dm_flags & _BUS_DMAMAP_IS_BOUNCING) {
    863 		struct arm32_bus_dma_cookie * const cookie = map->_dm_cookie;
    864 		va = (vaddr_t) cookie->id_bouncebuf;
    865 	}
    866 #endif
    867 
    868 	while (len > 0) {
    869 		while (offset >= ds->ds_len) {
    870 			offset -= ds->ds_len;
    871 			va += ds->ds_len;
    872 			ds++;
    873 		}
    874 
    875 		paddr_t pa = _bus_dma_busaddr_to_paddr(t, ds->ds_addr + offset);
    876 		size_t seglen = min(len, ds->ds_len - offset);
    877 
    878 		if ((ds->_ds_flags & _BUS_DMAMAP_COHERENT) == 0)
    879 			_bus_dmamap_sync_segment(va + offset, pa, seglen, ops,
    880 			    false);
    881 
    882 		offset += seglen;
    883 		len -= seglen;
    884 	}
    885 }
    886 
    887 static inline void
    888 _bus_dmamap_sync_mbuf(bus_dma_tag_t t, bus_dmamap_t map, bus_size_t offset,
    889     bus_size_t len, int ops)
    890 {
    891 	bus_dma_segment_t *ds = map->dm_segs;
    892 	struct mbuf *m = map->_dm_origbuf;
    893 	bus_size_t voff = offset;
    894 	bus_size_t ds_off = offset;
    895 
    896 	while (len > 0) {
    897 		/* Find the current dma segment */
    898 		while (ds_off >= ds->ds_len) {
    899 			ds_off -= ds->ds_len;
    900 			ds++;
    901 		}
    902 		/* Find the current mbuf. */
    903 		while (voff >= m->m_len) {
    904 			voff -= m->m_len;
    905 			m = m->m_next;
    906 		}
    907 
    908 		/*
    909 		 * Now at the first mbuf to sync; nail each one until
    910 		 * we have exhausted the length.
    911 		 */
    912 		vsize_t seglen = min(len, min(m->m_len - voff, ds->ds_len - ds_off));
    913 		vaddr_t va = mtod(m, vaddr_t) + voff;
    914 		paddr_t pa = _bus_dma_busaddr_to_paddr(t, ds->ds_addr + ds_off);
    915 
    916 		/*
    917 		 * We can save a lot of work here if we know the mapping
    918 		 * is read-only at the MMU and we aren't using the armv6+
    919 		 * MMU:
    920 		 *
    921 		 * If a mapping is read-only, no dirty cache blocks will
    922 		 * exist for it.  If a writable mapping was made read-only,
    923 		 * we know any dirty cache lines for the range will have
    924 		 * been cleaned for us already.  Therefore, if the upper
    925 		 * layer can tell us we have a read-only mapping, we can
    926 		 * skip all cache cleaning.
    927 		 *
    928 		 * NOTE: This only works if we know the pmap cleans pages
    929 		 * before making a read-write -> read-only transition.  If
    930 		 * this ever becomes non-true (e.g. Physically Indexed
    931 		 * cache), this will have to be revisited.
    932 		 */
    933 
    934 		if ((ds->_ds_flags & _BUS_DMAMAP_COHERENT) == 0) {
    935 			/*
    936 			 * If we are doing preread (DMAing into the mbuf),
    937 			 * this mbuf better not be readonly,
    938 			 */
    939 			KASSERT(!(ops & BUS_DMASYNC_PREREAD) || !M_ROMAP(m));
    940 			_bus_dmamap_sync_segment(va, pa, seglen, ops,
    941 			    M_ROMAP(m));
    942 		}
    943 		voff += seglen;
    944 		ds_off += seglen;
    945 		len -= seglen;
    946 	}
    947 }
    948 
    949 static inline void
    950 _bus_dmamap_sync_uio(bus_dma_tag_t t, bus_dmamap_t map, bus_addr_t offset,
    951     bus_size_t len, int ops)
    952 {
    953 	bus_dma_segment_t *ds = map->dm_segs;
    954 	struct uio *uio = map->_dm_origbuf;
    955 	struct iovec *iov = uio->uio_iov;
    956 	bus_size_t voff = offset;
    957 	bus_size_t ds_off = offset;
    958 
    959 	while (len > 0) {
    960 		/* Find the current dma segment */
    961 		while (ds_off >= ds->ds_len) {
    962 			ds_off -= ds->ds_len;
    963 			ds++;
    964 		}
    965 
    966 		/* Find the current iovec. */
    967 		while (voff >= iov->iov_len) {
    968 			voff -= iov->iov_len;
    969 			iov++;
    970 		}
    971 
    972 		/*
    973 		 * Now at the first iovec to sync; nail each one until
    974 		 * we have exhausted the length.
    975 		 */
    976 		vsize_t seglen = min(len, min(iov->iov_len - voff, ds->ds_len - ds_off));
    977 		vaddr_t va = (vaddr_t) iov->iov_base + voff;
    978 		paddr_t pa = _bus_dma_busaddr_to_paddr(t, ds->ds_addr + ds_off);
    979 
    980 		if ((ds->_ds_flags & _BUS_DMAMAP_COHERENT) == 0)
    981 			_bus_dmamap_sync_segment(va, pa, seglen, ops, false);
    982 
    983 		voff += seglen;
    984 		ds_off += seglen;
    985 		len -= seglen;
    986 	}
    987 }
    988 
    989 /*
    990  * Common function for DMA map synchronization.  May be called
    991  * by bus-specific DMA map synchronization functions.
    992  *
    993  * This version works for the Virtually Indexed Virtually Tagged
    994  * cache found on 32-bit ARM processors.
    995  *
    996  * XXX Should have separate versions for write-through vs.
    997  * XXX write-back caches.  We currently assume write-back
    998  * XXX here, which is not as efficient as it could be for
    999  * XXX the write-through case.
   1000  */
   1001 void
   1002 _bus_dmamap_sync(bus_dma_tag_t t, bus_dmamap_t map, bus_addr_t offset,
   1003     bus_size_t len, int ops)
   1004 {
   1005 #ifdef DEBUG_DMA
   1006 	printf("dmamap_sync: t=%p map=%p offset=%lx len=%lx ops=%x\n",
   1007 	    t, map, offset, len, ops);
   1008 #endif	/* DEBUG_DMA */
   1009 
   1010 	/*
   1011 	 * Mixing of PRE and POST operations is not allowed.
   1012 	 */
   1013 	if ((ops & (BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE)) != 0 &&
   1014 	    (ops & (BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE)) != 0)
   1015 		panic("_bus_dmamap_sync: mix PRE and POST");
   1016 
   1017 	KASSERTMSG(offset < map->dm_mapsize,
   1018 	    "offset %lu mapsize %lu",
   1019 	    offset, map->dm_mapsize);
   1020 	KASSERTMSG(len > 0 && offset + len <= map->dm_mapsize,
   1021 	    "len %lu offset %lu mapsize %lu",
   1022 	    len, offset, map->dm_mapsize);
   1023 
   1024 	/*
   1025 	 * For a virtually-indexed write-back cache, we need
   1026 	 * to do the following things:
   1027 	 *
   1028 	 *	PREREAD -- Invalidate the D-cache.  We do this
   1029 	 *	here in case a write-back is required by the back-end.
   1030 	 *
   1031 	 *	PREWRITE -- Write-back the D-cache.  Note that if
   1032 	 *	we are doing a PREREAD|PREWRITE, we can collapse
   1033 	 *	the whole thing into a single Wb-Inv.
   1034 	 *
   1035 	 *	POSTREAD -- Re-invalidate the D-cache in case speculative
   1036 	 *	memory accesses caused cachelines to become valid with now
   1037 	 *	invalid data.
   1038 	 *
   1039 	 *	POSTWRITE -- Nothing.
   1040 	 */
   1041 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1042 	const bool bouncing = (map->_dm_flags & _BUS_DMAMAP_IS_BOUNCING);
   1043 #else
   1044 	const bool bouncing = false;
   1045 #endif
   1046 
   1047 	const int pre_ops = ops & (BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
   1048 #ifdef CPU_CORTEX
   1049 	const int post_ops = ops & (BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
   1050 #else
   1051 	const int post_ops = 0;
   1052 #endif
   1053 	if (!bouncing && pre_ops == 0 && post_ops == BUS_DMASYNC_POSTWRITE) {
   1054 		STAT_INCR(sync_postwrite);
   1055 		return;
   1056 	}
   1057 	KASSERTMSG(bouncing || pre_ops != 0 || (post_ops & BUS_DMASYNC_POSTREAD),
   1058 	    "pre_ops %#x post_ops %#x", pre_ops, post_ops);
   1059 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1060 	if (bouncing && (ops & BUS_DMASYNC_PREWRITE)) {
   1061 		struct arm32_bus_dma_cookie * const cookie = map->_dm_cookie;
   1062 		STAT_INCR(write_bounces);
   1063 		char * const dataptr = (char *)cookie->id_bouncebuf + offset;
   1064 		/*
   1065 		 * Copy the caller's buffer to the bounce buffer.
   1066 		 */
   1067 		switch (map->_dm_buftype) {
   1068 		case _BUS_DMA_BUFTYPE_LINEAR:
   1069 			memcpy(dataptr, cookie->id_origlinearbuf + offset, len);
   1070 			break;
   1071 		case _BUS_DMA_BUFTYPE_MBUF:
   1072 			m_copydata(cookie->id_origmbuf, offset, len, dataptr);
   1073 			break;
   1074 		case _BUS_DMA_BUFTYPE_UIO:
   1075 			_bus_dma_uiomove(dataptr, cookie->id_origuio, len, UIO_WRITE);
   1076 			break;
   1077 #ifdef DIAGNOSTIC
   1078 		case _BUS_DMA_BUFTYPE_RAW:
   1079 			panic("_bus_dmamap_sync(pre): _BUS_DMA_BUFTYPE_RAW");
   1080 			break;
   1081 
   1082 		case _BUS_DMA_BUFTYPE_INVALID:
   1083 			panic("_bus_dmamap_sync(pre): _BUS_DMA_BUFTYPE_INVALID");
   1084 			break;
   1085 
   1086 		default:
   1087 			panic("_bus_dmamap_sync(pre): map %p: unknown buffer type %d\n",
   1088 			    map, map->_dm_buftype);
   1089 			break;
   1090 #endif /* DIAGNOSTIC */
   1091 		}
   1092 	}
   1093 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
   1094 
   1095 	/* Skip cache frobbing if mapping was COHERENT. */
   1096 	if (!bouncing && (map->_dm_flags & _BUS_DMAMAP_COHERENT)) {
   1097 		/* Drain the write buffer. */
   1098 		if (pre_ops & BUS_DMASYNC_PREWRITE)
   1099 			cpu_drain_writebuf();
   1100 		return;
   1101 	}
   1102 
   1103 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1104 	if (bouncing && ((map->_dm_flags & _BUS_DMAMAP_COHERENT) || pre_ops == 0)) {
   1105 		goto bounce_it;
   1106 	}
   1107 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
   1108 
   1109 #ifndef ARM_MMU_EXTENDED
   1110 	/*
   1111 	 * If the mapping belongs to a non-kernel vmspace, and the
   1112 	 * vmspace has not been active since the last time a full
   1113 	 * cache flush was performed, we don't need to do anything.
   1114 	 */
   1115 	if (__predict_false(!VMSPACE_IS_KERNEL_P(map->_dm_vmspace) &&
   1116 	    vm_map_pmap(&map->_dm_vmspace->vm_map)->pm_cstate.cs_cache_d == 0))
   1117 		return;
   1118 #endif
   1119 
   1120 	int buftype = map->_dm_buftype;
   1121 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1122 	if (bouncing) {
   1123 		buftype = _BUS_DMA_BUFTYPE_LINEAR;
   1124 	}
   1125 #endif
   1126 
   1127 	switch (buftype) {
   1128 	case _BUS_DMA_BUFTYPE_LINEAR:
   1129 		_bus_dmamap_sync_linear(t, map, offset, len, ops);
   1130 		break;
   1131 
   1132 	case _BUS_DMA_BUFTYPE_MBUF:
   1133 		_bus_dmamap_sync_mbuf(t, map, offset, len, ops);
   1134 		break;
   1135 
   1136 	case _BUS_DMA_BUFTYPE_UIO:
   1137 		_bus_dmamap_sync_uio(t, map, offset, len, ops);
   1138 		break;
   1139 
   1140 	case _BUS_DMA_BUFTYPE_RAW:
   1141 		panic("_bus_dmamap_sync: _BUS_DMA_BUFTYPE_RAW");
   1142 		break;
   1143 
   1144 	case _BUS_DMA_BUFTYPE_INVALID:
   1145 		panic("_bus_dmamap_sync: _BUS_DMA_BUFTYPE_INVALID");
   1146 		break;
   1147 
   1148 	default:
   1149 		panic("_bus_dmamap_sync: map %p: unknown buffer type %d\n",
   1150 		    map, map->_dm_buftype);
   1151 	}
   1152 
   1153 	/* Drain the write buffer. */
   1154 	cpu_drain_writebuf();
   1155 
   1156 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1157   bounce_it:
   1158 	if (!bouncing || (ops & BUS_DMASYNC_POSTREAD) == 0)
   1159 		return;
   1160 
   1161 	struct arm32_bus_dma_cookie * const cookie = map->_dm_cookie;
   1162 	char * const dataptr = (char *)cookie->id_bouncebuf + offset;
   1163 	STAT_INCR(read_bounces);
   1164 	/*
   1165 	 * Copy the bounce buffer to the caller's buffer.
   1166 	 */
   1167 	switch (map->_dm_buftype) {
   1168 	case _BUS_DMA_BUFTYPE_LINEAR:
   1169 		memcpy(cookie->id_origlinearbuf + offset, dataptr, len);
   1170 		break;
   1171 
   1172 	case _BUS_DMA_BUFTYPE_MBUF:
   1173 		m_copyback(cookie->id_origmbuf, offset, len, dataptr);
   1174 		break;
   1175 
   1176 	case _BUS_DMA_BUFTYPE_UIO:
   1177 		_bus_dma_uiomove(dataptr, cookie->id_origuio, len, UIO_READ);
   1178 		break;
   1179 #ifdef DIAGNOSTIC
   1180 	case _BUS_DMA_BUFTYPE_RAW:
   1181 		panic("_bus_dmamap_sync(post): _BUS_DMA_BUFTYPE_RAW");
   1182 		break;
   1183 
   1184 	case _BUS_DMA_BUFTYPE_INVALID:
   1185 		panic("_bus_dmamap_sync(post): _BUS_DMA_BUFTYPE_INVALID");
   1186 		break;
   1187 
   1188 	default:
   1189 		panic("_bus_dmamap_sync(post): map %p: unknown buffer type %d\n",
   1190 		    map, map->_dm_buftype);
   1191 		break;
   1192 #endif
   1193 	}
   1194 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
   1195 }
   1196 
   1197 /*
   1198  * Common function for DMA-safe memory allocation.  May be called
   1199  * by bus-specific DMA memory allocation functions.
   1200  */
   1201 
   1202 extern paddr_t physical_start;
   1203 extern paddr_t physical_end;
   1204 
   1205 int
   1206 _bus_dmamem_alloc(bus_dma_tag_t t, bus_size_t size, bus_size_t alignment,
   1207     bus_size_t boundary, bus_dma_segment_t *segs, int nsegs, int *rsegs,
   1208     int flags)
   1209 {
   1210 	struct arm32_dma_range *dr;
   1211 	int error, i;
   1212 
   1213 #ifdef DEBUG_DMA
   1214 	printf("dmamem_alloc t=%p size=%lx align=%lx boundary=%lx "
   1215 	    "segs=%p nsegs=%x rsegs=%p flags=%x\n", t, size, alignment,
   1216 	    boundary, segs, nsegs, rsegs, flags);
   1217 #endif
   1218 
   1219 	if ((dr = t->_ranges) != NULL) {
   1220 		error = ENOMEM;
   1221 		for (i = 0; i < t->_nranges; i++, dr++) {
   1222 			if (dr->dr_len == 0
   1223 			    || (dr->dr_flags & _BUS_DMAMAP_NOALLOC))
   1224 				continue;
   1225 			error = _bus_dmamem_alloc_range(t, size, alignment,
   1226 			    boundary, segs, nsegs, rsegs, flags,
   1227 			    trunc_page(dr->dr_sysbase),
   1228 			    trunc_page(dr->dr_sysbase + dr->dr_len));
   1229 			if (error == 0)
   1230 				break;
   1231 		}
   1232 	} else {
   1233 		error = _bus_dmamem_alloc_range(t, size, alignment, boundary,
   1234 		    segs, nsegs, rsegs, flags, trunc_page(physical_start),
   1235 		    trunc_page(physical_end));
   1236 	}
   1237 
   1238 #ifdef DEBUG_DMA
   1239 	printf("dmamem_alloc: =%d\n", error);
   1240 #endif
   1241 
   1242 	return(error);
   1243 }
   1244 
   1245 /*
   1246  * Common function for freeing DMA-safe memory.  May be called by
   1247  * bus-specific DMA memory free functions.
   1248  */
   1249 void
   1250 _bus_dmamem_free(bus_dma_tag_t t, bus_dma_segment_t *segs, int nsegs)
   1251 {
   1252 	struct vm_page *m;
   1253 	bus_addr_t addr;
   1254 	struct pglist mlist;
   1255 	int curseg;
   1256 
   1257 #ifdef DEBUG_DMA
   1258 	printf("dmamem_free: t=%p segs=%p nsegs=%x\n", t, segs, nsegs);
   1259 #endif	/* DEBUG_DMA */
   1260 
   1261 	/*
   1262 	 * Build a list of pages to free back to the VM system.
   1263 	 */
   1264 	TAILQ_INIT(&mlist);
   1265 	for (curseg = 0; curseg < nsegs; curseg++) {
   1266 		for (addr = segs[curseg].ds_addr;
   1267 		    addr < (segs[curseg].ds_addr + segs[curseg].ds_len);
   1268 		    addr += PAGE_SIZE) {
   1269 			m = PHYS_TO_VM_PAGE(addr);
   1270 			TAILQ_INSERT_TAIL(&mlist, m, pageq.queue);
   1271 		}
   1272 	}
   1273 	uvm_pglistfree(&mlist);
   1274 }
   1275 
   1276 /*
   1277  * Common function for mapping DMA-safe memory.  May be called by
   1278  * bus-specific DMA memory map functions.
   1279  */
   1280 int
   1281 _bus_dmamem_map(bus_dma_tag_t t, bus_dma_segment_t *segs, int nsegs,
   1282     size_t size, void **kvap, int flags)
   1283 {
   1284 	vaddr_t va;
   1285 	paddr_t pa;
   1286 	int curseg;
   1287 	const uvm_flag_t kmflags = UVM_KMF_VAONLY
   1288 	    | ((flags & BUS_DMA_NOWAIT) != 0 ? UVM_KMF_NOWAIT : 0);
   1289 	vsize_t align = 0;
   1290 
   1291 #ifdef DEBUG_DMA
   1292 	printf("dmamem_map: t=%p segs=%p nsegs=%x size=%lx flags=%x\n", t,
   1293 	    segs, nsegs, (unsigned long)size, flags);
   1294 #endif	/* DEBUG_DMA */
   1295 
   1296 #ifdef PMAP_MAP_POOLPAGE
   1297 	/*
   1298 	 * If all of memory is mapped, and we are mapping a single physically
   1299 	 * contiguous area then this area is already mapped.  Let's see if we
   1300 	 * avoid having a separate mapping for it.
   1301 	 */
   1302 	if (nsegs == 1) {
   1303 		/*
   1304 		 * If this is a non-COHERENT mapping, then the existing kernel
   1305 		 * mapping is already compatible with it.
   1306 		 */
   1307 		bool direct_mapable = (flags & BUS_DMA_COHERENT) == 0;
   1308 		pa = segs[0].ds_addr;
   1309 
   1310 		/*
   1311 		 * This is a COHERENT mapping which, unless this address is in
   1312 		 * a COHERENT dma range, will not be compatible.
   1313 		 */
   1314 		if (t->_ranges != NULL) {
   1315 			const struct arm32_dma_range * const dr =
   1316 			    _bus_dma_paddr_inrange(t->_ranges, t->_nranges, pa);
   1317 			if (dr != NULL
   1318 			    && (dr->dr_flags & _BUS_DMAMAP_COHERENT)) {
   1319 				direct_mapable = true;
   1320 			}
   1321 		}
   1322 
   1323 #ifdef PMAP_NEED_ALLOC_POOLPAGE
   1324 		/*
   1325 		 * The page can only be direct mapped if was allocated out
   1326 		 * of the arm poolpage vm freelist.
   1327 		 */
   1328 		int lcv = vm_physseg_find(atop(pa), NULL);
   1329 		KASSERT(lcv != -1);
   1330 		if (direct_mapable) {
   1331 			direct_mapable =
   1332 			    (arm_poolpage_vmfreelist == VM_PHYSMEM_PTR(lcv)->free_list);
   1333 		}
   1334 #endif
   1335 
   1336 		if (direct_mapable) {
   1337 			*kvap = (void *)PMAP_MAP_POOLPAGE(pa);
   1338 #ifdef DEBUG_DMA
   1339 			printf("dmamem_map: =%p\n", *kvap);
   1340 #endif	/* DEBUG_DMA */
   1341 			return 0;
   1342 		}
   1343 	}
   1344 #endif
   1345 
   1346 	size = round_page(size);
   1347 	if (__predict_true(size > L2_L_SIZE)) {
   1348 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
   1349 		if (size >= L1_SS_SIZE)
   1350 			align = L1_SS_SIZE;
   1351 		else
   1352 #endif
   1353 		if (size >= L1_S_SIZE)
   1354 			align = L1_S_SIZE;
   1355 		else
   1356 			align = L2_L_SIZE;
   1357 	}
   1358 
   1359 	va = uvm_km_alloc(kernel_map, size, align, kmflags);
   1360 	if (__predict_false(va == 0 && align > 0)) {
   1361 		align = 0;
   1362 		va = uvm_km_alloc(kernel_map, size, 0, kmflags);
   1363 	}
   1364 
   1365 	if (va == 0)
   1366 		return (ENOMEM);
   1367 
   1368 	*kvap = (void *)va;
   1369 
   1370 	for (curseg = 0; curseg < nsegs; curseg++) {
   1371 		for (pa = segs[curseg].ds_addr;
   1372 		    pa < (segs[curseg].ds_addr + segs[curseg].ds_len);
   1373 		    pa += PAGE_SIZE, va += PAGE_SIZE, size -= PAGE_SIZE) {
   1374 			bool uncached = (flags & BUS_DMA_COHERENT);
   1375 #ifdef DEBUG_DMA
   1376 			printf("wiring p%lx to v%lx", pa, va);
   1377 #endif	/* DEBUG_DMA */
   1378 			if (size == 0)
   1379 				panic("_bus_dmamem_map: size botch");
   1380 
   1381 			const struct arm32_dma_range * const dr =
   1382 			    _bus_dma_paddr_inrange(t->_ranges, t->_nranges, pa);
   1383 			/*
   1384 			 * If this dma region is coherent then there is
   1385 			 * no need for an uncached mapping.
   1386 			 */
   1387 			if (dr != NULL
   1388 			    && (dr->dr_flags & _BUS_DMAMAP_COHERENT)) {
   1389 				uncached = false;
   1390 			}
   1391 
   1392 			pmap_kenter_pa(va, pa, VM_PROT_READ | VM_PROT_WRITE,
   1393 			    PMAP_WIRED | (uncached ? PMAP_NOCACHE : 0));
   1394 		}
   1395 	}
   1396 	pmap_update(pmap_kernel());
   1397 #ifdef DEBUG_DMA
   1398 	printf("dmamem_map: =%p\n", *kvap);
   1399 #endif	/* DEBUG_DMA */
   1400 	return (0);
   1401 }
   1402 
   1403 /*
   1404  * Common function for unmapping DMA-safe memory.  May be called by
   1405  * bus-specific DMA memory unmapping functions.
   1406  */
   1407 void
   1408 _bus_dmamem_unmap(bus_dma_tag_t t, void *kva, size_t size)
   1409 {
   1410 
   1411 #ifdef DEBUG_DMA
   1412 	printf("dmamem_unmap: t=%p kva=%p size=%zx\n", t, kva, size);
   1413 #endif	/* DEBUG_DMA */
   1414 	KASSERTMSG(((uintptr_t)kva & PAGE_MASK) == 0,
   1415 	    "kva %p (%#"PRIxPTR")", kva, ((uintptr_t)kva & PAGE_MASK));
   1416 
   1417 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
   1418 	/*
   1419 	 * Check to see if this used direct mapped memory.  Get its physical
   1420 	 * address and try to map it.  If the resultant matches the kva, then
   1421 	 * it was and so we can just return since we have notice to free up.
   1422 	 */
   1423 	paddr_t pa;
   1424 	vaddr_t va;
   1425 	(void)pmap_extract(pmap_kernel(), (vaddr_t)kva, &pa);
   1426 	if (mm_md_direct_mapped_phys(pa, &va) && va == (vaddr_t)kva)
   1427 		return;
   1428 #endif
   1429 
   1430 	size = round_page(size);
   1431 	pmap_kremove((vaddr_t)kva, size);
   1432 	pmap_update(pmap_kernel());
   1433 	uvm_km_free(kernel_map, (vaddr_t)kva, size, UVM_KMF_VAONLY);
   1434 }
   1435 
   1436 /*
   1437  * Common functin for mmap(2)'ing DMA-safe memory.  May be called by
   1438  * bus-specific DMA mmap(2)'ing functions.
   1439  */
   1440 paddr_t
   1441 _bus_dmamem_mmap(bus_dma_tag_t t, bus_dma_segment_t *segs, int nsegs,
   1442     off_t off, int prot, int flags)
   1443 {
   1444 	paddr_t map_flags;
   1445 	int i;
   1446 
   1447 	for (i = 0; i < nsegs; i++) {
   1448 		KASSERTMSG((off & PAGE_MASK) == 0,
   1449 		    "off %#qx (%#x)", off, (int)off & PAGE_MASK);
   1450 		KASSERTMSG((segs[i].ds_addr & PAGE_MASK) == 0,
   1451 		    "ds_addr %#lx (%#x)", segs[i].ds_addr,
   1452 		    (int)segs[i].ds_addr & PAGE_MASK);
   1453 		KASSERTMSG((segs[i].ds_len & PAGE_MASK) == 0,
   1454 		    "ds_len %#lx (%#x)", segs[i].ds_addr,
   1455 		    (int)segs[i].ds_addr & PAGE_MASK);
   1456 		if (off >= segs[i].ds_len) {
   1457 			off -= segs[i].ds_len;
   1458 			continue;
   1459 		}
   1460 
   1461 		map_flags = 0;
   1462 		if (flags & BUS_DMA_PREFETCHABLE)
   1463 			map_flags |= ARM32_MMAP_WRITECOMBINE;
   1464 
   1465 		return (arm_btop((u_long)segs[i].ds_addr + off) | map_flags);
   1466 
   1467 	}
   1468 
   1469 	/* Page not found. */
   1470 	return (-1);
   1471 }
   1472 
   1473 /**********************************************************************
   1474  * DMA utility functions
   1475  **********************************************************************/
   1476 
   1477 /*
   1478  * Utility function to load a linear buffer.  lastaddrp holds state
   1479  * between invocations (for multiple-buffer loads).  segp contains
   1480  * the starting segment on entrace, and the ending segment on exit.
   1481  * first indicates if this is the first invocation of this function.
   1482  */
   1483 int
   1484 _bus_dmamap_load_buffer(bus_dma_tag_t t, bus_dmamap_t map, void *buf,
   1485     bus_size_t buflen, struct vmspace *vm, int flags)
   1486 {
   1487 	bus_size_t sgsize;
   1488 	bus_addr_t curaddr;
   1489 	vaddr_t vaddr = (vaddr_t)buf;
   1490 	int error;
   1491 	pmap_t pmap;
   1492 
   1493 #ifdef DEBUG_DMA
   1494 	printf("_bus_dmamem_load_buffer(buf=%p, len=%lx, flags=%d)\n",
   1495 	    buf, buflen, flags);
   1496 #endif	/* DEBUG_DMA */
   1497 
   1498 	pmap = vm_map_pmap(&vm->vm_map);
   1499 
   1500 	while (buflen > 0) {
   1501 		/*
   1502 		 * Get the physical address for this segment.
   1503 		 *
   1504 		 * XXX Doesn't support checking for coherent mappings
   1505 		 * XXX in user address space.
   1506 		 */
   1507 		bool coherent;
   1508 		if (__predict_true(pmap == pmap_kernel())) {
   1509 			pd_entry_t *pde;
   1510 			pt_entry_t *ptep;
   1511 			(void) pmap_get_pde_pte(pmap, vaddr, &pde, &ptep);
   1512 			if (__predict_false(pmap_pde_section(pde))) {
   1513 				paddr_t s_frame = L1_S_FRAME;
   1514 				paddr_t s_offset = L1_S_OFFSET;
   1515 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
   1516 				if (__predict_false(pmap_pde_supersection(pde))) {
   1517 					s_frame = L1_SS_FRAME;
   1518 					s_offset = L1_SS_OFFSET;
   1519 				}
   1520 #endif
   1521 				curaddr = (*pde & s_frame) | (vaddr & s_offset);
   1522 				coherent = (*pde & L1_S_CACHE_MASK) == 0;
   1523 			} else {
   1524 				pt_entry_t pte = *ptep;
   1525 				KDASSERTMSG((pte & L2_TYPE_MASK) != L2_TYPE_INV,
   1526 				    "va=%#"PRIxVADDR" pde=%#x ptep=%p pte=%#x",
   1527 				    vaddr, *pde, ptep, pte);
   1528 				if (__predict_false((pte & L2_TYPE_MASK)
   1529 						    == L2_TYPE_L)) {
   1530 					curaddr = (pte & L2_L_FRAME) |
   1531 					    (vaddr & L2_L_OFFSET);
   1532 					coherent = (pte & L2_L_CACHE_MASK) == 0;
   1533 				} else {
   1534 					curaddr = (pte & ~PAGE_MASK) |
   1535 					    (vaddr & PAGE_MASK);
   1536 					coherent = (pte & L2_S_CACHE_MASK) == 0;
   1537 				}
   1538 			}
   1539 		} else {
   1540 			(void) pmap_extract(pmap, vaddr, &curaddr);
   1541 			coherent = false;
   1542 		}
   1543 		KASSERTMSG((vaddr & PAGE_MASK) == (curaddr & PAGE_MASK),
   1544 		    "va %#lx curaddr %#lx", vaddr, curaddr);
   1545 
   1546 		/*
   1547 		 * Compute the segment size, and adjust counts.
   1548 		 */
   1549 		sgsize = PAGE_SIZE - ((u_long)vaddr & PGOFSET);
   1550 		if (buflen < sgsize)
   1551 			sgsize = buflen;
   1552 
   1553 		error = _bus_dmamap_load_paddr(t, map, curaddr, sgsize,
   1554 		    coherent);
   1555 		if (error)
   1556 			return (error);
   1557 
   1558 		vaddr += sgsize;
   1559 		buflen -= sgsize;
   1560 	}
   1561 
   1562 	return (0);
   1563 }
   1564 
   1565 /*
   1566  * Allocate physical memory from the given physical address range.
   1567  * Called by DMA-safe memory allocation methods.
   1568  */
   1569 int
   1570 _bus_dmamem_alloc_range(bus_dma_tag_t t, bus_size_t size, bus_size_t alignment,
   1571     bus_size_t boundary, bus_dma_segment_t *segs, int nsegs, int *rsegs,
   1572     int flags, paddr_t low, paddr_t high)
   1573 {
   1574 	paddr_t curaddr, lastaddr;
   1575 	struct vm_page *m;
   1576 	struct pglist mlist;
   1577 	int curseg, error;
   1578 
   1579 	KASSERTMSG(boundary == 0 || (boundary & (boundary-1)) == 0,
   1580 	    "invalid boundary %#lx", boundary);
   1581 
   1582 #ifdef DEBUG_DMA
   1583 	printf("alloc_range: t=%p size=%lx align=%lx boundary=%lx segs=%p nsegs=%x rsegs=%p flags=%x lo=%lx hi=%lx\n",
   1584 	    t, size, alignment, boundary, segs, nsegs, rsegs, flags, low, high);
   1585 #endif	/* DEBUG_DMA */
   1586 
   1587 	/* Always round the size. */
   1588 	size = round_page(size);
   1589 
   1590 	/*
   1591 	 * We accept boundaries < size, splitting in multiple segments
   1592 	 * if needed. uvm_pglistalloc does not, so compute an appropriate
   1593 	 * boundary: next power of 2 >= size
   1594 	 */
   1595 	bus_size_t uboundary = boundary;
   1596 	if (uboundary <= PAGE_SIZE) {
   1597 		uboundary = 0;
   1598 	} else {
   1599 		while (uboundary < size) {
   1600 			uboundary <<= 1;
   1601 		}
   1602 	}
   1603 
   1604 	/*
   1605 	 * Allocate pages from the VM system.
   1606 	 */
   1607 	error = uvm_pglistalloc(size, low, high, alignment, uboundary,
   1608 	    &mlist, nsegs, (flags & BUS_DMA_NOWAIT) == 0);
   1609 	if (error)
   1610 		return (error);
   1611 
   1612 	/*
   1613 	 * Compute the location, size, and number of segments actually
   1614 	 * returned by the VM code.
   1615 	 */
   1616 	m = TAILQ_FIRST(&mlist);
   1617 	curseg = 0;
   1618 	lastaddr = segs[curseg].ds_addr = VM_PAGE_TO_PHYS(m);
   1619 	segs[curseg].ds_len = PAGE_SIZE;
   1620 #ifdef DEBUG_DMA
   1621 		printf("alloc: page %lx\n", lastaddr);
   1622 #endif	/* DEBUG_DMA */
   1623 	m = TAILQ_NEXT(m, pageq.queue);
   1624 
   1625 	for (; m != NULL; m = TAILQ_NEXT(m, pageq.queue)) {
   1626 		curaddr = VM_PAGE_TO_PHYS(m);
   1627 		KASSERTMSG(low <= curaddr && curaddr < high,
   1628 		    "uvm_pglistalloc returned non-sensicaladdress %#lx "
   1629 		    "(low=%#lx, high=%#lx\n", curaddr, low, high);
   1630 #ifdef DEBUG_DMA
   1631 		printf("alloc: page %lx\n", curaddr);
   1632 #endif	/* DEBUG_DMA */
   1633 		if (curaddr == lastaddr + PAGE_SIZE
   1634 		    && (lastaddr & boundary) == (curaddr & boundary))
   1635 			segs[curseg].ds_len += PAGE_SIZE;
   1636 		else {
   1637 			curseg++;
   1638 			if (curseg >= nsegs) {
   1639 				uvm_pglistfree(&mlist);
   1640 				return EFBIG;
   1641 			}
   1642 			segs[curseg].ds_addr = curaddr;
   1643 			segs[curseg].ds_len = PAGE_SIZE;
   1644 		}
   1645 		lastaddr = curaddr;
   1646 	}
   1647 
   1648 	*rsegs = curseg + 1;
   1649 
   1650 	return (0);
   1651 }
   1652 
   1653 /*
   1654  * Check if a memory region intersects with a DMA range, and return the
   1655  * page-rounded intersection if it does.
   1656  */
   1657 int
   1658 arm32_dma_range_intersect(struct arm32_dma_range *ranges, int nranges,
   1659     paddr_t pa, psize_t size, paddr_t *pap, psize_t *sizep)
   1660 {
   1661 	struct arm32_dma_range *dr;
   1662 	int i;
   1663 
   1664 	if (ranges == NULL)
   1665 		return (0);
   1666 
   1667 	for (i = 0, dr = ranges; i < nranges; i++, dr++) {
   1668 		if (dr->dr_sysbase <= pa &&
   1669 		    pa < (dr->dr_sysbase + dr->dr_len)) {
   1670 			/*
   1671 			 * Beginning of region intersects with this range.
   1672 			 */
   1673 			*pap = trunc_page(pa);
   1674 			*sizep = round_page(min(pa + size,
   1675 			    dr->dr_sysbase + dr->dr_len) - pa);
   1676 			return (1);
   1677 		}
   1678 		if (pa < dr->dr_sysbase && dr->dr_sysbase < (pa + size)) {
   1679 			/*
   1680 			 * End of region intersects with this range.
   1681 			 */
   1682 			*pap = trunc_page(dr->dr_sysbase);
   1683 			*sizep = round_page(min((pa + size) - dr->dr_sysbase,
   1684 			    dr->dr_len));
   1685 			return (1);
   1686 		}
   1687 	}
   1688 
   1689 	/* No intersection found. */
   1690 	return (0);
   1691 }
   1692 
   1693 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1694 static int
   1695 _bus_dma_alloc_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map,
   1696     bus_size_t size, int flags)
   1697 {
   1698 	struct arm32_bus_dma_cookie *cookie = map->_dm_cookie;
   1699 	int error = 0;
   1700 
   1701 	KASSERT(cookie != NULL);
   1702 
   1703 	cookie->id_bouncebuflen = round_page(size);
   1704 	error = _bus_dmamem_alloc(t, cookie->id_bouncebuflen,
   1705 	    PAGE_SIZE, map->_dm_boundary, cookie->id_bouncesegs,
   1706 	    map->_dm_segcnt, &cookie->id_nbouncesegs, flags);
   1707 	if (error == 0) {
   1708 		error = _bus_dmamem_map(t, cookie->id_bouncesegs,
   1709 		    cookie->id_nbouncesegs, cookie->id_bouncebuflen,
   1710 		    (void **)&cookie->id_bouncebuf, flags);
   1711 		if (error) {
   1712 			_bus_dmamem_free(t, cookie->id_bouncesegs,
   1713 			    cookie->id_nbouncesegs);
   1714 			cookie->id_bouncebuflen = 0;
   1715 			cookie->id_nbouncesegs = 0;
   1716 		} else {
   1717 			cookie->id_flags |= _BUS_DMA_HAS_BOUNCE;
   1718 		}
   1719 	} else {
   1720 		cookie->id_bouncebuflen = 0;
   1721 		cookie->id_nbouncesegs = 0;
   1722 	}
   1723 
   1724 	return (error);
   1725 }
   1726 
   1727 static void
   1728 _bus_dma_free_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map)
   1729 {
   1730 	struct arm32_bus_dma_cookie *cookie = map->_dm_cookie;
   1731 
   1732 	KASSERT(cookie != NULL);
   1733 
   1734 	_bus_dmamem_unmap(t, cookie->id_bouncebuf, cookie->id_bouncebuflen);
   1735 	_bus_dmamem_free(t, cookie->id_bouncesegs, cookie->id_nbouncesegs);
   1736 	cookie->id_bouncebuflen = 0;
   1737 	cookie->id_nbouncesegs = 0;
   1738 	cookie->id_flags &= ~_BUS_DMA_HAS_BOUNCE;
   1739 }
   1740 
   1741 /*
   1742  * This function does the same as uiomove, but takes an explicit
   1743  * direction, and does not update the uio structure.
   1744  */
   1745 static int
   1746 _bus_dma_uiomove(void *buf, struct uio *uio, size_t n, int direction)
   1747 {
   1748 	struct iovec *iov;
   1749 	int error;
   1750 	struct vmspace *vm;
   1751 	char *cp;
   1752 	size_t resid, cnt;
   1753 	int i;
   1754 
   1755 	iov = uio->uio_iov;
   1756 	vm = uio->uio_vmspace;
   1757 	cp = buf;
   1758 	resid = n;
   1759 
   1760 	for (i = 0; i < uio->uio_iovcnt && resid > 0; i++) {
   1761 		iov = &uio->uio_iov[i];
   1762 		if (iov->iov_len == 0)
   1763 			continue;
   1764 		cnt = MIN(resid, iov->iov_len);
   1765 
   1766 		if (!VMSPACE_IS_KERNEL_P(vm) &&
   1767 		    (curlwp->l_cpu->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
   1768 		    != 0) {
   1769 			preempt();
   1770 		}
   1771 		if (direction == UIO_READ) {
   1772 			error = copyout_vmspace(vm, cp, iov->iov_base, cnt);
   1773 		} else {
   1774 			error = copyin_vmspace(vm, iov->iov_base, cp, cnt);
   1775 		}
   1776 		if (error)
   1777 			return (error);
   1778 		cp += cnt;
   1779 		resid -= cnt;
   1780 	}
   1781 	return (0);
   1782 }
   1783 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
   1784 
   1785 int
   1786 _bus_dmatag_subregion(bus_dma_tag_t tag, bus_addr_t min_addr,
   1787     bus_addr_t max_addr, bus_dma_tag_t *newtag, int flags)
   1788 {
   1789 
   1790 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1791 	struct arm32_dma_range *dr;
   1792 	bool subset = false;
   1793 	size_t nranges = 0;
   1794 	size_t i;
   1795 	for (i = 0, dr = tag->_ranges; i < tag->_nranges; i++, dr++) {
   1796 		if (dr->dr_sysbase <= min_addr
   1797 		    && max_addr <= dr->dr_sysbase + dr->dr_len - 1) {
   1798 			subset = true;
   1799 		}
   1800 		if (min_addr <= dr->dr_sysbase + dr->dr_len
   1801 		    && max_addr >= dr->dr_sysbase) {
   1802 			nranges++;
   1803 		}
   1804 	}
   1805 	if (subset) {
   1806 		*newtag = tag;
   1807 		/* if the tag must be freed, add a reference */
   1808 		if (tag->_tag_needs_free)
   1809 			(tag->_tag_needs_free)++;
   1810 		return 0;
   1811 	}
   1812 	if (nranges == 0) {
   1813 		nranges = 1;
   1814 	}
   1815 
   1816 	const size_t tagsize = sizeof(*tag) + nranges * sizeof(*dr);
   1817 	if ((*newtag = kmem_intr_zalloc(tagsize,
   1818 	    (flags & BUS_DMA_NOWAIT) ? KM_NOSLEEP : KM_SLEEP)) == NULL)
   1819 		return ENOMEM;
   1820 
   1821 	dr = (void *)(*newtag + 1);
   1822 	**newtag = *tag;
   1823 	(*newtag)->_tag_needs_free = 1;
   1824 	(*newtag)->_ranges = dr;
   1825 	(*newtag)->_nranges = nranges;
   1826 
   1827 	if (tag->_ranges == NULL) {
   1828 		dr->dr_sysbase = min_addr;
   1829 		dr->dr_busbase = min_addr;
   1830 		dr->dr_len = max_addr + 1 - min_addr;
   1831 	} else {
   1832 		for (i = 0; i < nranges; i++) {
   1833 			if (min_addr > dr->dr_sysbase + dr->dr_len
   1834 			    || max_addr < dr->dr_sysbase)
   1835 				continue;
   1836 			dr[0] = tag->_ranges[i];
   1837 			if (dr->dr_sysbase < min_addr) {
   1838 				psize_t diff = min_addr - dr->dr_sysbase;
   1839 				dr->dr_busbase += diff;
   1840 				dr->dr_len -= diff;
   1841 				dr->dr_sysbase += diff;
   1842 			}
   1843 			if (max_addr != 0xffffffff
   1844 			    && max_addr + 1 < dr->dr_sysbase + dr->dr_len) {
   1845 				dr->dr_len = max_addr + 1 - dr->dr_sysbase;
   1846 			}
   1847 			dr++;
   1848 		}
   1849 	}
   1850 
   1851 	return 0;
   1852 #else
   1853 	return EOPNOTSUPP;
   1854 #endif /* _ARM32_NEED_BUS_DMA_BOUNCE */
   1855 }
   1856 
   1857 void
   1858 _bus_dmatag_destroy(bus_dma_tag_t tag)
   1859 {
   1860 #ifdef _ARM32_NEED_BUS_DMA_BOUNCE
   1861 	switch (tag->_tag_needs_free) {
   1862 	case 0:
   1863 		break;				/* not allocated with kmem */
   1864 	case 1: {
   1865 		const size_t tagsize = sizeof(*tag)
   1866 		    + tag->_nranges * sizeof(*tag->_ranges);
   1867 		kmem_intr_free(tag, tagsize);	/* last reference to tag */
   1868 		break;
   1869 	}
   1870 	default:
   1871 		(tag->_tag_needs_free)--;	/* one less reference */
   1872 	}
   1873 #endif
   1874 }
   1875