xref: /freebsd/sys/dev/iommu/iommu_gas.c (revision e7437ae907c89bf85a99c5cbb7ddd194a1ff1354)
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  * Addresses can be allocated only in the range [lbound, ubound). Try to
296  * allocate space in the free interval, subject to the conditions expressed by
297  * 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 lbound, iommu_gaddr_t ubound)
302 {
303 	struct iommu_map_entry *entry;
304 	iommu_gaddr_t first, size, start;
305 	bool found __diagused;
306 	int offset;
307 
308 	/*
309 	 * The prev->end is always aligned on the page size, which
310 	 * causes page alignment for the entry->start too.
311 	 *
312 	 * Create IOMMU_PAGE_SIZE gaps before, after new entry
313 	 * to ensure that out-of-bounds accesses fault.
314 	 */
315 	beg = MAX(beg + IOMMU_PAGE_SIZE, lbound);
316 	start = roundup2(beg, a->common->alignment);
317 	if (start < beg)
318 		return (false);
319 	end = MIN(end - IOMMU_PAGE_SIZE, ubound);
320 	offset = a->offset;
321 	size = a->size;
322 	if (start + offset + size > end)
323 		return (false);
324 
325 	/* Check for and try to skip past boundary crossing. */
326 	if (!vm_addr_bound_ok(start + offset, size, a->common->boundary)) {
327 		/*
328 		 * The start + offset to start + offset + size region crosses
329 		 * the boundary.  Check if there is enough space after the next
330 		 * boundary after the beg.
331 		 */
332 		first = start;
333 		beg = roundup2(start + offset + 1, a->common->boundary);
334 		start = roundup2(beg, a->common->alignment);
335 
336 		if (start + offset + size > end ||
337 		    !vm_addr_bound_ok(start + offset, size,
338 		    a->common->boundary)) {
339 			/*
340 			 * Not enough space to align at the requested boundary,
341 			 * or boundary is smaller than the size, but allowed to
342 			 * split.  We already checked that start + size does not
343 			 * overlap ubound.
344 			 *
345 			 * XXXKIB. It is possible that beg is exactly at the
346 			 * start of the next entry, then we do not have gap.
347 			 * Ignore for now.
348 			 */
349 			if ((a->gas_flags & IOMMU_MF_CANSPLIT) == 0)
350 				return (false);
351 			size = beg - first - offset;
352 			start = first;
353 		}
354 	}
355 	entry = a->entry;
356 	entry->start = start;
357 	entry->end = start + roundup2(size + offset, IOMMU_PAGE_SIZE);
358 	entry->flags = IOMMU_MAP_ENTRY_MAP;
359 	found = iommu_gas_rb_insert(a->domain, entry);
360 	KASSERT(found, ("found dup %p start %jx size %jx",
361 	    a->domain, (uintmax_t)start, (uintmax_t)size));
362 	return (true);
363 }
364 
365 /* Find the next entry that might abut a big-enough range. */
366 static struct iommu_map_entry *
367 iommu_gas_next(struct iommu_map_entry *curr, iommu_gaddr_t min_free)
368 {
369 	struct iommu_map_entry *next;
370 
371 	if ((next = RB_RIGHT(curr, rb_entry)) != NULL &&
372 	    next->free_down >= min_free) {
373 		/* Find next entry in right subtree. */
374 		do
375 			curr = next;
376 		while ((next = RB_LEFT(curr, rb_entry)) != NULL &&
377 		    next->free_down >= min_free);
378 	} else {
379 		/* Find next entry in a left-parent ancestor. */
380 		while ((next = RB_PARENT(curr, rb_entry)) != NULL &&
381 		    curr == RB_RIGHT(next, rb_entry))
382 			curr = next;
383 		curr = next;
384 	}
385 	return (curr);
386 }
387 
388 static int
389 iommu_gas_find_space(struct iommu_gas_match_args *a)
390 {
391 	struct iommu_domain *domain;
392 	struct iommu_map_entry *curr, *first;
393 	iommu_gaddr_t addr, min_free;
394 
395 	IOMMU_DOMAIN_ASSERT_LOCKED(a->domain);
396 	KASSERT(a->entry->flags == 0,
397 	    ("dirty entry %p %p", a->domain, a->entry));
398 
399 	/*
400 	 * If the subtree doesn't have free space for the requested allocation
401 	 * plus two guard pages, skip it.
402 	 */
403 	min_free = 2 * IOMMU_PAGE_SIZE +
404 	    roundup2(a->size + a->offset, IOMMU_PAGE_SIZE);
405 
406 	/*
407 	 * Find the first entry in the lower region that could abut a big-enough
408 	 * range.
409 	 */
410 	curr = RB_ROOT(&a->domain->rb_root);
411 	first = NULL;
412 	while (curr != NULL && curr->free_down >= min_free) {
413 		first = curr;
414 		curr = RB_LEFT(curr, rb_entry);
415 	}
416 
417 	/*
418 	 * Walk the big-enough ranges until one satisfies alignment
419 	 * requirements, or violates lowaddr address requirement.
420 	 */
421 	addr = a->common->lowaddr + 1;
422 	for (curr = first; curr != NULL;
423 	    curr = iommu_gas_next(curr, min_free)) {
424 		if ((first = RB_LEFT(curr, rb_entry)) != NULL &&
425 		    iommu_gas_match_one(a, first->last, curr->start,
426 		    0, addr))
427 			return (0);
428 		if (curr->end >= addr) {
429 			/* All remaining ranges >= addr */
430 			break;
431 		}
432 		if ((first = RB_RIGHT(curr, rb_entry)) != NULL &&
433 		    iommu_gas_match_one(a, curr->end, first->first,
434 		    0, addr))
435 			return (0);
436 	}
437 
438 	/*
439 	 * To resume the search at the start of the upper region, first climb to
440 	 * the nearest ancestor that spans highaddr.  Then find the last entry
441 	 * before highaddr that could abut a big-enough range.
442 	 */
443 	addr = a->common->highaddr;
444 	while (curr != NULL && curr->last < addr)
445 		curr = RB_PARENT(curr, rb_entry);
446 	first = NULL;
447 	while (curr != NULL && curr->free_down >= min_free) {
448 		if (addr < curr->end)
449 			curr = RB_LEFT(curr, rb_entry);
450 		else {
451 			first = curr;
452 			curr = RB_RIGHT(curr, rb_entry);
453 		}
454 	}
455 
456 	/*
457 	 * Walk the remaining big-enough ranges until one satisfies alignment
458 	 * requirements.
459 	 */
460 	domain = a->domain;
461 	for (curr = first; curr != NULL;
462 	    curr = iommu_gas_next(curr, min_free)) {
463 		if ((first = RB_LEFT(curr, rb_entry)) != NULL &&
464 		    iommu_gas_match_one(a, first->last, curr->start,
465 		    addr + 1, domain->end))
466 			return (0);
467 		if ((first = RB_RIGHT(curr, rb_entry)) != NULL &&
468 		    iommu_gas_match_one(a, curr->end, first->first,
469 		    addr + 1, domain->end))
470 			return (0);
471 	}
472 
473 	return (ENOMEM);
474 }
475 
476 static int
477 iommu_gas_alloc_region(struct iommu_domain *domain, struct iommu_map_entry *entry,
478     u_int flags)
479 {
480 	struct iommu_map_entry *next, *prev;
481 	bool found __diagused;
482 
483 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
484 
485 	if ((entry->start & IOMMU_PAGE_MASK) != 0 ||
486 	    (entry->end & IOMMU_PAGE_MASK) != 0)
487 		return (EINVAL);
488 	if (entry->start >= entry->end)
489 		return (EINVAL);
490 	if (entry->end >= domain->end)
491 		return (EINVAL);
492 
493 	next = RB_NFIND(iommu_gas_entries_tree, &domain->rb_root, entry);
494 	KASSERT(next != NULL, ("next must be non-null %p %jx", domain,
495 	    (uintmax_t)entry->start));
496 	prev = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, next);
497 	/* prev could be NULL */
498 
499 	/*
500 	 * Adapt to broken BIOSes which specify overlapping RMRR
501 	 * entries.
502 	 *
503 	 * XXXKIB: this does not handle a case when prev or next
504 	 * entries are completely covered by the current one, which
505 	 * extends both ways.
506 	 */
507 	if (prev != NULL && prev->end > entry->start &&
508 	    (prev->flags & IOMMU_MAP_ENTRY_PLACE) == 0) {
509 		if ((flags & IOMMU_MF_RMRR) == 0 ||
510 		    (prev->flags & IOMMU_MAP_ENTRY_RMRR) == 0)
511 			return (EBUSY);
512 		entry->start = prev->end;
513 	}
514 	if (next->start < entry->end &&
515 	    (next->flags & IOMMU_MAP_ENTRY_PLACE) == 0) {
516 		if ((flags & IOMMU_MF_RMRR) == 0 ||
517 		    (next->flags & IOMMU_MAP_ENTRY_RMRR) == 0)
518 			return (EBUSY);
519 		entry->end = next->start;
520 	}
521 	if (entry->end == entry->start)
522 		return (0);
523 
524 	if (prev != NULL && prev->end > entry->start) {
525 		/* This assumes that prev is the placeholder entry. */
526 		iommu_gas_rb_remove(domain, prev);
527 		prev = NULL;
528 	}
529 	if (next->start < entry->end) {
530 		iommu_gas_rb_remove(domain, next);
531 		next = NULL;
532 	}
533 
534 	found = iommu_gas_rb_insert(domain, entry);
535 	KASSERT(found, ("found RMRR dup %p start %jx end %jx",
536 	    domain, (uintmax_t)entry->start, (uintmax_t)entry->end));
537 	if ((flags & IOMMU_MF_RMRR) != 0)
538 		entry->flags = IOMMU_MAP_ENTRY_RMRR;
539 
540 #ifdef INVARIANTS
541 	struct iommu_map_entry *ip, *in;
542 	ip = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, entry);
543 	in = RB_NEXT(iommu_gas_entries_tree, &domain->rb_root, entry);
544 	KASSERT(prev == NULL || ip == prev,
545 	    ("RMRR %p (%jx %jx) prev %p (%jx %jx) ins prev %p (%jx %jx)",
546 	    entry, entry->start, entry->end, prev,
547 	    prev == NULL ? 0 : prev->start, prev == NULL ? 0 : prev->end,
548 	    ip, ip == NULL ? 0 : ip->start, ip == NULL ? 0 : ip->end));
549 	KASSERT(next == NULL || in == next,
550 	    ("RMRR %p (%jx %jx) next %p (%jx %jx) ins next %p (%jx %jx)",
551 	    entry, entry->start, entry->end, next,
552 	    next == NULL ? 0 : next->start, next == NULL ? 0 : next->end,
553 	    in, in == NULL ? 0 : in->start, in == NULL ? 0 : in->end));
554 #endif
555 
556 	return (0);
557 }
558 
559 void
560 iommu_gas_free_space(struct iommu_domain *domain, struct iommu_map_entry *entry)
561 {
562 
563 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
564 	KASSERT((entry->flags & (IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_RMRR |
565 	    IOMMU_MAP_ENTRY_MAP)) == IOMMU_MAP_ENTRY_MAP,
566 	    ("permanent entry %p %p", domain, entry));
567 
568 	iommu_gas_rb_remove(domain, entry);
569 	entry->flags &= ~IOMMU_MAP_ENTRY_MAP;
570 #ifdef INVARIANTS
571 	if (iommu_check_free)
572 		iommu_gas_check_free(domain);
573 #endif
574 }
575 
576 void
577 iommu_gas_free_region(struct iommu_domain *domain, struct iommu_map_entry *entry)
578 {
579 	struct iommu_map_entry *next, *prev;
580 
581 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
582 	KASSERT((entry->flags & (IOMMU_MAP_ENTRY_PLACE | IOMMU_MAP_ENTRY_RMRR |
583 	    IOMMU_MAP_ENTRY_MAP)) == IOMMU_MAP_ENTRY_RMRR,
584 	    ("non-RMRR entry %p %p", domain, entry));
585 
586 	prev = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, entry);
587 	next = RB_NEXT(iommu_gas_entries_tree, &domain->rb_root, entry);
588 	iommu_gas_rb_remove(domain, entry);
589 	entry->flags &= ~IOMMU_MAP_ENTRY_RMRR;
590 
591 	if (prev == NULL)
592 		iommu_gas_rb_insert(domain, domain->first_place);
593 	if (next == NULL)
594 		iommu_gas_rb_insert(domain, domain->last_place);
595 }
596 
597 int
598 iommu_gas_map(struct iommu_domain *domain,
599     const struct bus_dma_tag_common *common, iommu_gaddr_t size, int offset,
600     u_int eflags, u_int flags, vm_page_t *ma, struct iommu_map_entry **res)
601 {
602 	struct iommu_gas_match_args a;
603 	struct iommu_map_entry *entry;
604 	int error;
605 
606 	KASSERT((flags & ~(IOMMU_MF_CANWAIT | IOMMU_MF_CANSPLIT)) == 0,
607 	    ("invalid flags 0x%x", flags));
608 
609 	a.domain = domain;
610 	a.size = size;
611 	a.offset = offset;
612 	a.common = common;
613 	a.gas_flags = flags;
614 	entry = iommu_gas_alloc_entry(domain,
615 	    (flags & IOMMU_MF_CANWAIT) != 0 ? IOMMU_PGF_WAITOK : 0);
616 	if (entry == NULL)
617 		return (ENOMEM);
618 	a.entry = entry;
619 	IOMMU_DOMAIN_LOCK(domain);
620 	error = iommu_gas_find_space(&a);
621 	if (error == ENOMEM) {
622 		IOMMU_DOMAIN_UNLOCK(domain);
623 		iommu_gas_free_entry(domain, entry);
624 		return (error);
625 	}
626 #ifdef INVARIANTS
627 	if (iommu_check_free)
628 		iommu_gas_check_free(domain);
629 #endif
630 	KASSERT(error == 0,
631 	    ("unexpected error %d from iommu_gas_find_entry", error));
632 	KASSERT(entry->end < domain->end, ("allocated GPA %jx, max GPA %jx",
633 	    (uintmax_t)entry->end, (uintmax_t)domain->end));
634 	entry->flags |= eflags;
635 	IOMMU_DOMAIN_UNLOCK(domain);
636 
637 	error = domain->ops->map(domain, entry->start,
638 	    entry->end - entry->start, ma, eflags,
639 	    ((flags & IOMMU_MF_CANWAIT) != 0 ? IOMMU_PGF_WAITOK : 0));
640 	if (error == ENOMEM) {
641 		iommu_domain_unload_entry(entry, true,
642 		    (flags & IOMMU_MF_CANWAIT) != 0);
643 		return (error);
644 	}
645 	KASSERT(error == 0,
646 	    ("unexpected error %d from domain_map_buf", error));
647 
648 	*res = entry;
649 	return (0);
650 }
651 
652 int
653 iommu_gas_map_region(struct iommu_domain *domain, struct iommu_map_entry *entry,
654     u_int eflags, u_int flags, vm_page_t *ma)
655 {
656 	iommu_gaddr_t start;
657 	int error;
658 
659 	KASSERT(entry->flags == 0, ("used RMRR entry %p %p %x", domain,
660 	    entry, entry->flags));
661 	KASSERT((flags & ~(IOMMU_MF_CANWAIT | IOMMU_MF_RMRR)) == 0,
662 	    ("invalid flags 0x%x", flags));
663 
664 	start = entry->start;
665 	IOMMU_DOMAIN_LOCK(domain);
666 	error = iommu_gas_alloc_region(domain, entry, flags);
667 	if (error != 0) {
668 		IOMMU_DOMAIN_UNLOCK(domain);
669 		return (error);
670 	}
671 	entry->flags |= eflags;
672 	IOMMU_DOMAIN_UNLOCK(domain);
673 	if (entry->end == entry->start)
674 		return (0);
675 
676 	error = domain->ops->map(domain, entry->start,
677 	    entry->end - entry->start, ma + OFF_TO_IDX(start - entry->start),
678 	    eflags, ((flags & IOMMU_MF_CANWAIT) != 0 ? IOMMU_PGF_WAITOK : 0));
679 	if (error == ENOMEM) {
680 		iommu_domain_unload_entry(entry, false,
681 		    (flags & IOMMU_MF_CANWAIT) != 0);
682 		return (error);
683 	}
684 	KASSERT(error == 0,
685 	    ("unexpected error %d from domain_map_buf", error));
686 
687 	return (0);
688 }
689 
690 static int
691 iommu_gas_reserve_region_locked(struct iommu_domain *domain,
692     iommu_gaddr_t start, iommu_gaddr_t end, struct iommu_map_entry *entry)
693 {
694 	int error;
695 
696 	IOMMU_DOMAIN_ASSERT_LOCKED(domain);
697 
698 	entry->start = start;
699 	entry->end = end;
700 	error = iommu_gas_alloc_region(domain, entry, IOMMU_MF_CANWAIT);
701 	if (error == 0)
702 		entry->flags |= IOMMU_MAP_ENTRY_UNMAPPED;
703 	return (error);
704 }
705 
706 int
707 iommu_gas_reserve_region(struct iommu_domain *domain, iommu_gaddr_t start,
708     iommu_gaddr_t end, struct iommu_map_entry **entry0)
709 {
710 	struct iommu_map_entry *entry;
711 	int error;
712 
713 	entry = iommu_gas_alloc_entry(domain, IOMMU_PGF_WAITOK);
714 	IOMMU_DOMAIN_LOCK(domain);
715 	error = iommu_gas_reserve_region_locked(domain, start, end, entry);
716 	IOMMU_DOMAIN_UNLOCK(domain);
717 	if (error != 0)
718 		iommu_gas_free_entry(domain, entry);
719 	else if (entry0 != NULL)
720 		*entry0 = entry;
721 	return (error);
722 }
723 
724 /*
725  * As in iommu_gas_reserve_region, reserve [start, end), but allow for existing
726  * entries.
727  */
728 int
729 iommu_gas_reserve_region_extend(struct iommu_domain *domain,
730     iommu_gaddr_t start, iommu_gaddr_t end)
731 {
732 	struct iommu_map_entry *entry, *next, *prev, key = {};
733 	iommu_gaddr_t entry_start, entry_end;
734 	int error;
735 
736 	error = 0;
737 	entry = NULL;
738 	end = ummin(end, domain->end);
739 	while (start < end) {
740 		/* Preallocate an entry. */
741 		if (entry == NULL)
742 			entry = iommu_gas_alloc_entry(domain,
743 			    IOMMU_PGF_WAITOK);
744 		/* Calculate the free region from here to the next entry. */
745 		key.start = key.end = start;
746 		IOMMU_DOMAIN_LOCK(domain);
747 		next = RB_NFIND(iommu_gas_entries_tree, &domain->rb_root, &key);
748 		KASSERT(next != NULL, ("domain %p with end %#jx has no entry "
749 		    "after %#jx", domain, (uintmax_t)domain->end,
750 		    (uintmax_t)start));
751 		entry_end = ummin(end, next->start);
752 		prev = RB_PREV(iommu_gas_entries_tree, &domain->rb_root, next);
753 		if (prev != NULL)
754 			entry_start = ummax(start, prev->end);
755 		else
756 			entry_start = start;
757 		start = next->end;
758 		/* Reserve the region if non-empty. */
759 		if (entry_start != entry_end) {
760 			error = iommu_gas_reserve_region_locked(domain,
761 			    entry_start, entry_end, entry);
762 			if (error != 0) {
763 				IOMMU_DOMAIN_UNLOCK(domain);
764 				break;
765 			}
766 			entry = NULL;
767 		}
768 		IOMMU_DOMAIN_UNLOCK(domain);
769 	}
770 	/* Release a preallocated entry if it was not used. */
771 	if (entry != NULL)
772 		iommu_gas_free_entry(domain, entry);
773 	return (error);
774 }
775 
776 void
777 iommu_unmap_msi(struct iommu_ctx *ctx)
778 {
779 	struct iommu_map_entry *entry;
780 	struct iommu_domain *domain;
781 
782 	domain = ctx->domain;
783 	entry = domain->msi_entry;
784 	if (entry == NULL)
785 		return;
786 
787 	domain->ops->unmap(domain, entry->start, entry->end -
788 	    entry->start, IOMMU_PGF_WAITOK);
789 
790 	IOMMU_DOMAIN_LOCK(domain);
791 	iommu_gas_free_space(domain, entry);
792 	IOMMU_DOMAIN_UNLOCK(domain);
793 
794 	iommu_gas_free_entry(domain, entry);
795 
796 	domain->msi_entry = NULL;
797 	domain->msi_base = 0;
798 	domain->msi_phys = 0;
799 }
800 
801 int
802 iommu_map_msi(struct iommu_ctx *ctx, iommu_gaddr_t size, int offset,
803     u_int eflags, u_int flags, vm_page_t *ma)
804 {
805 	struct iommu_domain *domain;
806 	struct iommu_map_entry *entry;
807 	int error;
808 
809 	error = 0;
810 	domain = ctx->domain;
811 
812 	/* Check if there is already an MSI page allocated */
813 	IOMMU_DOMAIN_LOCK(domain);
814 	entry = domain->msi_entry;
815 	IOMMU_DOMAIN_UNLOCK(domain);
816 
817 	if (entry == NULL) {
818 		error = iommu_gas_map(domain, &ctx->tag->common, size, offset,
819 		    eflags, flags, ma, &entry);
820 		IOMMU_DOMAIN_LOCK(domain);
821 		if (error == 0) {
822 			if (domain->msi_entry == NULL) {
823 				MPASS(domain->msi_base == 0);
824 				MPASS(domain->msi_phys == 0);
825 
826 				domain->msi_entry = entry;
827 				domain->msi_base = entry->start;
828 				domain->msi_phys = VM_PAGE_TO_PHYS(ma[0]);
829 			} else {
830 				/*
831 				 * We lost the race and already have an
832 				 * MSI page allocated. Free the unneeded entry.
833 				 */
834 				iommu_gas_free_entry(domain, entry);
835 			}
836 		} else if (domain->msi_entry != NULL) {
837 			/*
838 			 * The allocation failed, but another succeeded.
839 			 * Return success as there is a valid MSI page.
840 			 */
841 			error = 0;
842 		}
843 		IOMMU_DOMAIN_UNLOCK(domain);
844 	}
845 
846 	return (error);
847 }
848 
849 void
850 iommu_translate_msi(struct iommu_domain *domain, uint64_t *addr)
851 {
852 
853 	*addr = (*addr - domain->msi_phys) + domain->msi_base;
854 
855 	KASSERT(*addr >= domain->msi_entry->start,
856 	    ("%s: Address is below the MSI entry start address (%jx < %jx)",
857 	    __func__, (uintmax_t)*addr, (uintmax_t)domain->msi_entry->start));
858 
859 	KASSERT(*addr + sizeof(*addr) <= domain->msi_entry->end,
860 	    ("%s: Address is above the MSI entry end address (%jx < %jx)",
861 	    __func__, (uintmax_t)*addr, (uintmax_t)domain->msi_entry->end));
862 }
863 
864 SYSCTL_NODE(_hw, OID_AUTO, iommu, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, "");
865 
866 #ifdef INVARIANTS
867 SYSCTL_INT(_hw_iommu, OID_AUTO, check_free, CTLFLAG_RWTUN,
868     &iommu_check_free, 0,
869     "Check the GPA RBtree for free_down and free_after validity");
870 #endif
871