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