xref: /freebsd/sys/dev/iommu/busdma_iommu.c (revision a64729f5077d77e13b9497cb33ecb3c82e606ee8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2013 The FreeBSD Foundation
5  *
6  * This software was developed by Konstantin Belousov <kib@FreeBSD.org>
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/domainset.h>
34 #include <sys/malloc.h>
35 #include <sys/bus.h>
36 #include <sys/conf.h>
37 #include <sys/interrupt.h>
38 #include <sys/kernel.h>
39 #include <sys/ktr.h>
40 #include <sys/lock.h>
41 #include <sys/proc.h>
42 #include <sys/memdesc.h>
43 #include <sys/msan.h>
44 #include <sys/mutex.h>
45 #include <sys/sysctl.h>
46 #include <sys/rman.h>
47 #include <sys/taskqueue.h>
48 #include <sys/tree.h>
49 #include <sys/uio.h>
50 #include <sys/vmem.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <vm/vm.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_kern.h>
56 #include <vm/vm_object.h>
57 #include <vm/vm_page.h>
58 #include <vm/vm_map.h>
59 #include <dev/iommu/iommu.h>
60 #include <machine/atomic.h>
61 #include <machine/bus.h>
62 #include <machine/md_var.h>
63 #include <machine/iommu.h>
64 #include <dev/iommu/busdma_iommu.h>
65 
66 /*
67  * busdma_iommu.c, the implementation of the busdma(9) interface using
68  * IOMMU units from Intel VT-d.
69  */
70 
71 static bool
72 iommu_bus_dma_is_dev_disabled(int domain, int bus, int slot, int func)
73 {
74 	char str[128], *env;
75 	int default_bounce;
76 	bool ret;
77 	static const char bounce_str[] = "bounce";
78 	static const char iommu_str[] = "iommu";
79 	static const char dmar_str[] = "dmar"; /* compatibility */
80 
81 	default_bounce = 0;
82 	env = kern_getenv("hw.busdma.default");
83 	if (env != NULL) {
84 		if (strcmp(env, bounce_str) == 0)
85 			default_bounce = 1;
86 		else if (strcmp(env, iommu_str) == 0 ||
87 		    strcmp(env, dmar_str) == 0)
88 			default_bounce = 0;
89 		freeenv(env);
90 	}
91 
92 	snprintf(str, sizeof(str), "hw.busdma.pci%d.%d.%d.%d",
93 	    domain, bus, slot, func);
94 	env = kern_getenv(str);
95 	if (env == NULL)
96 		return (default_bounce != 0);
97 	if (strcmp(env, bounce_str) == 0)
98 		ret = true;
99 	else if (strcmp(env, iommu_str) == 0 ||
100 	    strcmp(env, dmar_str) == 0)
101 		ret = false;
102 	else
103 		ret = default_bounce != 0;
104 	freeenv(env);
105 	return (ret);
106 }
107 
108 /*
109  * Given original device, find the requester ID that will be seen by
110  * the IOMMU unit and used for page table lookup.  PCI bridges may take
111  * ownership of transactions from downstream devices, so it may not be
112  * the same as the BSF of the target device.  In those cases, all
113  * devices downstream of the bridge must share a single mapping
114  * domain, and must collectively be assigned to use either IOMMU or
115  * bounce mapping.
116  */
117 device_t
118 iommu_get_requester(device_t dev, uint16_t *rid)
119 {
120 	devclass_t pci_class;
121 	device_t l, pci, pcib, pcip, pcibp, requester;
122 	int cap_offset;
123 	uint16_t pcie_flags;
124 	bool bridge_is_pcie;
125 
126 	pci_class = devclass_find("pci");
127 	l = requester = dev;
128 
129 	pci = device_get_parent(dev);
130 	if (pci == NULL || device_get_devclass(pci) != pci_class) {
131 		*rid = 0;	/* XXXKIB: Could be ACPI HID */
132 		return (requester);
133 	}
134 
135 	*rid = pci_get_rid(dev);
136 
137 	/*
138 	 * Walk the bridge hierarchy from the target device to the
139 	 * host port to find the translating bridge nearest the IOMMU
140 	 * unit.
141 	 */
142 	for (;;) {
143 		pci = device_get_parent(l);
144 		KASSERT(pci != NULL, ("iommu_get_requester(%s): NULL parent "
145 		    "for %s", device_get_name(dev), device_get_name(l)));
146 		KASSERT(device_get_devclass(pci) == pci_class,
147 		    ("iommu_get_requester(%s): non-pci parent %s for %s",
148 		    device_get_name(dev), device_get_name(pci),
149 		    device_get_name(l)));
150 
151 		pcib = device_get_parent(pci);
152 		KASSERT(pcib != NULL, ("iommu_get_requester(%s): NULL bridge "
153 		    "for %s", device_get_name(dev), device_get_name(pci)));
154 
155 		/*
156 		 * The parent of our "bridge" isn't another PCI bus,
157 		 * so pcib isn't a PCI->PCI bridge but rather a host
158 		 * port, and the requester ID won't be translated
159 		 * further.
160 		 */
161 		pcip = device_get_parent(pcib);
162 		if (device_get_devclass(pcip) != pci_class)
163 			break;
164 		pcibp = device_get_parent(pcip);
165 
166 		if (pci_find_cap(l, PCIY_EXPRESS, &cap_offset) == 0) {
167 			/*
168 			 * Do not stop the loop even if the target
169 			 * device is PCIe, because it is possible (but
170 			 * unlikely) to have a PCI->PCIe bridge
171 			 * somewhere in the hierarchy.
172 			 */
173 			l = pcib;
174 		} else {
175 			/*
176 			 * Device is not PCIe, it cannot be seen as a
177 			 * requester by IOMMU unit.  Check whether the
178 			 * bridge is PCIe.
179 			 */
180 			bridge_is_pcie = pci_find_cap(pcib, PCIY_EXPRESS,
181 			    &cap_offset) == 0;
182 			requester = pcib;
183 
184 			/*
185 			 * Check for a buggy PCIe/PCI bridge that
186 			 * doesn't report the express capability.  If
187 			 * the bridge above it is express but isn't a
188 			 * PCI bridge, then we know pcib is actually a
189 			 * PCIe/PCI bridge.
190 			 */
191 			if (!bridge_is_pcie && pci_find_cap(pcibp,
192 			    PCIY_EXPRESS, &cap_offset) == 0) {
193 				pcie_flags = pci_read_config(pcibp,
194 				    cap_offset + PCIER_FLAGS, 2);
195 				if ((pcie_flags & PCIEM_FLAGS_TYPE) !=
196 				    PCIEM_TYPE_PCI_BRIDGE)
197 					bridge_is_pcie = true;
198 			}
199 
200 			if (bridge_is_pcie) {
201 				/*
202 				 * The current device is not PCIe, but
203 				 * the bridge above it is.  This is a
204 				 * PCIe->PCI bridge.  Assume that the
205 				 * requester ID will be the secondary
206 				 * bus number with slot and function
207 				 * set to zero.
208 				 *
209 				 * XXX: Doesn't handle the case where
210 				 * the bridge is PCIe->PCI-X, and the
211 				 * bridge will only take ownership of
212 				 * requests in some cases.  We should
213 				 * provide context entries with the
214 				 * same page tables for taken and
215 				 * non-taken transactions.
216 				 */
217 				*rid = PCI_RID(pci_get_bus(l), 0, 0);
218 				l = pcibp;
219 			} else {
220 				/*
221 				 * Neither the device nor the bridge
222 				 * above it are PCIe.  This is a
223 				 * conventional PCI->PCI bridge, which
224 				 * will use the bridge's BSF as the
225 				 * requester ID.
226 				 */
227 				*rid = pci_get_rid(pcib);
228 				l = pcib;
229 			}
230 		}
231 	}
232 	return (requester);
233 }
234 
235 struct iommu_ctx *
236 iommu_instantiate_ctx(struct iommu_unit *unit, device_t dev, bool rmrr)
237 {
238 	device_t requester;
239 	struct iommu_ctx *ctx;
240 	bool disabled;
241 	uint16_t rid;
242 
243 	requester = iommu_get_requester(dev, &rid);
244 
245 	/*
246 	 * If the user requested the IOMMU disabled for the device, we
247 	 * cannot disable the IOMMU unit, due to possibility of other
248 	 * devices on the same IOMMU unit still requiring translation.
249 	 * Instead provide the identity mapping for the device
250 	 * context.
251 	 */
252 	disabled = iommu_bus_dma_is_dev_disabled(pci_get_domain(requester),
253 	    pci_get_bus(requester), pci_get_slot(requester),
254 	    pci_get_function(requester));
255 	ctx = iommu_get_ctx(unit, requester, rid, disabled, rmrr);
256 	if (ctx == NULL)
257 		return (NULL);
258 	if (disabled) {
259 		/*
260 		 * Keep the first reference on context, release the
261 		 * later refs.
262 		 */
263 		IOMMU_LOCK(unit);
264 		if ((ctx->flags & IOMMU_CTX_DISABLED) == 0) {
265 			ctx->flags |= IOMMU_CTX_DISABLED;
266 			IOMMU_UNLOCK(unit);
267 		} else {
268 			iommu_free_ctx_locked(unit, ctx);
269 		}
270 		ctx = NULL;
271 	}
272 	return (ctx);
273 }
274 
275 struct iommu_ctx *
276 iommu_get_dev_ctx(device_t dev)
277 {
278 	struct iommu_unit *unit;
279 
280 	unit = iommu_find(dev, bootverbose);
281 	/* Not in scope of any IOMMU ? */
282 	if (unit == NULL)
283 		return (NULL);
284 	if (!unit->dma_enabled)
285 		return (NULL);
286 
287 	iommu_unit_pre_instantiate_ctx(unit);
288 	return (iommu_instantiate_ctx(unit, dev, false));
289 }
290 
291 bus_dma_tag_t
292 iommu_get_dma_tag(device_t dev, device_t child)
293 {
294 	struct iommu_ctx *ctx;
295 	bus_dma_tag_t res;
296 
297 	ctx = iommu_get_dev_ctx(child);
298 	if (ctx == NULL)
299 		return (NULL);
300 
301 	res = (bus_dma_tag_t)ctx->tag;
302 	return (res);
303 }
304 
305 bool
306 bus_dma_iommu_set_buswide(device_t dev)
307 {
308 	struct iommu_unit *unit;
309 	device_t parent;
310 	u_int busno, slot, func;
311 
312 	parent = device_get_parent(dev);
313 	if (device_get_devclass(parent) != devclass_find("pci"))
314 		return (false);
315 	unit = iommu_find(dev, bootverbose);
316 	if (unit == NULL)
317 		return (false);
318 	busno = pci_get_bus(dev);
319 	slot = pci_get_slot(dev);
320 	func = pci_get_function(dev);
321 	if (slot != 0 || func != 0) {
322 		if (bootverbose) {
323 			device_printf(dev,
324 			    "iommu%d pci%d:%d:%d requested buswide busdma\n",
325 			    unit->unit, busno, slot, func);
326 		}
327 		return (false);
328 	}
329 	iommu_set_buswide_ctx(unit, busno);
330 	return (true);
331 }
332 
333 void
334 iommu_set_buswide_ctx(struct iommu_unit *unit, u_int busno)
335 {
336 
337 	MPASS(busno <= PCI_BUSMAX);
338 	IOMMU_LOCK(unit);
339 	unit->buswide_ctxs[busno / NBBY / sizeof(uint32_t)] |=
340 	    1 << (busno % (NBBY * sizeof(uint32_t)));
341 	IOMMU_UNLOCK(unit);
342 }
343 
344 bool
345 iommu_is_buswide_ctx(struct iommu_unit *unit, u_int busno)
346 {
347 
348 	MPASS(busno <= PCI_BUSMAX);
349 	return ((unit->buswide_ctxs[busno / NBBY / sizeof(uint32_t)] &
350 	    (1U << (busno % (NBBY * sizeof(uint32_t))))) != 0);
351 }
352 
353 static MALLOC_DEFINE(M_IOMMU_DMAMAP, "iommu_dmamap", "IOMMU DMA Map");
354 
355 static void iommu_bus_schedule_dmamap(struct iommu_unit *unit,
356     struct bus_dmamap_iommu *map);
357 
358 static int
359 iommu_bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
360     bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr,
361     bus_size_t maxsize, int nsegments, bus_size_t maxsegsz, int flags,
362     bus_dma_lock_t *lockfunc, void *lockfuncarg, bus_dma_tag_t *dmat)
363 {
364 	struct bus_dma_tag_iommu *newtag, *oldtag;
365 	int error;
366 
367 	*dmat = NULL;
368 	error = common_bus_dma_tag_create(parent != NULL ?
369 	    &((struct bus_dma_tag_iommu *)parent)->common : NULL, alignment,
370 	    boundary, lowaddr, highaddr, maxsize, nsegments, maxsegsz, flags,
371 	    lockfunc, lockfuncarg, sizeof(struct bus_dma_tag_iommu),
372 	    (void **)&newtag);
373 	if (error != 0)
374 		goto out;
375 
376 	oldtag = (struct bus_dma_tag_iommu *)parent;
377 	newtag->common.impl = &bus_dma_iommu_impl;
378 	newtag->ctx = oldtag->ctx;
379 	newtag->owner = oldtag->owner;
380 
381 	*dmat = (bus_dma_tag_t)newtag;
382 out:
383 	CTR4(KTR_BUSDMA, "%s returned tag %p tag flags 0x%x error %d",
384 	    __func__, newtag, (newtag != NULL ? newtag->common.flags : 0),
385 	    error);
386 	return (error);
387 }
388 
389 static int
390 iommu_bus_dma_tag_set_domain(bus_dma_tag_t dmat)
391 {
392 
393 	return (0);
394 }
395 
396 static int
397 iommu_bus_dma_tag_destroy(bus_dma_tag_t dmat1)
398 {
399 	struct bus_dma_tag_iommu *dmat;
400 	int error;
401 
402 	error = 0;
403 	dmat = (struct bus_dma_tag_iommu *)dmat1;
404 
405 	if (dmat != NULL) {
406 		if (dmat->map_count != 0) {
407 			error = EBUSY;
408 			goto out;
409 		}
410 		if (dmat == dmat->ctx->tag)
411 			iommu_free_ctx(dmat->ctx);
412 		free(dmat->segments, M_IOMMU_DMAMAP);
413 		free(dmat, M_DEVBUF);
414 	}
415 out:
416 	CTR3(KTR_BUSDMA, "%s tag %p error %d", __func__, dmat, error);
417 	return (error);
418 }
419 
420 static bool
421 iommu_bus_dma_id_mapped(bus_dma_tag_t dmat, vm_paddr_t buf, bus_size_t buflen)
422 {
423 
424 	return (false);
425 }
426 
427 static int
428 iommu_bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)
429 {
430 	struct bus_dma_tag_iommu *tag;
431 	struct bus_dmamap_iommu *map;
432 
433 	tag = (struct bus_dma_tag_iommu *)dmat;
434 	map = malloc_domainset(sizeof(*map), M_IOMMU_DMAMAP,
435 	    DOMAINSET_PREF(tag->common.domain), M_NOWAIT | M_ZERO);
436 	if (map == NULL) {
437 		*mapp = NULL;
438 		return (ENOMEM);
439 	}
440 	if (tag->segments == NULL) {
441 		tag->segments = malloc_domainset(sizeof(bus_dma_segment_t) *
442 		    tag->common.nsegments, M_IOMMU_DMAMAP,
443 		    DOMAINSET_PREF(tag->common.domain), M_NOWAIT);
444 		if (tag->segments == NULL) {
445 			free(map, M_IOMMU_DMAMAP);
446 			*mapp = NULL;
447 			return (ENOMEM);
448 		}
449 	}
450 	IOMMU_DMAMAP_INIT(map);
451 	TAILQ_INIT(&map->map_entries);
452 	map->tag = tag;
453 	map->locked = true;
454 	map->cansleep = false;
455 	tag->map_count++;
456 	*mapp = (bus_dmamap_t)map;
457 
458 	return (0);
459 }
460 
461 static int
462 iommu_bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map1)
463 {
464 	struct bus_dma_tag_iommu *tag;
465 	struct bus_dmamap_iommu *map;
466 
467 	tag = (struct bus_dma_tag_iommu *)dmat;
468 	map = (struct bus_dmamap_iommu *)map1;
469 	if (map != NULL) {
470 		IOMMU_DMAMAP_LOCK(map);
471 		if (!TAILQ_EMPTY(&map->map_entries)) {
472 			IOMMU_DMAMAP_UNLOCK(map);
473 			return (EBUSY);
474 		}
475 		IOMMU_DMAMAP_DESTROY(map);
476 		free(map, M_IOMMU_DMAMAP);
477 	}
478 	tag->map_count--;
479 	return (0);
480 }
481 
482 
483 static int
484 iommu_bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
485     bus_dmamap_t *mapp)
486 {
487 	struct bus_dma_tag_iommu *tag;
488 	struct bus_dmamap_iommu *map;
489 	int error, mflags;
490 	vm_memattr_t attr;
491 
492 	error = iommu_bus_dmamap_create(dmat, flags, mapp);
493 	if (error != 0)
494 		return (error);
495 
496 	mflags = (flags & BUS_DMA_NOWAIT) != 0 ? M_NOWAIT : M_WAITOK;
497 	mflags |= (flags & BUS_DMA_ZERO) != 0 ? M_ZERO : 0;
498 	attr = (flags & BUS_DMA_NOCACHE) != 0 ? VM_MEMATTR_UNCACHEABLE :
499 	    VM_MEMATTR_DEFAULT;
500 
501 	tag = (struct bus_dma_tag_iommu *)dmat;
502 	map = (struct bus_dmamap_iommu *)*mapp;
503 
504 	if (tag->common.maxsize < PAGE_SIZE &&
505 	    tag->common.alignment <= tag->common.maxsize &&
506 	    attr == VM_MEMATTR_DEFAULT) {
507 		*vaddr = malloc_domainset(tag->common.maxsize, M_DEVBUF,
508 		    DOMAINSET_PREF(tag->common.domain), mflags);
509 		map->flags |= BUS_DMAMAP_IOMMU_MALLOC;
510 	} else {
511 		*vaddr = kmem_alloc_attr_domainset(
512 		    DOMAINSET_PREF(tag->common.domain), tag->common.maxsize,
513 		    mflags, 0ul, BUS_SPACE_MAXADDR, attr);
514 		map->flags |= BUS_DMAMAP_IOMMU_KMEM_ALLOC;
515 	}
516 	if (*vaddr == NULL) {
517 		iommu_bus_dmamap_destroy(dmat, *mapp);
518 		*mapp = NULL;
519 		return (ENOMEM);
520 	}
521 	return (0);
522 }
523 
524 static void
525 iommu_bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map1)
526 {
527 	struct bus_dma_tag_iommu *tag;
528 	struct bus_dmamap_iommu *map;
529 
530 	tag = (struct bus_dma_tag_iommu *)dmat;
531 	map = (struct bus_dmamap_iommu *)map1;
532 
533 	if ((map->flags & BUS_DMAMAP_IOMMU_MALLOC) != 0) {
534 		free(vaddr, M_DEVBUF);
535 		map->flags &= ~BUS_DMAMAP_IOMMU_MALLOC;
536 	} else {
537 		KASSERT((map->flags & BUS_DMAMAP_IOMMU_KMEM_ALLOC) != 0,
538 		    ("iommu_bus_dmamem_free for non alloced map %p", map));
539 		kmem_free(vaddr, tag->common.maxsize);
540 		map->flags &= ~BUS_DMAMAP_IOMMU_KMEM_ALLOC;
541 	}
542 
543 	iommu_bus_dmamap_destroy(dmat, map1);
544 }
545 
546 static int
547 iommu_bus_dmamap_load_something1(struct bus_dma_tag_iommu *tag,
548     struct bus_dmamap_iommu *map, vm_page_t *ma, int offset, bus_size_t buflen,
549     int flags, bus_dma_segment_t *segs, int *segp,
550     struct iommu_map_entries_tailq *entries)
551 {
552 	struct iommu_ctx *ctx;
553 	struct iommu_domain *domain;
554 	struct iommu_map_entry *entry;
555 	bus_size_t buflen1;
556 	int error, e_flags, idx, gas_flags, seg;
557 
558 	KASSERT(offset < IOMMU_PAGE_SIZE, ("offset %d", offset));
559 	if (segs == NULL)
560 		segs = tag->segments;
561 	ctx = tag->ctx;
562 	domain = ctx->domain;
563 	e_flags = IOMMU_MAP_ENTRY_READ |
564 	    ((flags & BUS_DMA_NOWRITE) == 0 ? IOMMU_MAP_ENTRY_WRITE : 0);
565 	seg = *segp;
566 	error = 0;
567 	idx = 0;
568 	while (buflen > 0) {
569 		seg++;
570 		if (seg >= tag->common.nsegments) {
571 			error = EFBIG;
572 			break;
573 		}
574 		buflen1 = buflen > tag->common.maxsegsz ?
575 		    tag->common.maxsegsz : buflen;
576 
577 		/*
578 		 * (Too) optimistically allow split if there are more
579 		 * then one segments left.
580 		 */
581 		gas_flags = map->cansleep ? IOMMU_MF_CANWAIT : 0;
582 		if (seg + 1 < tag->common.nsegments)
583 			gas_flags |= IOMMU_MF_CANSPLIT;
584 
585 		error = iommu_gas_map(domain, &tag->common, buflen1,
586 		    offset, e_flags, gas_flags, ma + idx, &entry);
587 		if (error != 0)
588 			break;
589 		/* Update buflen1 in case buffer split. */
590 		if (buflen1 > entry->end - entry->start - offset)
591 			buflen1 = entry->end - entry->start - offset;
592 
593 		KASSERT(vm_addr_align_ok(entry->start + offset,
594 		    tag->common.alignment),
595 		    ("alignment failed: ctx %p start 0x%jx offset %x "
596 		    "align 0x%jx", ctx, (uintmax_t)entry->start, offset,
597 		    (uintmax_t)tag->common.alignment));
598 		KASSERT(entry->end <= tag->common.lowaddr ||
599 		    entry->start >= tag->common.highaddr,
600 		    ("entry placement failed: ctx %p start 0x%jx end 0x%jx "
601 		    "lowaddr 0x%jx highaddr 0x%jx", ctx,
602 		    (uintmax_t)entry->start, (uintmax_t)entry->end,
603 		    (uintmax_t)tag->common.lowaddr,
604 		    (uintmax_t)tag->common.highaddr));
605 		KASSERT(vm_addr_bound_ok(entry->start + offset, buflen1,
606 		    tag->common.boundary),
607 		    ("boundary failed: ctx %p start 0x%jx end 0x%jx "
608 		    "boundary 0x%jx", ctx, (uintmax_t)entry->start,
609 		    (uintmax_t)entry->end, (uintmax_t)tag->common.boundary));
610 		KASSERT(buflen1 <= tag->common.maxsegsz,
611 		    ("segment too large: ctx %p start 0x%jx end 0x%jx "
612 		    "buflen1 0x%jx maxsegsz 0x%jx", ctx,
613 		    (uintmax_t)entry->start, (uintmax_t)entry->end,
614 		    (uintmax_t)buflen1, (uintmax_t)tag->common.maxsegsz));
615 
616 		KASSERT((entry->flags & IOMMU_MAP_ENTRY_MAP) != 0,
617 		    ("entry %p missing IOMMU_MAP_ENTRY_MAP", entry));
618 		TAILQ_INSERT_TAIL(entries, entry, dmamap_link);
619 
620 		segs[seg].ds_addr = entry->start + offset;
621 		segs[seg].ds_len = buflen1;
622 
623 		idx += OFF_TO_IDX(offset + buflen1);
624 		offset += buflen1;
625 		offset &= IOMMU_PAGE_MASK;
626 		buflen -= buflen1;
627 	}
628 	if (error == 0)
629 		*segp = seg;
630 	return (error);
631 }
632 
633 static int
634 iommu_bus_dmamap_load_something(struct bus_dma_tag_iommu *tag,
635     struct bus_dmamap_iommu *map, vm_page_t *ma, int offset, bus_size_t buflen,
636     int flags, bus_dma_segment_t *segs, int *segp)
637 {
638 	struct iommu_ctx *ctx;
639 	struct iommu_domain *domain;
640 	struct iommu_map_entries_tailq entries;
641 	int error;
642 
643 	ctx = tag->ctx;
644 	domain = ctx->domain;
645 	atomic_add_long(&ctx->loads, 1);
646 
647 	TAILQ_INIT(&entries);
648 	error = iommu_bus_dmamap_load_something1(tag, map, ma, offset,
649 	    buflen, flags, segs, segp, &entries);
650 	if (error == 0) {
651 		IOMMU_DMAMAP_LOCK(map);
652 		TAILQ_CONCAT(&map->map_entries, &entries, dmamap_link);
653 		IOMMU_DMAMAP_UNLOCK(map);
654 	} else if (!TAILQ_EMPTY(&entries)) {
655 		/*
656 		 * The busdma interface does not allow us to report
657 		 * partial buffer load, so unfortunately we have to
658 		 * revert all work done.
659 		 */
660 		IOMMU_DOMAIN_LOCK(domain);
661 		TAILQ_CONCAT(&domain->unload_entries, &entries, dmamap_link);
662 		IOMMU_DOMAIN_UNLOCK(domain);
663 		taskqueue_enqueue(domain->iommu->delayed_taskqueue,
664 		    &domain->unload_task);
665 	}
666 
667 	if (error == ENOMEM && (flags & BUS_DMA_NOWAIT) == 0 &&
668 	    !map->cansleep)
669 		error = EINPROGRESS;
670 	if (error == EINPROGRESS)
671 		iommu_bus_schedule_dmamap(domain->iommu, map);
672 	return (error);
673 }
674 
675 static int
676 iommu_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map1,
677     struct vm_page **ma, bus_size_t tlen, int ma_offs, int flags,
678     bus_dma_segment_t *segs, int *segp)
679 {
680 	struct bus_dma_tag_iommu *tag;
681 	struct bus_dmamap_iommu *map;
682 
683 	tag = (struct bus_dma_tag_iommu *)dmat;
684 	map = (struct bus_dmamap_iommu *)map1;
685 	return (iommu_bus_dmamap_load_something(tag, map, ma, ma_offs, tlen,
686 	    flags, segs, segp));
687 }
688 
689 static int
690 iommu_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map1,
691     vm_paddr_t buf, bus_size_t buflen, int flags, bus_dma_segment_t *segs,
692     int *segp)
693 {
694 	struct bus_dma_tag_iommu *tag;
695 	struct bus_dmamap_iommu *map;
696 	vm_page_t *ma, fma;
697 	vm_paddr_t pstart, pend, paddr;
698 	int error, i, ma_cnt, mflags, offset;
699 
700 	tag = (struct bus_dma_tag_iommu *)dmat;
701 	map = (struct bus_dmamap_iommu *)map1;
702 	pstart = trunc_page(buf);
703 	pend = round_page(buf + buflen);
704 	offset = buf & PAGE_MASK;
705 	ma_cnt = OFF_TO_IDX(pend - pstart);
706 	mflags = map->cansleep ? M_WAITOK : M_NOWAIT;
707 	ma = malloc(sizeof(vm_page_t) * ma_cnt, M_DEVBUF, mflags);
708 	if (ma == NULL)
709 		return (ENOMEM);
710 	fma = NULL;
711 	for (i = 0; i < ma_cnt; i++) {
712 		paddr = pstart + ptoa(i);
713 		ma[i] = PHYS_TO_VM_PAGE(paddr);
714 		if (ma[i] == NULL || VM_PAGE_TO_PHYS(ma[i]) != paddr) {
715 			/*
716 			 * If PHYS_TO_VM_PAGE() returned NULL or the
717 			 * vm_page was not initialized we'll use a
718 			 * fake page.
719 			 */
720 			if (fma == NULL) {
721 				fma = malloc(sizeof(struct vm_page) * ma_cnt,
722 				    M_DEVBUF, M_ZERO | mflags);
723 				if (fma == NULL) {
724 					free(ma, M_DEVBUF);
725 					return (ENOMEM);
726 				}
727 			}
728 			vm_page_initfake(&fma[i], pstart + ptoa(i),
729 			    VM_MEMATTR_DEFAULT);
730 			ma[i] = &fma[i];
731 		}
732 	}
733 	error = iommu_bus_dmamap_load_something(tag, map, ma, offset, buflen,
734 	    flags, segs, segp);
735 	free(fma, M_DEVBUF);
736 	free(ma, M_DEVBUF);
737 	return (error);
738 }
739 
740 static int
741 iommu_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map1, void *buf,
742     bus_size_t buflen, pmap_t pmap, int flags, bus_dma_segment_t *segs,
743     int *segp)
744 {
745 	struct bus_dma_tag_iommu *tag;
746 	struct bus_dmamap_iommu *map;
747 	vm_page_t *ma, fma;
748 	vm_paddr_t pstart, pend, paddr;
749 	int error, i, ma_cnt, mflags, offset;
750 
751 	tag = (struct bus_dma_tag_iommu *)dmat;
752 	map = (struct bus_dmamap_iommu *)map1;
753 	pstart = trunc_page((vm_offset_t)buf);
754 	pend = round_page((vm_offset_t)buf + buflen);
755 	offset = (vm_offset_t)buf & PAGE_MASK;
756 	ma_cnt = OFF_TO_IDX(pend - pstart);
757 	mflags = map->cansleep ? M_WAITOK : M_NOWAIT;
758 	ma = malloc(sizeof(vm_page_t) * ma_cnt, M_DEVBUF, mflags);
759 	if (ma == NULL)
760 		return (ENOMEM);
761 	fma = NULL;
762 	for (i = 0; i < ma_cnt; i++, pstart += PAGE_SIZE) {
763 		if (pmap == kernel_pmap)
764 			paddr = pmap_kextract(pstart);
765 		else
766 			paddr = pmap_extract(pmap, pstart);
767 		ma[i] = PHYS_TO_VM_PAGE(paddr);
768 		if (ma[i] == NULL || VM_PAGE_TO_PHYS(ma[i]) != paddr) {
769 			/*
770 			 * If PHYS_TO_VM_PAGE() returned NULL or the
771 			 * vm_page was not initialized we'll use a
772 			 * fake page.
773 			 */
774 			if (fma == NULL) {
775 				fma = malloc(sizeof(struct vm_page) * ma_cnt,
776 				    M_DEVBUF, M_ZERO | mflags);
777 				if (fma == NULL) {
778 					free(ma, M_DEVBUF);
779 					return (ENOMEM);
780 				}
781 			}
782 			vm_page_initfake(&fma[i], paddr, VM_MEMATTR_DEFAULT);
783 			ma[i] = &fma[i];
784 		}
785 	}
786 	error = iommu_bus_dmamap_load_something(tag, map, ma, offset, buflen,
787 	    flags, segs, segp);
788 	free(ma, M_DEVBUF);
789 	free(fma, M_DEVBUF);
790 	return (error);
791 }
792 
793 static void
794 iommu_bus_dmamap_waitok(bus_dma_tag_t dmat, bus_dmamap_t map1,
795     struct memdesc *mem, bus_dmamap_callback_t *callback, void *callback_arg)
796 {
797 	struct bus_dmamap_iommu *map;
798 
799 	if (map1 == NULL)
800 		return;
801 	map = (struct bus_dmamap_iommu *)map1;
802 	map->mem = *mem;
803 	map->tag = (struct bus_dma_tag_iommu *)dmat;
804 	map->callback = callback;
805 	map->callback_arg = callback_arg;
806 }
807 
808 static bus_dma_segment_t *
809 iommu_bus_dmamap_complete(bus_dma_tag_t dmat, bus_dmamap_t map1,
810     bus_dma_segment_t *segs, int nsegs, int error)
811 {
812 	struct bus_dma_tag_iommu *tag;
813 	struct bus_dmamap_iommu *map;
814 
815 	tag = (struct bus_dma_tag_iommu *)dmat;
816 	map = (struct bus_dmamap_iommu *)map1;
817 
818 	if (!map->locked) {
819 		KASSERT(map->cansleep,
820 		    ("map not locked and not sleepable context %p", map));
821 
822 		/*
823 		 * We are called from the delayed context.  Relock the
824 		 * driver.
825 		 */
826 		(tag->common.lockfunc)(tag->common.lockfuncarg, BUS_DMA_LOCK);
827 		map->locked = true;
828 	}
829 
830 	if (segs == NULL)
831 		segs = tag->segments;
832 	return (segs);
833 }
834 
835 /*
836  * The limitations of busdma KPI forces the iommu to perform the actual
837  * unload, consisting of the unmapping of the map entries page tables,
838  * from the delayed context on i386, since page table page mapping
839  * might require a sleep to be successfull.  The unfortunate
840  * consequence is that the DMA requests can be served some time after
841  * the bus_dmamap_unload() call returned.
842  *
843  * On amd64, we assume that sf allocation cannot fail.
844  */
845 static void
846 iommu_bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map1)
847 {
848 	struct bus_dma_tag_iommu *tag;
849 	struct bus_dmamap_iommu *map;
850 	struct iommu_ctx *ctx;
851 	struct iommu_domain *domain;
852 	struct iommu_map_entries_tailq entries;
853 
854 	tag = (struct bus_dma_tag_iommu *)dmat;
855 	map = (struct bus_dmamap_iommu *)map1;
856 	ctx = tag->ctx;
857 	domain = ctx->domain;
858 	atomic_add_long(&ctx->unloads, 1);
859 
860 	TAILQ_INIT(&entries);
861 	IOMMU_DMAMAP_LOCK(map);
862 	TAILQ_CONCAT(&entries, &map->map_entries, dmamap_link);
863 	IOMMU_DMAMAP_UNLOCK(map);
864 #if defined(IOMMU_DOMAIN_UNLOAD_SLEEP)
865 	IOMMU_DOMAIN_LOCK(domain);
866 	TAILQ_CONCAT(&domain->unload_entries, &entries, dmamap_link);
867 	IOMMU_DOMAIN_UNLOCK(domain);
868 	taskqueue_enqueue(domain->iommu->delayed_taskqueue,
869 	    &domain->unload_task);
870 #else
871 	THREAD_NO_SLEEPING();
872 	iommu_domain_unload(domain, &entries, false);
873 	THREAD_SLEEPING_OK();
874 	KASSERT(TAILQ_EMPTY(&entries), ("lazy iommu_ctx_unload %p", ctx));
875 #endif
876 }
877 
878 static void
879 iommu_bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map1,
880     bus_dmasync_op_t op)
881 {
882 	struct bus_dmamap_iommu *map __unused;
883 
884 	map = (struct bus_dmamap_iommu *)map1;
885 	kmsan_bus_dmamap_sync(&map->kmsan_mem, op);
886 }
887 
888 #ifdef KMSAN
889 static void
890 iommu_bus_dmamap_load_kmsan(bus_dmamap_t map1, struct memdesc *mem)
891 {
892 	struct bus_dmamap_iommu *map;
893 
894 	map = (struct bus_dmamap_iommu *)map1;
895 	if (map == NULL)
896 		return;
897 	memcpy(&map->kmsan_mem, mem, sizeof(struct memdesc));
898 }
899 #endif
900 
901 struct bus_dma_impl bus_dma_iommu_impl = {
902 	.tag_create = iommu_bus_dma_tag_create,
903 	.tag_destroy = iommu_bus_dma_tag_destroy,
904 	.tag_set_domain = iommu_bus_dma_tag_set_domain,
905 	.id_mapped = iommu_bus_dma_id_mapped,
906 	.map_create = iommu_bus_dmamap_create,
907 	.map_destroy = iommu_bus_dmamap_destroy,
908 	.mem_alloc = iommu_bus_dmamem_alloc,
909 	.mem_free = iommu_bus_dmamem_free,
910 	.load_phys = iommu_bus_dmamap_load_phys,
911 	.load_buffer = iommu_bus_dmamap_load_buffer,
912 	.load_ma = iommu_bus_dmamap_load_ma,
913 	.map_waitok = iommu_bus_dmamap_waitok,
914 	.map_complete = iommu_bus_dmamap_complete,
915 	.map_unload = iommu_bus_dmamap_unload,
916 	.map_sync = iommu_bus_dmamap_sync,
917 #ifdef KMSAN
918 	.load_kmsan = iommu_bus_dmamap_load_kmsan,
919 #endif
920 };
921 
922 static void
923 iommu_bus_task_dmamap(void *arg, int pending)
924 {
925 	struct bus_dma_tag_iommu *tag;
926 	struct bus_dmamap_iommu *map;
927 	struct iommu_unit *unit;
928 
929 	unit = arg;
930 	IOMMU_LOCK(unit);
931 	while ((map = TAILQ_FIRST(&unit->delayed_maps)) != NULL) {
932 		TAILQ_REMOVE(&unit->delayed_maps, map, delay_link);
933 		IOMMU_UNLOCK(unit);
934 		tag = map->tag;
935 		map->cansleep = true;
936 		map->locked = false;
937 		bus_dmamap_load_mem((bus_dma_tag_t)tag, (bus_dmamap_t)map,
938 		    &map->mem, map->callback, map->callback_arg,
939 		    BUS_DMA_WAITOK);
940 		map->cansleep = false;
941 		if (map->locked) {
942 			(tag->common.lockfunc)(tag->common.lockfuncarg,
943 			    BUS_DMA_UNLOCK);
944 		} else
945 			map->locked = true;
946 		map->cansleep = false;
947 		IOMMU_LOCK(unit);
948 	}
949 	IOMMU_UNLOCK(unit);
950 }
951 
952 static void
953 iommu_bus_schedule_dmamap(struct iommu_unit *unit, struct bus_dmamap_iommu *map)
954 {
955 
956 	map->locked = false;
957 	IOMMU_LOCK(unit);
958 	TAILQ_INSERT_TAIL(&unit->delayed_maps, map, delay_link);
959 	IOMMU_UNLOCK(unit);
960 	taskqueue_enqueue(unit->delayed_taskqueue, &unit->dmamap_load_task);
961 }
962 
963 int
964 iommu_init_busdma(struct iommu_unit *unit)
965 {
966 	int error;
967 
968 	unit->dma_enabled = 0;
969 	error = TUNABLE_INT_FETCH("hw.iommu.dma", &unit->dma_enabled);
970 	if (error == 0) /* compatibility */
971 		TUNABLE_INT_FETCH("hw.dmar.dma", &unit->dma_enabled);
972 	SYSCTL_ADD_INT(&unit->sysctl_ctx,
973 	    SYSCTL_CHILDREN(device_get_sysctl_tree(unit->dev)),
974 	    OID_AUTO, "dma", CTLFLAG_RD, &unit->dma_enabled, 0,
975 	    "DMA ops enabled");
976 	TAILQ_INIT(&unit->delayed_maps);
977 	TASK_INIT(&unit->dmamap_load_task, 0, iommu_bus_task_dmamap, unit);
978 	unit->delayed_taskqueue = taskqueue_create("iommu", M_WAITOK,
979 	    taskqueue_thread_enqueue, &unit->delayed_taskqueue);
980 	taskqueue_start_threads(&unit->delayed_taskqueue, 1, PI_DISK,
981 	    "iommu%d busdma taskq", unit->unit);
982 	return (0);
983 }
984 
985 void
986 iommu_fini_busdma(struct iommu_unit *unit)
987 {
988 
989 	if (unit->delayed_taskqueue == NULL)
990 		return;
991 
992 	taskqueue_drain(unit->delayed_taskqueue, &unit->dmamap_load_task);
993 	taskqueue_free(unit->delayed_taskqueue);
994 	unit->delayed_taskqueue = NULL;
995 }
996 
997 int
998 bus_dma_iommu_load_ident(bus_dma_tag_t dmat, bus_dmamap_t map1,
999     vm_paddr_t start, vm_size_t length, int flags)
1000 {
1001 	struct bus_dma_tag_common *tc;
1002 	struct bus_dma_tag_iommu *tag;
1003 	struct bus_dmamap_iommu *map;
1004 	struct iommu_ctx *ctx;
1005 	struct iommu_domain *domain;
1006 	struct iommu_map_entry *entry;
1007 	vm_page_t *ma;
1008 	vm_size_t i;
1009 	int error;
1010 	bool waitok;
1011 
1012 	MPASS((start & PAGE_MASK) == 0);
1013 	MPASS((length & PAGE_MASK) == 0);
1014 	MPASS(length > 0);
1015 	MPASS(start + length >= start);
1016 	MPASS((flags & ~(BUS_DMA_NOWAIT | BUS_DMA_NOWRITE)) == 0);
1017 
1018 	tc = (struct bus_dma_tag_common *)dmat;
1019 	if (tc->impl != &bus_dma_iommu_impl)
1020 		return (0);
1021 
1022 	tag = (struct bus_dma_tag_iommu *)dmat;
1023 	ctx = tag->ctx;
1024 	domain = ctx->domain;
1025 	map = (struct bus_dmamap_iommu *)map1;
1026 	waitok = (flags & BUS_DMA_NOWAIT) != 0;
1027 
1028 	entry = iommu_gas_alloc_entry(domain, waitok ? 0 : IOMMU_PGF_WAITOK);
1029 	if (entry == NULL)
1030 		return (ENOMEM);
1031 	entry->start = start;
1032 	entry->end = start + length;
1033 	ma = malloc(sizeof(vm_page_t) * atop(length), M_TEMP, waitok ?
1034 	    M_WAITOK : M_NOWAIT);
1035 	if (ma == NULL) {
1036 		iommu_gas_free_entry(entry);
1037 		return (ENOMEM);
1038 	}
1039 	for (i = 0; i < atop(length); i++) {
1040 		ma[i] = vm_page_getfake(entry->start + PAGE_SIZE * i,
1041 		    VM_MEMATTR_DEFAULT);
1042 	}
1043 	error = iommu_gas_map_region(domain, entry, IOMMU_MAP_ENTRY_READ |
1044 	    ((flags & BUS_DMA_NOWRITE) ? 0 : IOMMU_MAP_ENTRY_WRITE) |
1045 	    IOMMU_MAP_ENTRY_MAP, waitok ? IOMMU_MF_CANWAIT : 0, ma);
1046 	if (error == 0) {
1047 		IOMMU_DMAMAP_LOCK(map);
1048 		TAILQ_INSERT_TAIL(&map->map_entries, entry, dmamap_link);
1049 		IOMMU_DMAMAP_UNLOCK(map);
1050 	} else {
1051 		iommu_gas_free_entry(entry);
1052 	}
1053 	for (i = 0; i < atop(length); i++)
1054 		vm_page_putfake(ma[i]);
1055 	free(ma, M_TEMP);
1056 	return (error);
1057 }
1058 
1059 static void
1060 iommu_domain_unload_task(void *arg, int pending)
1061 {
1062 	struct iommu_domain *domain;
1063 	struct iommu_map_entries_tailq entries;
1064 
1065 	domain = arg;
1066 	TAILQ_INIT(&entries);
1067 
1068 	for (;;) {
1069 		IOMMU_DOMAIN_LOCK(domain);
1070 		TAILQ_SWAP(&domain->unload_entries, &entries,
1071 		    iommu_map_entry, dmamap_link);
1072 		IOMMU_DOMAIN_UNLOCK(domain);
1073 		if (TAILQ_EMPTY(&entries))
1074 			break;
1075 		iommu_domain_unload(domain, &entries, true);
1076 	}
1077 }
1078 
1079 void
1080 iommu_domain_init(struct iommu_unit *unit, struct iommu_domain *domain,
1081     const struct iommu_domain_map_ops *ops)
1082 {
1083 
1084 	domain->ops = ops;
1085 	domain->iommu = unit;
1086 
1087 	TASK_INIT(&domain->unload_task, 0, iommu_domain_unload_task, domain);
1088 	RB_INIT(&domain->rb_root);
1089 	TAILQ_INIT(&domain->unload_entries);
1090 	mtx_init(&domain->lock, "iodom", NULL, MTX_DEF);
1091 }
1092 
1093 void
1094 iommu_domain_fini(struct iommu_domain *domain)
1095 {
1096 
1097 	mtx_destroy(&domain->lock);
1098 }
1099