xref: /freebsd/sys/dev/iommu/iommu_gas.c (revision a765ac11c50bb20a64905e365b05b010533f26d3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #define	RB_AUGMENT(entry) iommu_gas_augment_entry(entry)
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
39 #include <sys/bus.h>
40 #include <sys/interrupt.h>
41 #include <sys/kernel.h>
42 #include <sys/ktr.h>
43 #include <sys/lock.h>
44 #include <sys/proc.h>
45 #include <sys/rwlock.h>
46 #include <sys/memdesc.h>
47 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
49 #include <sys/rman.h>
50 #include <sys/taskqueue.h>
51 #include <sys/tree.h>
52 #include <sys/uio.h>
53 #include <sys/vmem.h>
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vm_object.h>
58 #include <vm/vm_page.h>
59 #include <vm/vm_map.h>
60 #include <vm/uma.h>
61 #include <dev/pci/pcireg.h>
62 #include <dev/pci/pcivar.h>
63 #include <dev/iommu/iommu.h>
64 #include <dev/iommu/iommu_gas.h>
65 #include <dev/iommu/iommu_msi.h>
66 #include <machine/atomic.h>
67 #include <machine/bus.h>
68 #include <machine/md_var.h>
69 #include <machine/iommu.h>
70 #include <dev/iommu/busdma_iommu.h>
71 
72 /*
73  * Guest Address Space management.
74  */
75 
76 static uma_zone_t iommu_map_entry_zone;
77 
78 #ifdef INVARIANTS
79 static int iommu_check_free;
80 #endif
81 
82 static void
83 intel_gas_init(void)
84 {
85 
86 	iommu_map_entry_zone = uma_zcreate("IOMMU_MAP_ENTRY",
87 	    sizeof(struct iommu_map_entry), NULL, NULL,
88 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NODUMP);
89 }
90 SYSINIT(intel_gas, SI_SUB_DRIVERS, SI_ORDER_FIRST, intel_gas_init, NULL);
91 
92 struct iommu_map_entry *
93 iommu_gas_alloc_entry(struct iommu_domain *domain, u_int flags)
94 {
95 	struct iommu_map_entry *res;
96 
97 	KASSERT((flags & ~(IOMMU_PGF_WAITOK)) == 0,
98 	    ("unsupported flags %x", flags));
99 
100 	res = uma_zalloc(iommu_map_entry_zone, ((flags & IOMMU_PGF_WAITOK) !=
101 	    0 ? M_WAITOK : M_NOWAIT) | M_ZERO);
102 	if (res != NULL) {
103 		res->domain = domain;
104 		atomic_add_int(&domain->entries_cnt, 1);
105 	}
106 	return (res);
107 }
108 
109 void
110 iommu_gas_free_entry(struct iommu_domain *domain, struct iommu_map_entry *entry)
111 {
112 
113 	KASSERT(domain == entry->domain,
114 	    ("mismatched free domain %p entry %p entry->domain %p", domain,
115 	    entry, entry->domain));
116 	atomic_subtract_int(&domain->entries_cnt, 1);
117 	uma_zfree(iommu_map_entry_zone, entry);
118 }
119 
120 static int
121 iommu_gas_cmp_entries(struct iommu_map_entry *a, struct iommu_map_entry *b)
122 {
123 
124 	/* Last entry have zero size, so <= */
125 	KASSERT(a->start <= a->end, ("inverted entry %p (%jx, %jx)",
126 	    a, (uintmax_t)a->start, (uintmax_t)a->end));
127 	KASSERT(b->start <= b->end, ("inverted entry %p (%jx, %jx)",
128 	    b, (uintmax_t)b->start, (uintmax_t)b->end));
129 	KASSERT(a->end <= b->start || b->end <= a->start ||
130 	    a->end == a->start || b->end == b->start,
131 	    ("overlapping entries %p (%jx, %jx) %p (%jx, %jx)",
132 	    a, (uintmax_t)a->start, (uintmax_t)a->end,
133 	    b, (uintmax_t)b->start, (uintmax_t)b->end));
134 
135 	if (a->end < b->end)
136 		return (-1);
137 	else if (b->end < a->end)
138 		return (1);
139 	return (0);
140 }
141 
142 static void
143 iommu_gas_augment_entry(struct iommu_map_entry *entry)
144 {
145 	struct iommu_map_entry *child;
146 	iommu_gaddr_t free_down;
147 
148 	free_down = 0;
149 	if ((child = RB_LEFT(entry, rb_entry)) != NULL) {
150 		free_down = MAX(free_down, child->free_down);
151 		free_down = MAX(free_down, entry->start - child->last);
152 		entry->first = child->first;
153 	} else
154 		entry->first = entry->start;
155 
156 	if ((child = RB_RIGHT(entry, rb_entry)) != NULL) {
157 		free_down = MAX(free_down, child->free_down);
158 		free_down = MAX(free_down, child->first - entry->end);
159 		entry->last = child->last;
160 	} else
161 		entry->last = entry->end;
162 	entry->free_down = free_down;
163 }
164 
165 RB_GENERATE(iommu_gas_entries_tree, iommu_map_entry, rb_entry,
166     iommu_gas_cmp_entries);
167 
168 #ifdef INVARIANTS
169 static void
170 iommu_gas_check_free(struct iommu_domain *domain)
171 {
172 	struct iommu_map_entry *entry, *l, *r;
173 	iommu_gaddr_t v;
174 
175 	RB_FOREACH(entry, iommu_gas_entries_tree, &domain->rb_root) {
176 		KASSERT(domain == entry->domain,
177 		    ("mismatched free domain %p entry %p entry->domain %p",
178 		    domain, entry, entry->domain));
179 		l = RB_LEFT(entry, rb_entry);
180 		r = RB_RIGHT(entry, rb_entry);
181 		v = 0;
182 		if (l != NULL) {
183 			v = MAX(v, l->free_down);
184 			v = MAX(v, entry->start - l->last);
185 		}
186 		if (r != NULL) {
187 			v = MAX(v, r->free_down);
188 			v = MAX(v, r->first - entry->end);
189 		}
190 		MPASS(entry->free_down == v);
191 	}
192 }
193 #endif
194 
195 static bool
196 iommu_gas_rb_insert(struct iommu_domain *domain, struct iommu_map_entry *entry)
197 {
198 	struct iommu_map_entry *found;
199 
200 	found = RB_INSERT(iommu_gas_entries_tree, &domain->rb_root, entry);
201 	return (found == NULL);
202 }
203 
204 static void
205 iommu_gas_rb_remove(struct iommu_domain *domain, struct iommu_map_entry *entry)
206 {
207 
208 	RB_REMOVE(iommu_gas_entries_tree, &domain->rb_root, entry);
209 }
210 
211 struct iommu_domain *
212 iommu_get_ctx_domain(struct iommu_ctx *ctx)
213 {
214 
215 	return (ctx->domain);
216 }
217 
218 void
219 iommu_gas_init_domain(struct iommu_domain *domain)
220 {
221 	struct iommu_map_entry *begin, *end;
222 
223 	begin = iommu_gas_alloc_entry(domain, IOMMU_PGF_WAITOK);
224 	end = iommu_gas_alloc_entry(domain, IOMMU_PGF_WAITOK);
225 
226 	IOMMU_DOMAIN_LOCK(domain);
227 	KASSERT(domain->entries_cnt == 2, ("dirty domain %p", domain));
228 	KASSERT(RB_EMPTY(&domain->rb_root),
229 	    ("non-empty entries %p", domain));
230 
231 	begin->start = 0;
232 	begin->end = IOMMU_PAGE_SIZE;
233 	begin->flags = IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_UNMAPPED;
234 	iommu_gas_rb_insert(domain, begin);
235 
236 	end->start = domain->end;
237 	end->end = domain->end;
238 	end->flags = IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_UNMAPPED;
239 	iommu_gas_rb_insert(domain, end);
240 
241 	domain->first_place = begin;
242 	domain->last_place = end;
243 	domain->flags |= IOMMU_DOMAIN_GAS_INITED;
244 	IOMMU_DOMAIN_UNLOCK(domain);
245 }
246 
247 void
248 iommu_gas_fini_domain(struct iommu_domain *domain)
249 {
250 	struct iommu_map_entry *entry, *entry1;
251 
252 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
253 	KASSERT(domain->entries_cnt == 2,
254 	    ("domain still in use %p", domain));
255 
256 	entry = RB_MIN(iommu_gas_entries_tree, &domain->rb_root);
257 	KASSERT(entry->start == 0, ("start entry start %p", domain));
258 	KASSERT(entry->end == IOMMU_PAGE_SIZE, ("start entry end %p", domain));
259 	KASSERT(entry->flags ==
260 	    (IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_UNMAPPED),
261 	    ("start entry flags %p", domain));
262 	RB_REMOVE(iommu_gas_entries_tree, &domain->rb_root, entry);
263 	iommu_gas_free_entry(domain, entry);
264 
265 	entry = RB_MAX(iommu_gas_entries_tree, &domain->rb_root);
266 	KASSERT(entry->start == domain->end, ("end entry start %p", domain));
267 	KASSERT(entry->end == domain->end, ("end entry end %p", domain));
268 	KASSERT(entry->flags ==
269 	    (IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_UNMAPPED),
270 	    ("end entry flags %p", domain));
271 	RB_REMOVE(iommu_gas_entries_tree, &domain->rb_root, entry);
272 	iommu_gas_free_entry(domain, entry);
273 
274 	RB_FOREACH_SAFE(entry, iommu_gas_entries_tree, &domain->rb_root,
275 	    entry1) {
276 		KASSERT((entry->flags & IOMMU_MAP_ENTRY_RMRR) != 0,
277 		    ("non-RMRR entry left %p", domain));
278 		RB_REMOVE(iommu_gas_entries_tree, &domain->rb_root,
279 		    entry);
280 		iommu_gas_free_entry(domain, entry);
281 	}
282 }
283 
284 struct iommu_gas_match_args {
285 	struct iommu_domain *domain;
286 	iommu_gaddr_t size;
287 	int offset;
288 	const struct bus_dma_tag_common *common;
289 	u_int gas_flags;
290 	struct iommu_map_entry *entry;
291 };
292 
293 /*
294  * The interval [beg, end) is a free interval between two iommu_map_entries.
295  * maxaddr is an upper bound on addresses that can be allocated. Try to
296  * allocate space in the free interval, subject to the conditions expressed
297  * by a, and return 'true' if and only if the allocation attempt succeeds.
298  */
299 static bool
300 iommu_gas_match_one(struct iommu_gas_match_args *a, iommu_gaddr_t beg,
301     iommu_gaddr_t end, iommu_gaddr_t maxaddr)
302 {
303 	iommu_gaddr_t bs, start;
304 
305 	/*
306 	 * The prev->end is always aligned on the page size, which
307 	 * causes page alignment for the entry->start too.
308 	 *
309 	 * A page sized gap is created between consecutive
310 	 * allocations to ensure that out-of-bounds accesses fault.
311 	 */
312 	a->entry->start = roundup2(beg + IOMMU_PAGE_SIZE,
313 	    a->common->alignment);
314 	if (a->entry->start + a->offset + a->size > maxaddr)
315 		return (false);
316 
317 	/* IOMMU_PAGE_SIZE to create gap after new entry. */
318 	if (a->entry->start < beg + IOMMU_PAGE_SIZE ||
319 	    a->entry->start + a->size + a->offset + IOMMU_PAGE_SIZE > end)
320 		return (false);
321 
322 	/* No boundary crossing. */
323 	if (vm_addr_bound_ok(a->entry->start + a->offset, a->size,
324 	    a->common->boundary))
325 		return (true);
326 
327 	/*
328 	 * The start + offset to start + offset + size region crosses
329 	 * the boundary.  Check if there is enough space after the
330 	 * next boundary after the beg.
331 	 */
332 	bs = rounddown2(a->entry->start + a->offset + a->common->boundary,
333 	    a->common->boundary);
334 	start = roundup2(bs, a->common->alignment);
335 	/* IOMMU_PAGE_SIZE to create gap after new entry. */
336 	if (start + a->offset + a->size + IOMMU_PAGE_SIZE <= end &&
337 	    start + a->offset + a->size <= maxaddr &&
338 	    vm_addr_bound_ok(start + a->offset, a->size,
339 	    a->common->boundary)) {
340 		a->entry->start = start;
341 		return (true);
342 	}
343 
344 	/*
345 	 * Not enough space to align at the requested boundary, or
346 	 * boundary is smaller than the size, but allowed to split.
347 	 * We already checked that start + size does not overlap maxaddr.
348 	 *
349 	 * XXXKIB. It is possible that bs is exactly at the start of
350 	 * the next entry, then we do not have gap.  Ignore for now.
351 	 */
352 	if ((a->gas_flags & IOMMU_MF_CANSPLIT) != 0) {
353 		a->size = bs - a->entry->start - a->offset;
354 		return (true);
355 	}
356 
357 	return (false);
358 }
359 
360 static void
361 iommu_gas_match_insert(struct iommu_gas_match_args *a)
362 {
363 	bool found __diagused;
364 
365 	a->entry->end = a->entry->start +
366 	    roundup2(a->size + a->offset, IOMMU_PAGE_SIZE);
367 
368 	found = iommu_gas_rb_insert(a->domain, a->entry);
369 	KASSERT(found, ("found dup %p start %jx size %jx",
370 	    a->domain, (uintmax_t)a->entry->start, (uintmax_t)a->size));
371 	a->entry->flags = IOMMU_MAP_ENTRY_MAP;
372 }
373 
374 static int
375 iommu_gas_lowermatch(struct iommu_gas_match_args *a, struct iommu_map_entry *entry)
376 {
377 	struct iommu_map_entry *first;
378 	iommu_gaddr_t min_free;
379 
380 	/*
381 	 * If the subtree doesn't have free space for the requested allocation
382 	 * plus two guard pages, skip it.
383 	 */
384 	min_free = 2 * IOMMU_PAGE_SIZE +
385 	    roundup2(a->size + a->offset, IOMMU_PAGE_SIZE);
386 
387 	/* Find the first entry that could abut a big-enough range. */
388 	first = NULL;
389 	while (entry != NULL && entry->free_down >= min_free) {
390 		first = entry;
391 		entry = RB_LEFT(entry, rb_entry);
392 	}
393 
394 	/*
395 	 * Walk the big-enough ranges until one satisfies alignment
396 	 * requirements, or violates lowaddr address requirement.
397 	 */
398 	entry = first;
399 	while (entry != NULL) {
400 		if ((first = RB_LEFT(entry, rb_entry)) != NULL &&
401 		    iommu_gas_match_one(a, first->last, entry->start,
402 		    a->common->lowaddr)) {
403 			iommu_gas_match_insert(a);
404 			return (0);
405 		}
406 		if (entry->end >= a->common->lowaddr) {
407 			/* All remaining ranges >= lowaddr */
408 			break;
409 		}
410 		if ((first = RB_RIGHT(entry, rb_entry)) != NULL &&
411 		    iommu_gas_match_one(a, entry->end, first->first,
412 		    a->common->lowaddr)) {
413 			iommu_gas_match_insert(a);
414 			return (0);
415 		}
416 		/* Find the next entry that might abut a big-enough range. */
417 		if (first != NULL && first->free_down >= min_free) {
418 			/* Find next entry in right subtree. */
419 			do
420 				entry = first;
421 			while ((first = RB_LEFT(entry, rb_entry)) != NULL &&
422 			    first->free_down >= min_free);
423 		} else {
424 			/* Find next entry in a left-parent ancestor. */
425 			while ((first = RB_PARENT(entry, rb_entry)) != NULL &&
426 			    entry == RB_RIGHT(first, rb_entry))
427 				entry = first;
428 			entry = first;
429 		}
430 	}
431 	return (ENOMEM);
432 }
433 
434 static int
435 iommu_gas_uppermatch(struct iommu_gas_match_args *a, struct iommu_map_entry *entry)
436 {
437 	struct iommu_map_entry *child;
438 
439 	/*
440 	 * If the subtree doesn't have free space for the requested allocation
441 	 * plus two guard pages, give up.
442 	 */
443 	if (entry->free_down < 2 * IOMMU_PAGE_SIZE +
444 	    roundup2(a->size + a->offset, IOMMU_PAGE_SIZE))
445 		return (ENOMEM);
446 	if (entry->last < a->common->highaddr)
447 		return (ENOMEM);
448 	child = RB_LEFT(entry, rb_entry);
449 	if (child != NULL && 0 == iommu_gas_uppermatch(a, child))
450 		return (0);
451 	if (child != NULL && child->last >= a->common->highaddr &&
452 	    iommu_gas_match_one(a, child->last, entry->start,
453 	    a->domain->end)) {
454 		iommu_gas_match_insert(a);
455 		return (0);
456 	}
457 	child = RB_RIGHT(entry, rb_entry);
458 	if (child != NULL && entry->end >= a->common->highaddr &&
459 	    iommu_gas_match_one(a, entry->end, child->first,
460 	    a->domain->end)) {
461 		iommu_gas_match_insert(a);
462 		return (0);
463 	}
464 	if (child != NULL && 0 == iommu_gas_uppermatch(a, child))
465 		return (0);
466 	return (ENOMEM);
467 }
468 
469 static int
470 iommu_gas_find_space(struct iommu_domain *domain,
471     const struct bus_dma_tag_common *common, iommu_gaddr_t size,
472     int offset, u_int flags, struct iommu_map_entry *entry)
473 {
474 	struct iommu_gas_match_args a;
475 	int error;
476 
477 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
478 	KASSERT(entry->flags == 0, ("dirty entry %p %p", domain, entry));
479 
480 	a.domain = domain;
481 	a.size = size;
482 	a.offset = offset;
483 	a.common = common;
484 	a.gas_flags = flags;
485 	a.entry = entry;
486 
487 	/* Handle lower region. */
488 	if (common->lowaddr > 0) {
489 		error = iommu_gas_lowermatch(&a, RB_ROOT(&domain->rb_root));
490 		if (error == 0)
491 			return (0);
492 		KASSERT(error == ENOMEM,
493 		    ("error %d from iommu_gas_lowermatch", error));
494 	}
495 	/* Handle upper region. */
496 	if (common->highaddr >= domain->end)
497 		return (ENOMEM);
498 	error = iommu_gas_uppermatch(&a, RB_ROOT(&domain->rb_root));
499 	KASSERT(error == 0 || error == ENOMEM,
500 	    ("error %d from iommu_gas_uppermatch", error));
501 	return (error);
502 }
503 
504 static int
505 iommu_gas_alloc_region(struct iommu_domain *domain, struct iommu_map_entry *entry,
506     u_int flags)
507 {
508 	struct iommu_map_entry *next, *prev;
509 	bool found __diagused;
510 
511 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
512 
513 	if ((entry->start & IOMMU_PAGE_MASK) != 0 ||
514 	    (entry->end & IOMMU_PAGE_MASK) != 0)
515 		return (EINVAL);
516 	if (entry->start >= entry->end)
517 		return (EINVAL);
518 	if (entry->end >= domain->end)
519 		return (EINVAL);
520 
521 	next = RB_NFIND(iommu_gas_entries_tree, &domain->rb_root, entry);
522 	KASSERT(next != NULL, ("next must be non-null %p %jx", domain,
523 	    (uintmax_t)entry->start));
524 	prev = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, next);
525 	/* prev could be NULL */
526 
527 	/*
528 	 * Adapt to broken BIOSes which specify overlapping RMRR
529 	 * entries.
530 	 *
531 	 * XXXKIB: this does not handle a case when prev or next
532 	 * entries are completely covered by the current one, which
533 	 * extends both ways.
534 	 */
535 	if (prev != NULL && prev->end > entry->start &&
536 	    (prev->flags & IOMMU_MAP_ENTRY_PLACE) == 0) {
537 		if ((flags & IOMMU_MF_RMRR) == 0 ||
538 		    (prev->flags & IOMMU_MAP_ENTRY_RMRR) == 0)
539 			return (EBUSY);
540 		entry->start = prev->end;
541 	}
542 	if (next->start < entry->end &&
543 	    (next->flags & IOMMU_MAP_ENTRY_PLACE) == 0) {
544 		if ((flags & IOMMU_MF_RMRR) == 0 ||
545 		    (next->flags & IOMMU_MAP_ENTRY_RMRR) == 0)
546 			return (EBUSY);
547 		entry->end = next->start;
548 	}
549 	if (entry->end == entry->start)
550 		return (0);
551 
552 	if (prev != NULL && prev->end > entry->start) {
553 		/* This assumes that prev is the placeholder entry. */
554 		iommu_gas_rb_remove(domain, prev);
555 		prev = NULL;
556 	}
557 	if (next->start < entry->end) {
558 		iommu_gas_rb_remove(domain, next);
559 		next = NULL;
560 	}
561 
562 	found = iommu_gas_rb_insert(domain, entry);
563 	KASSERT(found, ("found RMRR dup %p start %jx end %jx",
564 	    domain, (uintmax_t)entry->start, (uintmax_t)entry->end));
565 	if ((flags & IOMMU_MF_RMRR) != 0)
566 		entry->flags = IOMMU_MAP_ENTRY_RMRR;
567 
568 #ifdef INVARIANTS
569 	struct iommu_map_entry *ip, *in;
570 	ip = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, entry);
571 	in = RB_NEXT(iommu_gas_entries_tree, &domain->rb_root, entry);
572 	KASSERT(prev == NULL || ip == prev,
573 	    ("RMRR %p (%jx %jx) prev %p (%jx %jx) ins prev %p (%jx %jx)",
574 	    entry, entry->start, entry->end, prev,
575 	    prev == NULL ? 0 : prev->start, prev == NULL ? 0 : prev->end,
576 	    ip, ip == NULL ? 0 : ip->start, ip == NULL ? 0 : ip->end));
577 	KASSERT(next == NULL || in == next,
578 	    ("RMRR %p (%jx %jx) next %p (%jx %jx) ins next %p (%jx %jx)",
579 	    entry, entry->start, entry->end, next,
580 	    next == NULL ? 0 : next->start, next == NULL ? 0 : next->end,
581 	    in, in == NULL ? 0 : in->start, in == NULL ? 0 : in->end));
582 #endif
583 
584 	return (0);
585 }
586 
587 void
588 iommu_gas_free_space(struct iommu_domain *domain, struct iommu_map_entry *entry)
589 {
590 
591 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
592 	KASSERT((entry->flags & (IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_RMRR |
593 	    IOMMU_MAP_ENTRY_MAP)) == IOMMU_MAP_ENTRY_MAP,
594 	    ("permanent entry %p %p", domain, entry));
595 
596 	iommu_gas_rb_remove(domain, entry);
597 	entry->flags &= ~IOMMU_MAP_ENTRY_MAP;
598 #ifdef INVARIANTS
599 	if (iommu_check_free)
600 		iommu_gas_check_free(domain);
601 #endif
602 }
603 
604 void
605 iommu_gas_free_region(struct iommu_domain *domain, struct iommu_map_entry *entry)
606 {
607 	struct iommu_map_entry *next, *prev;
608 
609 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
610 	KASSERT((entry->flags & (IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_RMRR |
611 	    IOMMU_MAP_ENTRY_MAP)) == IOMMU_MAP_ENTRY_RMRR,
612 	    ("non-RMRR entry %p %p", domain, entry));
613 
614 	prev = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, entry);
615 	next = RB_NEXT(iommu_gas_entries_tree, &domain->rb_root, entry);
616 	iommu_gas_rb_remove(domain, entry);
617 	entry->flags &= ~IOMMU_MAP_ENTRY_RMRR;
618 
619 	if (prev == NULL)
620 		iommu_gas_rb_insert(domain, domain->first_place);
621 	if (next == NULL)
622 		iommu_gas_rb_insert(domain, domain->last_place);
623 }
624 
625 int
626 iommu_gas_map(struct iommu_domain *domain,
627     const struct bus_dma_tag_common *common, iommu_gaddr_t size, int offset,
628     u_int eflags, u_int flags, vm_page_t *ma, struct iommu_map_entry **res)
629 {
630 	struct iommu_map_entry *entry;
631 	int error;
632 
633 	KASSERT((flags & ~(IOMMU_MF_CANWAIT | IOMMU_MF_CANSPLIT)) == 0,
634 	    ("invalid flags 0x%x", flags));
635 
636 	entry = iommu_gas_alloc_entry(domain,
637 	    (flags & IOMMU_MF_CANWAIT) != 0 ? IOMMU_PGF_WAITOK : 0);
638 	if (entry == NULL)
639 		return (ENOMEM);
640 	IOMMU_DOMAIN_LOCK(domain);
641 	error = iommu_gas_find_space(domain, common, size, offset, flags,
642 	    entry);
643 	if (error == ENOMEM) {
644 		IOMMU_DOMAIN_UNLOCK(domain);
645 		iommu_gas_free_entry(domain, entry);
646 		return (error);
647 	}
648 #ifdef INVARIANTS
649 	if (iommu_check_free)
650 		iommu_gas_check_free(domain);
651 #endif
652 	KASSERT(error == 0,
653 	    ("unexpected error %d from iommu_gas_find_entry", error));
654 	KASSERT(entry->end < domain->end, ("allocated GPA %jx, max GPA %jx",
655 	    (uintmax_t)entry->end, (uintmax_t)domain->end));
656 	entry->flags |= eflags;
657 	IOMMU_DOMAIN_UNLOCK(domain);
658 
659 	error = domain->ops->map(domain, entry->start,
660 	    entry->end - entry->start, ma, eflags,
661 	    ((flags & IOMMU_MF_CANWAIT) != 0 ? IOMMU_PGF_WAITOK : 0));
662 	if (error == ENOMEM) {
663 		iommu_domain_unload_entry(entry, true);
664 		return (error);
665 	}
666 	KASSERT(error == 0,
667 	    ("unexpected error %d from domain_map_buf", error));
668 
669 	*res = entry;
670 	return (0);
671 }
672 
673 int
674 iommu_gas_map_region(struct iommu_domain *domain, struct iommu_map_entry *entry,
675     u_int eflags, u_int flags, vm_page_t *ma)
676 {
677 	iommu_gaddr_t start;
678 	int error;
679 
680 	KASSERT(entry->flags == 0, ("used RMRR entry %p %p %x", domain,
681 	    entry, entry->flags));
682 	KASSERT((flags & ~(IOMMU_MF_CANWAIT | IOMMU_MF_RMRR)) == 0,
683 	    ("invalid flags 0x%x", flags));
684 
685 	start = entry->start;
686 	IOMMU_DOMAIN_LOCK(domain);
687 	error = iommu_gas_alloc_region(domain, entry, flags);
688 	if (error != 0) {
689 		IOMMU_DOMAIN_UNLOCK(domain);
690 		return (error);
691 	}
692 	entry->flags |= eflags;
693 	IOMMU_DOMAIN_UNLOCK(domain);
694 	if (entry->end == entry->start)
695 		return (0);
696 
697 	error = domain->ops->map(domain, entry->start,
698 	    entry->end - entry->start, ma + OFF_TO_IDX(start - entry->start),
699 	    eflags, ((flags & IOMMU_MF_CANWAIT) != 0 ? IOMMU_PGF_WAITOK : 0));
700 	if (error == ENOMEM) {
701 		iommu_domain_unload_entry(entry, false);
702 		return (error);
703 	}
704 	KASSERT(error == 0,
705 	    ("unexpected error %d from domain_map_buf", error));
706 
707 	return (0);
708 }
709 
710 static int
711 iommu_gas_reserve_region_locked(struct iommu_domain *domain,
712     iommu_gaddr_t start, iommu_gaddr_t end, struct iommu_map_entry *entry)
713 {
714 	int error;
715 
716 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
717 
718 	entry->start = start;
719 	entry->end = end;
720 	error = iommu_gas_alloc_region(domain, entry, IOMMU_MF_CANWAIT);
721 	if (error == 0)
722 		entry->flags |= IOMMU_MAP_ENTRY_UNMAPPED;
723 	return (error);
724 }
725 
726 int
727 iommu_gas_reserve_region(struct iommu_domain *domain, iommu_gaddr_t start,
728     iommu_gaddr_t end, struct iommu_map_entry **entry0)
729 {
730 	struct iommu_map_entry *entry;
731 	int error;
732 
733 	entry = iommu_gas_alloc_entry(domain, IOMMU_PGF_WAITOK);
734 	IOMMU_DOMAIN_LOCK(domain);
735 	error = iommu_gas_reserve_region_locked(domain, start, end, entry);
736 	IOMMU_DOMAIN_UNLOCK(domain);
737 	if (error != 0)
738 		iommu_gas_free_entry(domain, entry);
739 	else if (entry0 != NULL)
740 		*entry0 = entry;
741 	return (error);
742 }
743 
744 /*
745  * As in iommu_gas_reserve_region, reserve [start, end), but allow for existing
746  * entries.
747  */
748 int
749 iommu_gas_reserve_region_extend(struct iommu_domain *domain,
750     iommu_gaddr_t start, iommu_gaddr_t end)
751 {
752 	struct iommu_map_entry *entry, *next, *prev, key = {};
753 	iommu_gaddr_t entry_start, entry_end;
754 	int error;
755 
756 	error = 0;
757 	entry = NULL;
758 	end = ummin(end, domain->end);
759 	while (start < end) {
760 		/* Preallocate an entry. */
761 		if (entry == NULL)
762 			entry = iommu_gas_alloc_entry(domain,
763 			    IOMMU_PGF_WAITOK);
764 		/* Calculate the free region from here to the next entry. */
765 		key.start = key.end = start;
766 		IOMMU_DOMAIN_LOCK(domain);
767 		next = RB_NFIND(iommu_gas_entries_tree, &domain->rb_root, &key);
768 		KASSERT(next != NULL, ("domain %p with end %#jx has no entry "
769 		    "after %#jx", domain, (uintmax_t)domain->end,
770 		    (uintmax_t)start));
771 		entry_end = ummin(end, next->start);
772 		prev = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, next);
773 		if (prev != NULL)
774 			entry_start = ummax(start, prev->end);
775 		else
776 			entry_start = start;
777 		start = next->end;
778 		/* Reserve the region if non-empty. */
779 		if (entry_start != entry_end) {
780 			error = iommu_gas_reserve_region_locked(domain,
781 			    entry_start, entry_end, entry);
782 			if (error != 0) {
783 				IOMMU_DOMAIN_UNLOCK(domain);
784 				break;
785 			}
786 			entry = NULL;
787 		}
788 		IOMMU_DOMAIN_UNLOCK(domain);
789 	}
790 	/* Release a preallocated entry if it was not used. */
791 	if (entry != NULL)
792 		iommu_gas_free_entry(domain, entry);
793 	return (error);
794 }
795 
796 void
797 iommu_unmap_msi(struct iommu_ctx *ctx)
798 {
799 	struct iommu_map_entry *entry;
800 	struct iommu_domain *domain;
801 
802 	domain = ctx->domain;
803 	entry = domain->msi_entry;
804 	if (entry == NULL)
805 		return;
806 
807 	domain->ops->unmap(domain, entry->start, entry->end -
808 	    entry->start, IOMMU_PGF_WAITOK);
809 
810 	IOMMU_DOMAIN_LOCK(domain);
811 	iommu_gas_free_space(domain, entry);
812 	IOMMU_DOMAIN_UNLOCK(domain);
813 
814 	iommu_gas_free_entry(domain, entry);
815 
816 	domain->msi_entry = NULL;
817 	domain->msi_base = 0;
818 	domain->msi_phys = 0;
819 }
820 
821 int
822 iommu_map_msi(struct iommu_ctx *ctx, iommu_gaddr_t size, int offset,
823     u_int eflags, u_int flags, vm_page_t *ma)
824 {
825 	struct iommu_domain *domain;
826 	struct iommu_map_entry *entry;
827 	int error;
828 
829 	error = 0;
830 	domain = ctx->domain;
831 
832 	/* Check if there is already an MSI page allocated */
833 	IOMMU_DOMAIN_LOCK(domain);
834 	entry = domain->msi_entry;
835 	IOMMU_DOMAIN_UNLOCK(domain);
836 
837 	if (entry == NULL) {
838 		error = iommu_gas_map(domain, &ctx->tag->common, size, offset,
839 		    eflags, flags, ma, &entry);
840 		IOMMU_DOMAIN_LOCK(domain);
841 		if (error == 0) {
842 			if (domain->msi_entry == NULL) {
843 				MPASS(domain->msi_base == 0);
844 				MPASS(domain->msi_phys == 0);
845 
846 				domain->msi_entry = entry;
847 				domain->msi_base = entry->start;
848 				domain->msi_phys = VM_PAGE_TO_PHYS(ma[0]);
849 			} else {
850 				/*
851 				 * We lost the race and already have an
852 				 * MSI page allocated. Free the unneeded entry.
853 				 */
854 				iommu_gas_free_entry(domain, entry);
855 			}
856 		} else if (domain->msi_entry != NULL) {
857 			/*
858 			 * The allocation failed, but another succeeded.
859 			 * Return success as there is a valid MSI page.
860 			 */
861 			error = 0;
862 		}
863 		IOMMU_DOMAIN_UNLOCK(domain);
864 	}
865 
866 	return (error);
867 }
868 
869 void
870 iommu_translate_msi(struct iommu_domain *domain, uint64_t *addr)
871 {
872 
873 	*addr = (*addr - domain->msi_phys) + domain->msi_base;
874 
875 	KASSERT(*addr >= domain->msi_entry->start,
876 	    ("%s: Address is below the MSI entry start address (%jx < %jx)",
877 	    __func__, (uintmax_t)*addr, (uintmax_t)domain->msi_entry->start));
878 
879 	KASSERT(*addr + sizeof(*addr) <= domain->msi_entry->end,
880 	    ("%s: Address is above the MSI entry end address (%jx < %jx)",
881 	    __func__, (uintmax_t)*addr, (uintmax_t)domain->msi_entry->end));
882 }
883 
884 SYSCTL_NODE(_hw, OID_AUTO, iommu, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, "");
885 
886 #ifdef INVARIANTS
887 SYSCTL_INT(_hw_iommu, OID_AUTO, check_free, CTLFLAG_RWTUN,
888     &iommu_check_free, 0,
889     "Check the GPA RBtree for free_down and free_after validity");
890 #endif
891