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