xref: /freebsd/sys/x86/iommu/intel_drv.c (revision 8d20be1e22095c27faf8fe8b2f0d089739cc742e)
1 /*-
2  * Copyright (c) 2013 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Konstantin Belousov <kib@FreeBSD.org>
6  * under sponsorship from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_acpi.h"
34 #if defined(__amd64__) /* || defined(__ia64__) */
35 #define	DEV_APIC
36 #else
37 #include "opt_apic.h"
38 #endif
39 #include "opt_ddb.h"
40 
41 #include <sys/param.h>
42 #include <sys/bus.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/memdesc.h>
47 #include <sys/module.h>
48 #include <sys/rman.h>
49 #include <sys/rwlock.h>
50 #include <sys/smp.h>
51 #include <sys/taskqueue.h>
52 #include <sys/tree.h>
53 #include <machine/bus.h>
54 #include <contrib/dev/acpica/include/acpi.h>
55 #include <contrib/dev/acpica/include/accommon.h>
56 #include <dev/acpica/acpivar.h>
57 #include <vm/vm.h>
58 #include <vm/vm_extern.h>
59 #include <vm/vm_kern.h>
60 #include <vm/vm_object.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_pager.h>
63 #include <vm/vm_map.h>
64 #include <x86/include/busdma_impl.h>
65 #include <x86/iommu/intel_reg.h>
66 #include <x86/iommu/busdma_dmar.h>
67 #include <x86/iommu/intel_dmar.h>
68 #include <dev/pci/pcivar.h>
69 
70 #ifdef DEV_APIC
71 #include "pcib_if.h"
72 #endif
73 
74 #define	DMAR_REG_RID	1
75 #define	DMAR_IRQ_RID	0
76 
77 static devclass_t dmar_devclass;
78 static device_t *dmar_devs;
79 static int dmar_devcnt;
80 
81 typedef int (*dmar_iter_t)(ACPI_DMAR_HEADER *, void *);
82 
83 static void
84 dmar_iterate_tbl(dmar_iter_t iter, void *arg)
85 {
86 	ACPI_TABLE_DMAR *dmartbl;
87 	ACPI_DMAR_HEADER *dmarh;
88 	char *ptr, *ptrend;
89 	ACPI_STATUS status;
90 
91 	status = AcpiGetTable(ACPI_SIG_DMAR, 1, (ACPI_TABLE_HEADER **)&dmartbl);
92 	if (ACPI_FAILURE(status))
93 		return;
94 	ptr = (char *)dmartbl + sizeof(*dmartbl);
95 	ptrend = (char *)dmartbl + dmartbl->Header.Length;
96 	for (;;) {
97 		if (ptr >= ptrend)
98 			break;
99 		dmarh = (ACPI_DMAR_HEADER *)ptr;
100 		if (dmarh->Length <= 0) {
101 			printf("dmar_identify: corrupted DMAR table, l %d\n",
102 			    dmarh->Length);
103 			break;
104 		}
105 		ptr += dmarh->Length;
106 		if (!iter(dmarh, arg))
107 			break;
108 	}
109 }
110 
111 struct find_iter_args {
112 	int i;
113 	ACPI_DMAR_HARDWARE_UNIT *res;
114 };
115 
116 static int
117 dmar_find_iter(ACPI_DMAR_HEADER *dmarh, void *arg)
118 {
119 	struct find_iter_args *fia;
120 
121 	if (dmarh->Type != ACPI_DMAR_TYPE_HARDWARE_UNIT)
122 		return (1);
123 
124 	fia = arg;
125 	if (fia->i == 0) {
126 		fia->res = (ACPI_DMAR_HARDWARE_UNIT *)dmarh;
127 		return (0);
128 	}
129 	fia->i--;
130 	return (1);
131 }
132 
133 static ACPI_DMAR_HARDWARE_UNIT *
134 dmar_find_by_index(int idx)
135 {
136 	struct find_iter_args fia;
137 
138 	fia.i = idx;
139 	fia.res = NULL;
140 	dmar_iterate_tbl(dmar_find_iter, &fia);
141 	return (fia.res);
142 }
143 
144 static int
145 dmar_count_iter(ACPI_DMAR_HEADER *dmarh, void *arg)
146 {
147 
148 	if (dmarh->Type == ACPI_DMAR_TYPE_HARDWARE_UNIT)
149 		dmar_devcnt++;
150 	return (1);
151 }
152 
153 static int dmar_enable = 0;
154 static void
155 dmar_identify(driver_t *driver, device_t parent)
156 {
157 	ACPI_TABLE_DMAR *dmartbl;
158 	ACPI_DMAR_HARDWARE_UNIT *dmarh;
159 	ACPI_STATUS status;
160 	int i, error;
161 
162 	if (acpi_disabled("dmar"))
163 		return;
164 	TUNABLE_INT_FETCH("hw.dmar.enable", &dmar_enable);
165 	if (!dmar_enable)
166 		return;
167 #ifdef INVARIANTS
168 	TUNABLE_INT_FETCH("hw.dmar.check_free", &dmar_check_free);
169 #endif
170 	TUNABLE_INT_FETCH("hw.dmar.match_verbose", &dmar_match_verbose);
171 	status = AcpiGetTable(ACPI_SIG_DMAR, 1, (ACPI_TABLE_HEADER **)&dmartbl);
172 	if (ACPI_FAILURE(status))
173 		return;
174 	haw = dmartbl->Width + 1;
175 	if ((1ULL << (haw + 1)) > BUS_SPACE_MAXADDR)
176 		dmar_high = BUS_SPACE_MAXADDR;
177 	else
178 		dmar_high = 1ULL << (haw + 1);
179 	if (bootverbose) {
180 		printf("DMAR HAW=%d flags=<%b>\n", dmartbl->Width,
181 		    (unsigned)dmartbl->Flags,
182 		    "\020\001INTR_REMAP\002X2APIC_OPT_OUT");
183 	}
184 
185 	dmar_iterate_tbl(dmar_count_iter, NULL);
186 	if (dmar_devcnt == 0)
187 		return;
188 	dmar_devs = malloc(sizeof(device_t) * dmar_devcnt, M_DEVBUF,
189 	    M_WAITOK | M_ZERO);
190 	for (i = 0; i < dmar_devcnt; i++) {
191 		dmarh = dmar_find_by_index(i);
192 		if (dmarh == NULL) {
193 			printf("dmar_identify: cannot find HWUNIT %d\n", i);
194 			continue;
195 		}
196 		dmar_devs[i] = BUS_ADD_CHILD(parent, 1, "dmar", i);
197 		if (dmar_devs[i] == NULL) {
198 			printf("dmar_identify: cannot create instance %d\n", i);
199 			continue;
200 		}
201 		error = bus_set_resource(dmar_devs[i], SYS_RES_MEMORY,
202 		    DMAR_REG_RID, dmarh->Address, PAGE_SIZE);
203 		if (error != 0) {
204 			printf(
205 	"dmar%d: unable to alloc register window at 0x%08jx: error %d\n",
206 			    i, (uintmax_t)dmarh->Address, error);
207 			device_delete_child(parent, dmar_devs[i]);
208 			dmar_devs[i] = NULL;
209 		}
210 	}
211 }
212 
213 static int
214 dmar_probe(device_t dev)
215 {
216 
217 	if (acpi_get_handle(dev) != NULL)
218 		return (ENXIO);
219 	device_set_desc(dev, "DMA remap");
220 	return (0);
221 }
222 
223 static void
224 dmar_release_resources(device_t dev, struct dmar_unit *unit)
225 {
226 
227 	dmar_fini_busdma(unit);
228 	dmar_fini_fault_log(unit);
229 	if (unit->irq != -1) {
230 		bus_teardown_intr(dev, unit->irq_res, unit->intr_handle);
231 		bus_release_resource(dev, SYS_RES_IRQ, unit->irq_rid,
232 		    unit->irq_res);
233 		bus_delete_resource(dev, SYS_RES_IRQ, unit->irq_rid);
234 		PCIB_RELEASE_MSIX(device_get_parent(device_get_parent(dev)),
235 		    dev, unit->irq);
236 		unit->irq = -1;
237 	}
238 	if (unit->regs != NULL) {
239 		bus_deactivate_resource(dev, SYS_RES_MEMORY, unit->reg_rid,
240 		    unit->regs);
241 		bus_release_resource(dev, SYS_RES_MEMORY, unit->reg_rid,
242 		    unit->regs);
243 		unit->regs = NULL;
244 	}
245 	if (unit->domids != NULL) {
246 		delete_unrhdr(unit->domids);
247 		unit->domids = NULL;
248 	}
249 	if (unit->ctx_obj != NULL) {
250 		vm_object_deallocate(unit->ctx_obj);
251 		unit->ctx_obj = NULL;
252 	}
253 }
254 
255 static int
256 dmar_alloc_irq(device_t dev, struct dmar_unit *unit)
257 {
258 	device_t pcib;
259 	uint64_t msi_addr;
260 	uint32_t msi_data;
261 	int error;
262 
263 	pcib = device_get_parent(device_get_parent(dev)); /* Really not pcib */
264 	error = PCIB_ALLOC_MSIX(pcib, dev, &unit->irq);
265 	if (error != 0) {
266 		device_printf(dev, "cannot allocate fault interrupt, %d\n",
267 		    error);
268 		goto err1;
269 	}
270 	unit->irq_rid = DMAR_IRQ_RID;
271 	error = bus_set_resource(dev, SYS_RES_IRQ, unit->irq_rid, unit->irq,
272 	    1);
273 	if (error != 0) {
274 		device_printf(dev, "cannot set interrupt resource, %d\n",
275 		    error);
276 		goto err2;
277 	}
278 	unit->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ,
279 	    &unit->irq_rid, RF_ACTIVE);
280 	if (unit->irq_res == NULL) {
281 		device_printf(dev, "cannot map fault interrupt\n");
282 		error = ENXIO;
283 		goto err3;
284 	}
285 	error = bus_setup_intr(dev, unit->irq_res, INTR_TYPE_MISC,
286 	    dmar_intr, NULL, unit, &unit->intr_handle);
287 	if (error != 0) {
288 		device_printf(dev, "cannot setup fault interrupt, %d\n", error);
289 		goto err4;
290 	}
291 	bus_describe_intr(dev, unit->irq_res, unit->intr_handle, "fault");
292 	error = PCIB_MAP_MSI(pcib, dev, unit->irq, &msi_addr, &msi_data);
293 	if (error != 0) {
294 		device_printf(dev, "cannot map interrupt, %d\n", error);
295 		goto err5;
296 	}
297 	dmar_write4(unit, DMAR_FEDATA_REG, msi_data);
298 	dmar_write4(unit, DMAR_FEADDR_REG, msi_addr);
299 	/* Only for xAPIC mode */
300 	dmar_write4(unit, DMAR_FEUADDR_REG, msi_addr >> 32);
301 	return (0);
302 
303 err5:
304 	bus_teardown_intr(dev, unit->irq_res, unit->intr_handle);
305 err4:
306 	bus_release_resource(dev, SYS_RES_IRQ, unit->irq_rid, unit->irq_res);
307 err3:
308 	bus_delete_resource(dev, SYS_RES_IRQ, unit->irq_rid);
309 err2:
310 	PCIB_RELEASE_MSIX(pcib, dev, unit->irq);
311 	unit->irq = -1;
312 err1:
313 	return (error);
314 }
315 
316 #ifdef DEV_APIC
317 static int
318 dmar_remap_intr(device_t dev, device_t child, u_int irq)
319 {
320 	struct dmar_unit *unit;
321 	uint64_t msi_addr;
322 	uint32_t msi_data;
323 	int error;
324 
325 	unit = device_get_softc(dev);
326 	if (irq != unit->irq)
327 		return (ENOENT);
328 	error = PCIB_MAP_MSI(device_get_parent(device_get_parent(dev)), dev,
329 	    irq, &msi_addr, &msi_data);
330 	if (error != 0)
331 		return (error);
332 	dmar_disable_intr(unit);
333 	dmar_write4(unit, DMAR_FEDATA_REG, msi_data);
334 	dmar_write4(unit, DMAR_FEADDR_REG, msi_addr);
335 	dmar_write4(unit, DMAR_FEUADDR_REG, msi_addr >> 32);
336 	dmar_enable_intr(unit);
337 	return (0);
338 }
339 #endif
340 
341 static void
342 dmar_print_caps(device_t dev, struct dmar_unit *unit,
343     ACPI_DMAR_HARDWARE_UNIT *dmaru)
344 {
345 	uint32_t caphi, ecaphi;
346 
347 	device_printf(dev, "regs@0x%08jx, ver=%d.%d, seg=%d, flags=<%b>\n",
348 	    (uintmax_t)dmaru->Address, DMAR_MAJOR_VER(unit->hw_ver),
349 	    DMAR_MINOR_VER(unit->hw_ver), dmaru->Segment,
350 	    dmaru->Flags, "\020\001INCLUDE_ALL_PCI");
351 	caphi = unit->hw_cap >> 32;
352 	device_printf(dev, "cap=%b,", (u_int)unit->hw_cap,
353 	    "\020\004AFL\005WBF\006PLMR\007PHMR\010CM\027ZLR\030ISOCH");
354 	printf("%b, ", caphi, "\020\010PSI\027DWD\030DRD");
355 	printf("ndoms=%d, sagaw=%d, mgaw=%d, fro=%d, nfr=%d, superp=%d",
356 	    DMAR_CAP_ND(unit->hw_cap), DMAR_CAP_SAGAW(unit->hw_cap),
357 	    DMAR_CAP_MGAW(unit->hw_cap), DMAR_CAP_FRO(unit->hw_cap),
358 	    DMAR_CAP_NFR(unit->hw_cap), DMAR_CAP_SPS(unit->hw_cap));
359 	if ((unit->hw_cap & DMAR_CAP_PSI) != 0)
360 		printf(", mamv=%d", DMAR_CAP_MAMV(unit->hw_cap));
361 	printf("\n");
362 	ecaphi = unit->hw_ecap >> 32;
363 	device_printf(dev, "ecap=%b,", (u_int)unit->hw_ecap,
364 	    "\020\001C\002QI\003DI\004IR\005EIM\007PT\010SC");
365 	printf("%b, ", ecaphi, "\020");
366 	printf("mhmw=%d, iro=%d\n", DMAR_ECAP_MHMV(unit->hw_ecap),
367 	    DMAR_ECAP_IRO(unit->hw_ecap));
368 }
369 
370 static int
371 dmar_attach(device_t dev)
372 {
373 	struct dmar_unit *unit;
374 	ACPI_DMAR_HARDWARE_UNIT *dmaru;
375 	int error;
376 
377 	unit = device_get_softc(dev);
378 	unit->dev = dev;
379 	unit->unit = device_get_unit(dev);
380 	dmaru = dmar_find_by_index(unit->unit);
381 	if (dmaru == NULL)
382 		return (EINVAL);
383 	unit->irq = -1;
384 	unit->segment = dmaru->Segment;
385 	unit->base = dmaru->Address;
386 	unit->reg_rid = DMAR_REG_RID;
387 	unit->regs = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
388 	    &unit->reg_rid, RF_ACTIVE);
389 	if (unit->regs == NULL) {
390 		device_printf(dev, "cannot allocate register window\n");
391 		return (ENOMEM);
392 	}
393 	unit->hw_ver = dmar_read4(unit, DMAR_VER_REG);
394 	unit->hw_cap = dmar_read8(unit, DMAR_CAP_REG);
395 	unit->hw_ecap = dmar_read8(unit, DMAR_ECAP_REG);
396 	if (bootverbose)
397 		dmar_print_caps(dev, unit, dmaru);
398 	dmar_quirks_post_ident(unit);
399 
400 	error = dmar_alloc_irq(dev, unit);
401 	if (error != 0) {
402 		dmar_release_resources(dev, unit);
403 		return (error);
404 	}
405 	mtx_init(&unit->lock, "dmarhw", NULL, MTX_DEF);
406 	unit->domids = new_unrhdr(0, dmar_nd2mask(DMAR_CAP_ND(unit->hw_cap)),
407 	    &unit->lock);
408 
409 	/*
410 	 * 9.2 "Context Entry":
411 	 * When Caching Mode (CM) field is reported as Set, the
412 	 * domain-id value of zero is architecturally reserved.
413 	 * Software must not use domain-id value of zero
414 	 * when CM is Set.
415 	 */
416 	if ((unit->hw_cap & DMAR_CAP_CM) != 0)
417 		alloc_unr_specific(unit->domids, 0);
418 
419 	unit->ctx_obj = vm_pager_allocate(OBJT_PHYS, NULL, IDX_TO_OFF(1 +
420 	    DMAR_CTX_CNT), 0, 0, NULL);
421 
422 	/*
423 	 * Allocate and load the root entry table pointer.  Enable the
424 	 * address translation after the required invalidations are
425 	 * done.
426 	 */
427 	dmar_pgalloc(unit->ctx_obj, 0, DMAR_PGF_WAITOK | DMAR_PGF_ZERO);
428 	DMAR_LOCK(unit);
429 	error = dmar_load_root_entry_ptr(unit);
430 	if (error != 0) {
431 		DMAR_UNLOCK(unit);
432 		dmar_release_resources(dev, unit);
433 		return (error);
434 	}
435 	error = dmar_inv_ctx_glob(unit);
436 	if (error != 0) {
437 		DMAR_UNLOCK(unit);
438 		dmar_release_resources(dev, unit);
439 		return (error);
440 	}
441 	if ((unit->hw_ecap & DMAR_ECAP_DI) != 0) {
442 		error = dmar_inv_iotlb_glob(unit);
443 		if (error != 0) {
444 			DMAR_UNLOCK(unit);
445 			dmar_release_resources(dev, unit);
446 			return (error);
447 		}
448 	}
449 
450 	DMAR_UNLOCK(unit);
451 	error = dmar_init_fault_log(unit);
452 	if (error != 0) {
453 		dmar_release_resources(dev, unit);
454 		return (error);
455 	}
456 	error = dmar_init_busdma(unit);
457 	if (error != 0) {
458 		dmar_release_resources(dev, unit);
459 		return (error);
460 	}
461 
462 #ifdef NOTYET
463 	DMAR_LOCK(unit);
464 	error = dmar_enable_translation(unit);
465 	if (error != 0) {
466 		DMAR_UNLOCK(unit);
467 		dmar_release_resources(dev, unit);
468 		return (error);
469 	}
470 	DMAR_UNLOCK(unit);
471 #endif
472 
473 	return (0);
474 }
475 
476 static int
477 dmar_detach(device_t dev)
478 {
479 
480 	return (EBUSY);
481 }
482 
483 static int
484 dmar_suspend(device_t dev)
485 {
486 
487 	return (0);
488 }
489 
490 static int
491 dmar_resume(device_t dev)
492 {
493 
494 	/* XXXKIB */
495 	return (0);
496 }
497 
498 static device_method_t dmar_methods[] = {
499 	DEVMETHOD(device_identify, dmar_identify),
500 	DEVMETHOD(device_probe, dmar_probe),
501 	DEVMETHOD(device_attach, dmar_attach),
502 	DEVMETHOD(device_detach, dmar_detach),
503 	DEVMETHOD(device_suspend, dmar_suspend),
504 	DEVMETHOD(device_resume, dmar_resume),
505 #ifdef DEV_APIC
506 	DEVMETHOD(bus_remap_intr, dmar_remap_intr),
507 #endif
508 	DEVMETHOD_END
509 };
510 
511 static driver_t	dmar_driver = {
512 	"dmar",
513 	dmar_methods,
514 	sizeof(struct dmar_unit),
515 };
516 
517 DRIVER_MODULE(dmar, acpi, dmar_driver, dmar_devclass, 0, 0);
518 MODULE_DEPEND(dmar, acpi, 1, 1, 1);
519 
520 static void
521 dmar_print_path(device_t dev, const char *banner, int busno, int depth,
522     const ACPI_DMAR_PCI_PATH *path)
523 {
524 	int i;
525 
526 	device_printf(dev, "%s [%d, ", banner, busno);
527 	for (i = 0; i < depth; i++) {
528 		if (i != 0)
529 			printf(", ");
530 		printf("(%d, %d)", path[i].Device, path[i].Function);
531 	}
532 	printf("]\n");
533 }
534 
535 static int
536 dmar_dev_depth(device_t child)
537 {
538 	devclass_t pci_class;
539 	device_t bus, pcib;
540 	int depth;
541 
542 	pci_class = devclass_find("pci");
543 	for (depth = 1; ; depth++) {
544 		bus = device_get_parent(child);
545 		pcib = device_get_parent(bus);
546 		if (device_get_devclass(device_get_parent(pcib)) !=
547 		    pci_class)
548 			return (depth);
549 		child = pcib;
550 	}
551 }
552 
553 static void
554 dmar_dev_path(device_t child, int *busno, ACPI_DMAR_PCI_PATH *path, int depth)
555 {
556 	devclass_t pci_class;
557 	device_t bus, pcib;
558 
559 	pci_class = devclass_find("pci");
560 	for (depth--; depth != -1; depth--) {
561 		path[depth].Device = pci_get_slot(child);
562 		path[depth].Function = pci_get_function(child);
563 		bus = device_get_parent(child);
564 		pcib = device_get_parent(bus);
565 		if (device_get_devclass(device_get_parent(pcib)) !=
566 		    pci_class) {
567 			/* reached a host bridge */
568 			*busno = pcib_get_bus(bus);
569 			return;
570 		}
571 		child = pcib;
572 	}
573 	panic("wrong depth");
574 }
575 
576 static int
577 dmar_match_pathes(int busno1, const ACPI_DMAR_PCI_PATH *path1, int depth1,
578     int busno2, const ACPI_DMAR_PCI_PATH *path2, int depth2,
579     enum AcpiDmarScopeType scope_type)
580 {
581 	int i, depth;
582 
583 	if (busno1 != busno2)
584 		return (0);
585 	if (scope_type == ACPI_DMAR_SCOPE_TYPE_ENDPOINT && depth1 != depth2)
586 		return (0);
587 	depth = depth1;
588 	if (depth2 < depth)
589 		depth = depth2;
590 	for (i = 0; i < depth; i++) {
591 		if (path1[i].Device != path2[i].Device ||
592 		    path1[i].Function != path2[i].Function)
593 			return (0);
594 	}
595 	return (1);
596 }
597 
598 static int
599 dmar_match_devscope(ACPI_DMAR_DEVICE_SCOPE *devscope, device_t dev,
600     int dev_busno, const ACPI_DMAR_PCI_PATH *dev_path, int dev_path_len)
601 {
602 	ACPI_DMAR_PCI_PATH *path;
603 	int path_len;
604 
605 	if (devscope->Length < sizeof(*devscope)) {
606 		printf("dmar_find: corrupted DMAR table, dl %d\n",
607 		    devscope->Length);
608 		return (-1);
609 	}
610 	if (devscope->EntryType != ACPI_DMAR_SCOPE_TYPE_ENDPOINT &&
611 	    devscope->EntryType != ACPI_DMAR_SCOPE_TYPE_BRIDGE)
612 		return (0);
613 	path_len = devscope->Length - sizeof(*devscope);
614 	if (path_len % 2 != 0) {
615 		printf("dmar_find_bsf: corrupted DMAR table, dl %d\n",
616 		    devscope->Length);
617 		return (-1);
618 	}
619 	path_len /= 2;
620 	path = (ACPI_DMAR_PCI_PATH *)(devscope + 1);
621 	if (path_len == 0) {
622 		printf("dmar_find: corrupted DMAR table, dl %d\n",
623 		    devscope->Length);
624 		return (-1);
625 	}
626 	if (dmar_match_verbose)
627 		dmar_print_path(dev, "DMAR", devscope->Bus, path_len, path);
628 
629 	return (dmar_match_pathes(devscope->Bus, path, path_len, dev_busno,
630 	    dev_path, dev_path_len, devscope->EntryType));
631 }
632 
633 struct dmar_unit *
634 dmar_find(device_t dev)
635 {
636 	device_t dmar_dev;
637 	ACPI_DMAR_HARDWARE_UNIT *dmarh;
638 	ACPI_DMAR_DEVICE_SCOPE *devscope;
639 	char *ptr, *ptrend;
640 	int i, match, dev_domain, dev_busno, dev_path_len;
641 
642 	dmar_dev = NULL;
643 	dev_domain = pci_get_domain(dev);
644 	dev_path_len = dmar_dev_depth(dev);
645 	ACPI_DMAR_PCI_PATH dev_path[dev_path_len];
646 	dmar_dev_path(dev, &dev_busno, dev_path, dev_path_len);
647 	if (dmar_match_verbose)
648 		dmar_print_path(dev, "PCI", dev_busno, dev_path_len, dev_path);
649 
650 	for (i = 0; i < dmar_devcnt; i++) {
651 		if (dmar_devs[i] == NULL)
652 			continue;
653 		dmarh = dmar_find_by_index(i);
654 		if (dmarh == NULL)
655 			continue;
656 		if (dmarh->Segment != dev_domain)
657 			continue;
658 		if ((dmarh->Flags & ACPI_DMAR_INCLUDE_ALL) != 0) {
659 			dmar_dev = dmar_devs[i];
660 			if (dmar_match_verbose) {
661 				device_printf(dev,
662 				    "pci%d:%d:%d:%d matched dmar%d INCLUDE_ALL\n",
663 				    dev_domain, pci_get_bus(dev),
664 				    pci_get_slot(dev),
665 				    pci_get_function(dev),
666 				    ((struct dmar_unit *)device_get_softc(
667 				    dmar_dev))->unit);
668 			}
669 			goto found;
670 		}
671 		ptr = (char *)dmarh + sizeof(*dmarh);
672 		ptrend = (char *)dmarh + dmarh->Header.Length;
673 		for (;;) {
674 			if (ptr >= ptrend)
675 				break;
676 			devscope = (ACPI_DMAR_DEVICE_SCOPE *)ptr;
677 			ptr += devscope->Length;
678 			if (dmar_match_verbose) {
679 				device_printf(dev,
680 				    "pci%d:%d:%d:%d matching dmar%d\n",
681 				    dev_domain, pci_get_bus(dev),
682 				    pci_get_slot(dev),
683 				    pci_get_function(dev),
684 				    ((struct dmar_unit *)device_get_softc(
685 				    dmar_devs[i]))->unit);
686 			}
687 			match = dmar_match_devscope(devscope, dev, dev_busno,
688 			    dev_path, dev_path_len);
689 			if (dmar_match_verbose) {
690 				if (match == -1)
691 					printf("table error\n");
692 				else if (match == 0)
693 					printf("not matched\n");
694 				else
695 					printf("matched\n");
696 			}
697 			if (match == -1)
698 				return (NULL);
699 			else if (match == 1) {
700 				dmar_dev = dmar_devs[i];
701 				goto found;
702 			}
703 		}
704 	}
705 	return (NULL);
706 found:
707 	return (device_get_softc(dmar_dev));
708 }
709 
710 struct rmrr_iter_args {
711 	struct dmar_ctx *ctx;
712 	device_t dev;
713 	int dev_domain;
714 	int dev_busno;
715 	ACPI_DMAR_PCI_PATH *dev_path;
716 	int dev_path_len;
717 	struct dmar_map_entries_tailq *rmrr_entries;
718 };
719 
720 static int
721 dmar_rmrr_iter(ACPI_DMAR_HEADER *dmarh, void *arg)
722 {
723 	struct rmrr_iter_args *ria;
724 	ACPI_DMAR_RESERVED_MEMORY *resmem;
725 	ACPI_DMAR_DEVICE_SCOPE *devscope;
726 	struct dmar_map_entry *entry;
727 	char *ptr, *ptrend;
728 	int match;
729 
730 	if (dmarh->Type != ACPI_DMAR_TYPE_RESERVED_MEMORY)
731 		return (1);
732 
733 	ria = arg;
734 	resmem = (ACPI_DMAR_RESERVED_MEMORY *)dmarh;
735 	if (dmar_match_verbose) {
736 		printf("RMRR [%jx,%jx] segment %d\n",
737 		    (uintmax_t)resmem->BaseAddress,
738 		    (uintmax_t)resmem->EndAddress,
739 		    resmem->Segment);
740 	}
741 	if (resmem->Segment != ria->dev_domain)
742 		return (1);
743 
744 	ptr = (char *)resmem + sizeof(*resmem);
745 	ptrend = (char *)resmem + resmem->Header.Length;
746 	for (;;) {
747 		if (ptr >= ptrend)
748 			break;
749 		devscope = (ACPI_DMAR_DEVICE_SCOPE *)ptr;
750 		ptr += devscope->Length;
751 		match = dmar_match_devscope(devscope, ria->dev, ria->dev_busno,
752 		    ria->dev_path, ria->dev_path_len);
753 		if (match == 1) {
754 			if (dmar_match_verbose)
755 				printf("matched\n");
756 			entry = dmar_gas_alloc_entry(ria->ctx, DMAR_PGF_WAITOK);
757 			entry->start = resmem->BaseAddress;
758 			/* The RMRR entry end address is inclusive. */
759 			entry->end = resmem->EndAddress;
760 			TAILQ_INSERT_TAIL(ria->rmrr_entries, entry,
761 			    unroll_link);
762 		} else if (dmar_match_verbose) {
763 			printf("not matched, err %d\n", match);
764 		}
765 	}
766 
767 	return (1);
768 }
769 
770 void
771 dmar_ctx_parse_rmrr(struct dmar_ctx *ctx, device_t dev,
772     struct dmar_map_entries_tailq *rmrr_entries)
773 {
774 	struct rmrr_iter_args ria;
775 
776 	ria.dev_domain = pci_get_domain(dev);
777 	ria.dev_path_len = dmar_dev_depth(dev);
778 	ACPI_DMAR_PCI_PATH dev_path[ria.dev_path_len];
779 	dmar_dev_path(dev, &ria.dev_busno, dev_path, ria.dev_path_len);
780 
781 	if (dmar_match_verbose) {
782 		device_printf(dev, "parsing RMRR entries for ");
783 		dmar_print_path(dev, "PCI", ria.dev_busno, ria.dev_path_len,
784 		    dev_path);
785 	}
786 
787 	ria.ctx = ctx;
788 	ria.dev = dev;
789 	ria.dev_path = dev_path;
790 	ria.rmrr_entries = rmrr_entries;
791 	dmar_iterate_tbl(dmar_rmrr_iter, &ria);
792 }
793 
794 struct inst_rmrr_iter_args {
795 	struct dmar_unit *dmar;
796 };
797 
798 static device_t
799 dmar_path_dev(int segment, int path_len, int busno,
800     const ACPI_DMAR_PCI_PATH *path)
801 {
802 	devclass_t pci_class;
803 	device_t bus, pcib, dev;
804 	int i;
805 
806 	pci_class = devclass_find("pci");
807 	dev = NULL;
808 	for (i = 0; i < path_len; i++, path++) {
809 		dev = pci_find_dbsf(segment, busno, path->Device,
810 		    path->Function);
811 		if (dev == NULL)
812 			break;
813 		if (i != path_len - 1) {
814 			bus = device_get_parent(dev);
815 			pcib = device_get_parent(bus);
816 			if (device_get_devclass(device_get_parent(pcib)) !=
817 			    pci_class)
818 				return (NULL);
819 		}
820 		busno = pcib_get_bus(dev);
821 	}
822 	return (dev);
823 }
824 
825 static int
826 dmar_inst_rmrr_iter(ACPI_DMAR_HEADER *dmarh, void *arg)
827 {
828 	const ACPI_DMAR_RESERVED_MEMORY *resmem;
829 	const ACPI_DMAR_DEVICE_SCOPE *devscope;
830 	struct inst_rmrr_iter_args *iria;
831 	const char *ptr, *ptrend;
832 	struct dmar_unit *dev_dmar;
833 	device_t dev;
834 
835 	if (dmarh->Type != ACPI_DMAR_TYPE_RESERVED_MEMORY)
836 		return (1);
837 
838 	iria = arg;
839 	resmem = (ACPI_DMAR_RESERVED_MEMORY *)dmarh;
840 	if (resmem->Segment != iria->dmar->segment)
841 		return (1);
842 	if (dmar_match_verbose) {
843 		printf("dmar%d: RMRR [%jx,%jx]\n", iria->dmar->unit,
844 		    (uintmax_t)resmem->BaseAddress,
845 		    (uintmax_t)resmem->EndAddress);
846 	}
847 
848 	ptr = (char *)resmem + sizeof(*resmem);
849 	ptrend = (char *)resmem + resmem->Header.Length;
850 	for (;;) {
851 		if (ptr >= ptrend)
852 			break;
853 		devscope = (ACPI_DMAR_DEVICE_SCOPE *)ptr;
854 		ptr += devscope->Length;
855 		/* XXXKIB bridge */
856 		if (devscope->EntryType != ACPI_DMAR_SCOPE_TYPE_ENDPOINT)
857 			continue;
858 		if (dmar_match_verbose) {
859 			dmar_print_path(iria->dmar->dev, "RMRR scope",
860 			    devscope->Bus, (devscope->Length -
861 			    sizeof(ACPI_DMAR_DEVICE_SCOPE)) / 2,
862 			    (ACPI_DMAR_PCI_PATH *)(devscope + 1));
863 		}
864 		dev = dmar_path_dev(resmem->Segment, (devscope->Length -
865 		    sizeof(ACPI_DMAR_DEVICE_SCOPE)) / 2, devscope->Bus,
866 		    (ACPI_DMAR_PCI_PATH *)(devscope + 1));
867 		if (dev == NULL) {
868 			if (dmar_match_verbose)
869 				printf("null dev\n");
870 			continue;
871 		}
872 		dev_dmar = dmar_find(dev);
873 		if (dev_dmar != iria->dmar) {
874 			if (dmar_match_verbose) {
875 				printf("dmar%d matched, skipping\n",
876 				    dev_dmar->unit);
877 			}
878 			continue;
879 		}
880 		if (dmar_match_verbose)
881 			printf("matched, instantiating RMRR context\n");
882 		dmar_instantiate_ctx(iria->dmar, dev, true);
883 	}
884 
885 	return (1);
886 
887 }
888 
889 /*
890  * Pre-create all contexts for the DMAR which have RMRR entries.
891  */
892 int
893 dmar_instantiate_rmrr_ctxs(struct dmar_unit *dmar)
894 {
895 	struct inst_rmrr_iter_args iria;
896 	int error;
897 
898 	if (!dmar_barrier_enter(dmar, DMAR_BARRIER_RMRR))
899 		return (0);
900 
901 	error = 0;
902 	iria.dmar = dmar;
903 	if (dmar_match_verbose)
904 		printf("dmar%d: instantiating RMRR contexts\n", dmar->unit);
905 	dmar_iterate_tbl(dmar_inst_rmrr_iter, &iria);
906 	DMAR_LOCK(dmar);
907 	if (!LIST_EMPTY(&dmar->contexts)) {
908 		KASSERT((dmar->hw_gcmd & DMAR_GCMD_TE) == 0,
909 	    ("dmar%d: RMRR not handled but translation is already enabled",
910 		    dmar->unit));
911 		error = dmar_enable_translation(dmar);
912 	}
913 	dmar_barrier_exit(dmar, DMAR_BARRIER_RMRR);
914 	return (error);
915 }
916 
917 #ifdef DDB
918 #include <ddb/ddb.h>
919 #include <ddb/db_lex.h>
920 
921 static void
922 dmar_print_ctx_entry(const struct dmar_map_entry *entry)
923 {
924 	struct dmar_map_entry *l, *r;
925 
926 	db_printf(
927 	    "    start %jx end %jx free_after %jx free_down %jx flags %x ",
928 	    entry->start, entry->end, entry->free_after, entry->free_down,
929 	    entry->flags);
930 	db_printf("left ");
931 	l = RB_LEFT(entry, rb_entry);
932 	if (l == NULL)
933 		db_printf("NULL ");
934 	else
935 		db_printf("%jx ", l->start);
936 	db_printf("right ");
937 	r = RB_RIGHT(entry, rb_entry);
938 	if (r == NULL)
939 		db_printf("NULL");
940 	else
941 		db_printf("%jx", r->start);
942 	db_printf("\n");
943 }
944 
945 static void
946 dmar_print_ctx(struct dmar_ctx *ctx, bool show_mappings)
947 {
948 	struct dmar_map_entry *entry;
949 
950 	db_printf(
951 	    "  @%p pci%d:%d:%d dom %d mgaw %d agaw %d pglvl %d end %jx\n"
952 	    "    refs %d flags %x pgobj %p map_ents %u loads %lu unloads %lu\n",
953 	    ctx, ctx->bus, ctx->slot, ctx->func, ctx->domain, ctx->mgaw,
954 	    ctx->agaw, ctx->pglvl, (uintmax_t)ctx->end, ctx->refs,
955 	    ctx->flags, ctx->pgtbl_obj, ctx->entries_cnt, ctx->loads,
956 	    ctx->unloads);
957 	if (!show_mappings)
958 		return;
959 	db_printf("    mapped:\n");
960 	RB_FOREACH(entry, dmar_gas_entries_tree, &ctx->rb_root) {
961 		dmar_print_ctx_entry(entry);
962 		if (db_pager_quit)
963 			break;
964 	}
965 	if (db_pager_quit)
966 		return;
967 	db_printf("    unloading:\n");
968 	TAILQ_FOREACH(entry, &ctx->unload_entries, dmamap_link) {
969 		dmar_print_ctx_entry(entry);
970 		if (db_pager_quit)
971 			break;
972 	}
973 }
974 
975 DB_FUNC(dmar_ctx, db_dmar_print_ctx, db_show_table, CS_OWN, NULL)
976 {
977 	struct dmar_unit *unit;
978 	struct dmar_ctx *ctx;
979 	bool show_mappings, valid;
980 	int domain, bus, device, function, i, t;
981 	db_expr_t radix;
982 
983 	valid = false;
984 	radix = db_radix;
985 	db_radix = 10;
986 	t = db_read_token();
987 	if (t == tSLASH) {
988 		t = db_read_token();
989 		if (t != tIDENT) {
990 			db_printf("Bad modifier\n");
991 			db_radix = radix;
992 			db_skip_to_eol();
993 			return;
994 		}
995 		show_mappings = strchr(db_tok_string, 'm') != NULL;
996 		t = db_read_token();
997 	}
998 	if (t == tNUMBER) {
999 		domain = db_tok_number;
1000 		t = db_read_token();
1001 		if (t == tNUMBER) {
1002 			bus = db_tok_number;
1003 			t = db_read_token();
1004 			if (t == tNUMBER) {
1005 				device = db_tok_number;
1006 				t = db_read_token();
1007 				if (t == tNUMBER) {
1008 					function = db_tok_number;
1009 					valid = true;
1010 				}
1011 			}
1012 		}
1013 	}
1014 			db_radix = radix;
1015 	db_skip_to_eol();
1016 	if (!valid) {
1017 		db_printf("usage: show dmar_ctx [/m] "
1018 		    "<domain> <bus> <device> <func>\n");
1019 		return;
1020 	}
1021 	for (i = 0; i < dmar_devcnt; i++) {
1022 		unit = device_get_softc(dmar_devs[i]);
1023 		LIST_FOREACH(ctx, &unit->contexts, link) {
1024 			if (domain == unit->segment && bus == ctx->bus &&
1025 			    device == ctx->slot && function == ctx->func) {
1026 				dmar_print_ctx(ctx, show_mappings);
1027 				goto out;
1028 			}
1029 		}
1030 	}
1031 out:;
1032 }
1033 
1034 static void
1035 dmar_print_one(int idx, bool show_ctxs, bool show_mappings)
1036 {
1037 	struct dmar_unit *unit;
1038 	struct dmar_ctx *ctx;
1039 	int i, frir;
1040 
1041 	unit = device_get_softc(dmar_devs[idx]);
1042 	db_printf("dmar%d at %p, root at 0x%jx, ver 0x%x\n", unit->unit, unit,
1043 	    dmar_read8(unit, DMAR_RTADDR_REG), dmar_read4(unit, DMAR_VER_REG));
1044 	db_printf("cap 0x%jx ecap 0x%jx gsts 0x%x fsts 0x%x fectl 0x%x\n",
1045 	    (uintmax_t)dmar_read8(unit, DMAR_CAP_REG),
1046 	    (uintmax_t)dmar_read8(unit, DMAR_ECAP_REG),
1047 	    dmar_read4(unit, DMAR_GSTS_REG),
1048 	    dmar_read4(unit, DMAR_FSTS_REG),
1049 	    dmar_read4(unit, DMAR_FECTL_REG));
1050 	db_printf("fed 0x%x fea 0x%x feua 0x%x\n",
1051 	    dmar_read4(unit, DMAR_FEDATA_REG),
1052 	    dmar_read4(unit, DMAR_FEADDR_REG),
1053 	    dmar_read4(unit, DMAR_FEUADDR_REG));
1054 	db_printf("primary fault log:\n");
1055 	for (i = 0; i < DMAR_CAP_NFR(unit->hw_cap); i++) {
1056 		frir = (DMAR_CAP_FRO(unit->hw_cap) + i) * 16;
1057 		db_printf("  %d at 0x%x: %jx %jx\n", i, frir,
1058 		    (uintmax_t)dmar_read8(unit, frir),
1059 		    (uintmax_t)dmar_read8(unit, frir + 8));
1060 	}
1061 	if (show_ctxs) {
1062 		db_printf("contexts:\n");
1063 		LIST_FOREACH(ctx, &unit->contexts, link) {
1064 			dmar_print_ctx(ctx, show_mappings);
1065 			if (db_pager_quit)
1066 				break;
1067 		}
1068 	}
1069 }
1070 
1071 DB_SHOW_COMMAND(dmar, db_dmar_print)
1072 {
1073 	bool show_ctxs, show_mappings;
1074 
1075 	show_ctxs = strchr(modif, 'c') != NULL;
1076 	show_mappings = strchr(modif, 'm') != NULL;
1077 	if (!have_addr) {
1078 		db_printf("usage: show dmar [/c] [/m] index\n");
1079 		return;
1080 	}
1081 	dmar_print_one((int)addr, show_ctxs, show_mappings);
1082 }
1083 
1084 DB_SHOW_ALL_COMMAND(dmars, db_show_all_dmars)
1085 {
1086 	int i;
1087 	bool show_ctxs, show_mappings;
1088 
1089 	show_ctxs = strchr(modif, 'c') != NULL;
1090 	show_mappings = strchr(modif, 'm') != NULL;
1091 
1092 	for (i = 0; i < dmar_devcnt; i++) {
1093 		dmar_print_one(i, show_ctxs, show_mappings);
1094 		if (db_pager_quit)
1095 			break;
1096 	}
1097 }
1098 #endif
1099