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