xref: /freebsd/sys/amd64/vmm/amd/amdvi_hw.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2016, Anish Gupta (anish@freebsd.org)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    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 ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/bus.h>
35 #include <sys/kernel.h>
36 #include <sys/module.h>
37 #include <sys/malloc.h>
38 #include <sys/pcpu.h>
39 #include <sys/rman.h>
40 #include <sys/smp.h>
41 #include <sys/sysctl.h>
42 
43 #include <vm/vm.h>
44 #include <vm/pmap.h>
45 
46 #include <dev/pci/pcivar.h>
47 #include <dev/pci/pcireg.h>
48 
49 #include <machine/resource.h>
50 #include <machine/vmm.h>
51 #include <machine/pmap.h>
52 #include <machine/vmparam.h>
53 #include <machine/pci_cfgreg.h>
54 
55 #include "pcib_if.h"
56 
57 #include "io/iommu.h"
58 #include "amdvi_priv.h"
59 
60 SYSCTL_DECL(_hw_vmm);
61 SYSCTL_NODE(_hw_vmm, OID_AUTO, amdvi, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
62     NULL);
63 
64 #define MOD_INC(a, s, m) (((a) + (s)) % ((m) * (s)))
65 #define MOD_DEC(a, s, m) (((a) - (s)) % ((m) * (s)))
66 
67 /* Print RID or device ID in PCI string format. */
68 #define RID2PCI_STR(d) PCI_RID2BUS(d), PCI_RID2SLOT(d), PCI_RID2FUNC(d)
69 
70 static void amdvi_dump_cmds(struct amdvi_softc *softc, int count);
71 static void amdvi_print_dev_cap(struct amdvi_softc *softc);
72 
73 MALLOC_DEFINE(M_AMDVI, "amdvi", "amdvi");
74 
75 extern device_t *ivhd_devs;
76 
77 extern int ivhd_count;
78 SYSCTL_INT(_hw_vmm_amdvi, OID_AUTO, count, CTLFLAG_RDTUN, &ivhd_count,
79     0, NULL);
80 
81 static int amdvi_enable_user = 0;
82 SYSCTL_INT(_hw_vmm_amdvi, OID_AUTO, enable, CTLFLAG_RDTUN,
83     &amdvi_enable_user, 0, NULL);
84 TUNABLE_INT("hw.vmm.amdvi_enable", &amdvi_enable_user);
85 
86 #ifdef AMDVI_ATS_ENABLE
87 /* XXX: ATS is not tested. */
88 static int amdvi_enable_iotlb = 1;
89 SYSCTL_INT(_hw_vmm_amdvi, OID_AUTO, iotlb_enabled, CTLFLAG_RDTUN,
90     &amdvi_enable_iotlb, 0, NULL);
91 TUNABLE_INT("hw.vmm.enable_iotlb", &amdvi_enable_iotlb);
92 #endif
93 
94 static int amdvi_host_ptp = 1;	/* Use page tables for host. */
95 SYSCTL_INT(_hw_vmm_amdvi, OID_AUTO, host_ptp, CTLFLAG_RDTUN,
96     &amdvi_host_ptp, 0, NULL);
97 TUNABLE_INT("hw.vmm.amdvi.host_ptp", &amdvi_host_ptp);
98 
99 /* Page table level used <= supported by h/w[v1=7]. */
100 int amdvi_ptp_level = 4;
101 SYSCTL_INT(_hw_vmm_amdvi, OID_AUTO, ptp_level, CTLFLAG_RDTUN,
102     &amdvi_ptp_level, 0, NULL);
103 TUNABLE_INT("hw.vmm.amdvi.ptp_level", &amdvi_ptp_level);
104 
105 /* Disable fault event reporting. */
106 static int amdvi_disable_io_fault = 0;
107 SYSCTL_INT(_hw_vmm_amdvi, OID_AUTO, disable_io_fault, CTLFLAG_RDTUN,
108     &amdvi_disable_io_fault, 0, NULL);
109 TUNABLE_INT("hw.vmm.amdvi.disable_io_fault", &amdvi_disable_io_fault);
110 
111 static uint32_t amdvi_dom_id = 0;	/* 0 is reserved for host. */
112 SYSCTL_UINT(_hw_vmm_amdvi, OID_AUTO, domain_id, CTLFLAG_RD,
113     &amdvi_dom_id, 0, NULL);
114 /*
115  * Device table entry.
116  * Bus(256) x Dev(32) x Fun(8) x DTE(256 bits or 32 bytes).
117  *	= 256 * 2 * PAGE_SIZE.
118  */
119 static struct amdvi_dte amdvi_dte[PCI_NUM_DEV_MAX] __aligned(PAGE_SIZE);
120 CTASSERT(PCI_NUM_DEV_MAX == 0x10000);
121 CTASSERT(sizeof(amdvi_dte) == 0x200000);
122 
123 static SLIST_HEAD (, amdvi_domain) dom_head;
124 
125 static inline uint32_t
126 amdvi_pci_read(struct amdvi_softc *softc, int off)
127 {
128 
129 	return (pci_cfgregread(PCI_RID2BUS(softc->pci_rid),
130 	    PCI_RID2SLOT(softc->pci_rid), PCI_RID2FUNC(softc->pci_rid),
131 	    off, 4));
132 }
133 
134 #ifdef AMDVI_ATS_ENABLE
135 /* XXX: Should be in pci.c */
136 /*
137  * Check if device has ATS capability and its enabled.
138  * If ATS is absent or disabled, return (-1), otherwise ATS
139  * queue length.
140  */
141 static int
142 amdvi_find_ats_qlen(uint16_t devid)
143 {
144 	device_t dev;
145 	uint32_t off, cap;
146 	int qlen = -1;
147 
148 	dev = pci_find_bsf(PCI_RID2BUS(devid), PCI_RID2SLOT(devid),
149 			   PCI_RID2FUNC(devid));
150 
151 	if (!dev) {
152 		return (-1);
153 	}
154 #define PCIM_ATS_EN	BIT(31)
155 
156 	if (pci_find_extcap(dev, PCIZ_ATS, &off) == 0) {
157 		cap = pci_read_config(dev, off + 4, 4);
158 		qlen = (cap & 0x1F);
159 		qlen = qlen ? qlen : 32;
160 		printf("AMD-Vi: PCI device %d.%d.%d ATS %s qlen=%d\n",
161 		       RID2PCI_STR(devid),
162 		       (cap & PCIM_ATS_EN) ? "enabled" : "Disabled",
163 		       qlen);
164 		qlen = (cap & PCIM_ATS_EN) ? qlen : -1;
165 	}
166 
167 	return (qlen);
168 }
169 
170 /*
171  * Check if an endpoint device support device IOTLB or ATS.
172  */
173 static inline bool
174 amdvi_dev_support_iotlb(struct amdvi_softc *softc, uint16_t devid)
175 {
176 	struct ivhd_dev_cfg *cfg;
177 	int qlen, i;
178 	bool pci_ats, ivhd_ats;
179 
180 	qlen = amdvi_find_ats_qlen(devid);
181 	if (qlen < 0)
182 		return (false);
183 
184 	KASSERT(softc, ("softc is NULL"));
185 	cfg = softc->dev_cfg;
186 
187 	ivhd_ats = false;
188 	for (i = 0; i < softc->dev_cfg_cnt; i++) {
189 		if ((cfg->start_id <= devid) && (cfg->end_id >= devid)) {
190 			ivhd_ats = cfg->enable_ats;
191 			break;
192 		}
193 		cfg++;
194 	}
195 
196 	pci_ats = (qlen < 0) ? false : true;
197 	if (pci_ats != ivhd_ats)
198 		device_printf(softc->dev,
199 		    "BIOS bug: mismatch in ATS setting for %d.%d.%d,"
200 		    "ATS inv qlen = %d\n", RID2PCI_STR(devid), qlen);
201 
202 	/* Ignore IVRS setting and respect PCI setting. */
203 	return (pci_ats);
204 }
205 #endif
206 
207 /* Enable IOTLB support for IOMMU if its supported. */
208 static inline void
209 amdvi_hw_enable_iotlb(struct amdvi_softc *softc)
210 {
211 #ifndef AMDVI_ATS_ENABLE
212 	softc->iotlb = false;
213 #else
214 	bool supported;
215 
216 	supported = (softc->ivhd_flag & IVHD_FLAG_IOTLB) ? true : false;
217 
218 	if (softc->pci_cap & AMDVI_PCI_CAP_IOTLB) {
219 		if (!supported)
220 			device_printf(softc->dev, "IOTLB disabled by BIOS.\n");
221 
222 		if (supported && !amdvi_enable_iotlb) {
223 			device_printf(softc->dev, "IOTLB disabled by user.\n");
224 			supported = false;
225 		}
226 	} else
227 		supported = false;
228 
229 	softc->iotlb = supported;
230 
231 #endif
232 }
233 
234 static int
235 amdvi_init_cmd(struct amdvi_softc *softc)
236 {
237 	struct amdvi_ctrl *ctrl = softc->ctrl;
238 
239 	ctrl->cmd.len = 8;	/* Use 256 command buffer entries. */
240 	softc->cmd_max = 1 << ctrl->cmd.len;
241 
242 	softc->cmd = malloc(sizeof(struct amdvi_cmd) *
243 	    softc->cmd_max, M_AMDVI, M_WAITOK | M_ZERO);
244 
245 	if ((uintptr_t)softc->cmd & PAGE_MASK)
246 		panic("AMDVi: Command buffer not aligned on page boundary.");
247 
248 	ctrl->cmd.base = vtophys(softc->cmd) / PAGE_SIZE;
249 	/*
250 	 * XXX: Reset the h/w pointers in case IOMMU is restarting,
251 	 * h/w doesn't clear these pointers based on empirical data.
252 	 */
253 	ctrl->cmd_tail = 0;
254 	ctrl->cmd_head = 0;
255 
256 	return (0);
257 }
258 
259 /*
260  * Note: Update tail pointer after we have written the command since tail
261  * pointer update cause h/w to execute new commands, see section 3.3
262  * of AMD IOMMU spec ver 2.0.
263  */
264 /* Get the command tail pointer w/o updating it. */
265 static struct amdvi_cmd *
266 amdvi_get_cmd_tail(struct amdvi_softc *softc)
267 {
268 	struct amdvi_ctrl *ctrl;
269 	struct amdvi_cmd *tail;
270 
271 	KASSERT(softc, ("softc is NULL"));
272 	KASSERT(softc->cmd != NULL, ("cmd is NULL"));
273 
274 	ctrl = softc->ctrl;
275 	KASSERT(ctrl != NULL, ("ctrl is NULL"));
276 
277 	tail = (struct amdvi_cmd *)((uint8_t *)softc->cmd +
278 	    ctrl->cmd_tail);
279 
280 	return (tail);
281 }
282 
283 /*
284  * Update the command tail pointer which will start command execution.
285  */
286 static void
287 amdvi_update_cmd_tail(struct amdvi_softc *softc)
288 {
289 	struct amdvi_ctrl *ctrl;
290 	int size;
291 
292 	size = sizeof(struct amdvi_cmd);
293 	KASSERT(softc->cmd != NULL, ("cmd is NULL"));
294 
295 	ctrl = softc->ctrl;
296 	KASSERT(ctrl != NULL, ("ctrl is NULL"));
297 
298 	ctrl->cmd_tail = MOD_INC(ctrl->cmd_tail, size, softc->cmd_max);
299 	softc->total_cmd++;
300 
301 #ifdef AMDVI_DEBUG_CMD
302 	device_printf(softc->dev, "cmd_tail: %s Tail:0x%x, Head:0x%x.\n",
303 	    ctrl->cmd_tail,
304 	    ctrl->cmd_head);
305 #endif
306 
307 }
308 
309 /*
310  * Various commands supported by IOMMU.
311  */
312 
313 /* Completion wait command. */
314 static void
315 amdvi_cmd_cmp(struct amdvi_softc *softc, const uint64_t data)
316 {
317 	struct amdvi_cmd *cmd;
318 	uint64_t pa;
319 
320 	cmd = amdvi_get_cmd_tail(softc);
321 	KASSERT(cmd != NULL, ("Cmd is NULL"));
322 
323 	pa = vtophys(&softc->cmp_data);
324 	cmd->opcode = AMDVI_CMP_WAIT_OPCODE;
325 	cmd->word0 = (pa & 0xFFFFFFF8) | AMDVI_CMP_WAIT_STORE;
326 	cmd->word1 = (pa >> 32) & 0xFFFFF;
327 	cmd->addr = data;
328 
329 	amdvi_update_cmd_tail(softc);
330 }
331 
332 /* Invalidate device table entry. */
333 static void
334 amdvi_cmd_inv_dte(struct amdvi_softc *softc, uint16_t devid)
335 {
336 	struct amdvi_cmd *cmd;
337 
338 	cmd = amdvi_get_cmd_tail(softc);
339 	KASSERT(cmd != NULL, ("Cmd is NULL"));
340 	cmd->opcode = AMDVI_INVD_DTE_OPCODE;
341 	cmd->word0 = devid;
342 	amdvi_update_cmd_tail(softc);
343 #ifdef AMDVI_DEBUG_CMD
344 	device_printf(softc->dev, "Invalidated DTE:0x%x\n", devid);
345 #endif
346 }
347 
348 /* Invalidate IOMMU page, use for invalidation of domain. */
349 static void
350 amdvi_cmd_inv_iommu_pages(struct amdvi_softc *softc, uint16_t domain_id,
351 			  uint64_t addr, bool guest_nested,
352 			  bool pde, bool page)
353 {
354 	struct amdvi_cmd *cmd;
355 
356 	cmd = amdvi_get_cmd_tail(softc);
357 	KASSERT(cmd != NULL, ("Cmd is NULL"));
358 
359 	cmd->opcode = AMDVI_INVD_PAGE_OPCODE;
360 	cmd->word1 = domain_id;
361 	/*
362 	 * Invalidate all addresses for this domain.
363 	 */
364 	cmd->addr = addr;
365 	cmd->addr |= pde ? AMDVI_INVD_PAGE_PDE : 0;
366 	cmd->addr |= page ? AMDVI_INVD_PAGE_S : 0;
367 
368 	amdvi_update_cmd_tail(softc);
369 }
370 
371 #ifdef AMDVI_ATS_ENABLE
372 /* Invalidate device IOTLB. */
373 static void
374 amdvi_cmd_inv_iotlb(struct amdvi_softc *softc, uint16_t devid)
375 {
376 	struct amdvi_cmd *cmd;
377 	int qlen;
378 
379 	if (!softc->iotlb)
380 		return;
381 
382 	qlen = amdvi_find_ats_qlen(devid);
383 	if (qlen < 0) {
384 		panic("AMDVI: Invalid ATS qlen(%d) for device %d.%d.%d\n",
385 		      qlen, RID2PCI_STR(devid));
386 	}
387 	cmd = amdvi_get_cmd_tail(softc);
388 	KASSERT(cmd != NULL, ("Cmd is NULL"));
389 
390 #ifdef AMDVI_DEBUG_CMD
391 	device_printf(softc->dev, "Invalidate IOTLB devID 0x%x"
392 		      " Qlen:%d\n", devid, qlen);
393 #endif
394 	cmd->opcode = AMDVI_INVD_IOTLB_OPCODE;
395 	cmd->word0 = devid;
396 	cmd->word1 = qlen;
397 	cmd->addr = AMDVI_INVD_IOTLB_ALL_ADDR |
398 		AMDVI_INVD_IOTLB_S;
399 	amdvi_update_cmd_tail(softc);
400 }
401 #endif
402 
403 #ifdef notyet				/* For Interrupt Remap. */
404 static void
405 amdvi_cmd_inv_intr_map(struct amdvi_softc *softc,
406 		       uint16_t devid)
407 {
408 	struct amdvi_cmd *cmd;
409 
410 	cmd = amdvi_get_cmd_tail(softc);
411 	KASSERT(cmd != NULL, ("Cmd is NULL"));
412 	cmd->opcode = AMDVI_INVD_INTR_OPCODE;
413 	cmd->word0 = devid;
414 	amdvi_update_cmd_tail(softc);
415 #ifdef AMDVI_DEBUG_CMD
416 	device_printf(softc->dev, "Invalidate INTR map of devID 0x%x\n", devid);
417 #endif
418 }
419 #endif
420 
421 /* Invalidate domain using INVALIDATE_IOMMU_PAGES command. */
422 static void
423 amdvi_inv_domain(struct amdvi_softc *softc, uint16_t domain_id)
424 {
425 	struct amdvi_cmd *cmd;
426 
427 	cmd = amdvi_get_cmd_tail(softc);
428 	KASSERT(cmd != NULL, ("Cmd is NULL"));
429 
430 	/*
431 	 * See section 3.3.3 of IOMMU spec rev 2.0, software note
432 	 * for invalidating domain.
433 	 */
434 	amdvi_cmd_inv_iommu_pages(softc, domain_id, AMDVI_INVD_PAGE_ALL_ADDR,
435 				false, true, true);
436 
437 #ifdef AMDVI_DEBUG_CMD
438 	device_printf(softc->dev, "Invalidate domain:0x%x\n", domain_id);
439 
440 #endif
441 }
442 
443 static	bool
444 amdvi_cmp_wait(struct amdvi_softc *softc)
445 {
446 	struct amdvi_ctrl *ctrl;
447 	const uint64_t VERIFY = 0xA5A5;
448 	volatile uint64_t *read;
449 	int i;
450 	bool status;
451 
452 	ctrl = softc->ctrl;
453 	read = &softc->cmp_data;
454 	*read = 0;
455 	amdvi_cmd_cmp(softc, VERIFY);
456 	/* Wait for h/w to update completion data. */
457 	for (i = 0; i < 100 && (*read != VERIFY); i++) {
458 		DELAY(1000);		/* 1 ms */
459 	}
460 	status = (VERIFY == softc->cmp_data) ? true : false;
461 
462 #ifdef AMDVI_DEBUG_CMD
463 	if (status)
464 		device_printf(softc->dev, "CMD completion DONE Tail:0x%x, "
465 			      "Head:0x%x, loop:%d.\n", ctrl->cmd_tail,
466 			      ctrl->cmd_head, loop);
467 #endif
468 	return (status);
469 }
470 
471 static void
472 amdvi_wait(struct amdvi_softc *softc)
473 {
474 	struct amdvi_ctrl *ctrl;
475 	int i;
476 
477 	KASSERT(softc, ("softc is NULL"));
478 
479 	ctrl = softc->ctrl;
480 	KASSERT(ctrl != NULL, ("ctrl is NULL"));
481 	/* Don't wait if h/w is not enabled. */
482 	if ((ctrl->control & AMDVI_CTRL_EN) == 0)
483 		return;
484 
485 	for (i = 0; i < 10; i++) {
486 		if (amdvi_cmp_wait(softc))
487 			return;
488 	}
489 
490 	device_printf(softc->dev, "Error: completion failed"
491 		      " tail:0x%x, head:0x%x.\n",
492 		      ctrl->cmd_tail, ctrl->cmd_head);
493 	/* Dump the last command. */
494 	amdvi_dump_cmds(softc, 1);
495 }
496 
497 static void
498 amdvi_dump_cmds(struct amdvi_softc *softc, int count)
499 {
500 	struct amdvi_ctrl *ctrl;
501 	struct amdvi_cmd *cmd;
502 	int off, i;
503 
504 	ctrl = softc->ctrl;
505 	device_printf(softc->dev, "Dump last %d command(s):\n", count);
506 	/*
507 	 * If h/w is stuck in completion, it is the previous command,
508 	 * start dumping from previous command onward.
509 	 */
510 	off = MOD_DEC(ctrl->cmd_head, sizeof(struct amdvi_cmd),
511 	    softc->cmd_max);
512 	for (i = 0; off != ctrl->cmd_tail && i < count; i++) {
513 		cmd = (struct amdvi_cmd *)((uint8_t *)softc->cmd + off);
514 		printf("  [CMD%d, off:0x%x] opcode= 0x%x 0x%x"
515 		    " 0x%x 0x%lx\n", i, off, cmd->opcode,
516 		    cmd->word0, cmd->word1, cmd->addr);
517 		off = (off + sizeof(struct amdvi_cmd)) %
518 		    (softc->cmd_max * sizeof(struct amdvi_cmd));
519 	}
520 }
521 
522 static int
523 amdvi_init_event(struct amdvi_softc *softc)
524 {
525 	struct amdvi_ctrl *ctrl;
526 
527 	ctrl = softc->ctrl;
528 	ctrl->event.len = 8;
529 	softc->event_max = 1 << ctrl->event.len;
530 	softc->event = malloc(sizeof(struct amdvi_event) *
531 	    softc->event_max, M_AMDVI, M_WAITOK | M_ZERO);
532 	if ((uintptr_t)softc->event & PAGE_MASK) {
533 		device_printf(softc->dev, "Event buffer not aligned on page.");
534 		return (false);
535 	}
536 	ctrl->event.base = vtophys(softc->event) / PAGE_SIZE;
537 
538 	/* Reset the pointers. */
539 	ctrl->evt_head = 0;
540 	ctrl->evt_tail = 0;
541 
542 	return (0);
543 }
544 
545 static inline void
546 amdvi_decode_evt_flag(uint16_t flag)
547 {
548 
549 	flag &= AMDVI_EVENT_FLAG_MASK;
550 	printf(" 0x%b]\n", flag,
551 		"\020"
552 		"\001GN"
553 		"\002NX"
554 		"\003US"
555 		"\004I"
556 		"\005PR"
557 		"\006RW"
558 		"\007PE"
559 		"\010RZ"
560 		"\011TR"
561 		);
562 }
563 
564 /* See section 2.5.4 of AMD IOMMU spec ver 2.62.*/
565 static inline void
566 amdvi_decode_evt_flag_type(uint8_t type)
567 {
568 
569 	switch (AMDVI_EVENT_FLAG_TYPE(type)) {
570 	case 0:
571 		printf("RSVD\n");
572 		break;
573 	case 1:
574 		printf("Master Abort\n");
575 		break;
576 	case 2:
577 		printf("Target Abort\n");
578 		break;
579 	case 3:
580 		printf("Data Err\n");
581 		break;
582 	default:
583 		break;
584 	}
585 }
586 
587 static void
588 amdvi_decode_inv_dte_evt(uint16_t devid, uint16_t domid, uint64_t addr,
589     uint16_t flag)
590 {
591 
592 	printf("\t[IO_PAGE_FAULT EVT: devId:0x%x DomId:0x%x"
593 	    " Addr:0x%lx",
594 	    devid, domid, addr);
595 	amdvi_decode_evt_flag(flag);
596 }
597 
598 static void
599 amdvi_decode_pf_evt(uint16_t devid, uint16_t domid, uint64_t addr,
600     uint16_t flag)
601 {
602 
603 	printf("\t[IO_PAGE_FAULT EVT: devId:0x%x DomId:0x%x"
604 	    " Addr:0x%lx",
605 	    devid, domid, addr);
606 	amdvi_decode_evt_flag(flag);
607 }
608 
609 static void
610 amdvi_decode_dte_hwerr_evt(uint16_t devid, uint16_t domid,
611     uint64_t addr, uint16_t flag)
612 {
613 
614 	printf("\t[DEV_TAB_HW_ERR EVT: devId:0x%x DomId:0x%x"
615 	    " Addr:0x%lx", devid, domid, addr);
616 	amdvi_decode_evt_flag(flag);
617 	amdvi_decode_evt_flag_type(flag);
618 }
619 
620 static void
621 amdvi_decode_page_hwerr_evt(uint16_t devid, uint16_t domid, uint64_t addr,
622     uint16_t flag)
623 {
624 
625 	printf("\t[PAGE_TAB_HW_ERR EVT: devId:0x%x DomId:0x%x"
626 	    " Addr:0x%lx", devid, domid, addr);
627 	amdvi_decode_evt_flag(flag);
628 	amdvi_decode_evt_flag_type(AMDVI_EVENT_FLAG_TYPE(flag));
629 }
630 
631 static void
632 amdvi_decode_evt(struct amdvi_event *evt)
633 {
634 	struct amdvi_cmd *cmd;
635 
636 	switch (evt->opcode) {
637 	case AMDVI_EVENT_INVALID_DTE:
638 		amdvi_decode_inv_dte_evt(evt->devid, evt->pasid_domid,
639 		    evt->addr, evt->flag);
640 		break;
641 
642 	case AMDVI_EVENT_PFAULT:
643 		amdvi_decode_pf_evt(evt->devid, evt->pasid_domid,
644 		    evt->addr, evt->flag);
645 		break;
646 
647 	case AMDVI_EVENT_DTE_HW_ERROR:
648 		amdvi_decode_dte_hwerr_evt(evt->devid, evt->pasid_domid,
649 		    evt->addr, evt->flag);
650 		break;
651 
652 	case AMDVI_EVENT_PAGE_HW_ERROR:
653 		amdvi_decode_page_hwerr_evt(evt->devid, evt->pasid_domid,
654 		    evt->addr, evt->flag);
655 		break;
656 
657 	case AMDVI_EVENT_ILLEGAL_CMD:
658 		/* FALL THROUGH */
659 	case AMDVI_EVENT_CMD_HW_ERROR:
660 		printf("\t[%s EVT]\n", (evt->opcode == AMDVI_EVENT_ILLEGAL_CMD) ?
661 		    "ILLEGAL CMD" : "CMD HW ERR");
662 		cmd = (struct amdvi_cmd *)PHYS_TO_DMAP(evt->addr);
663 		printf("\tCMD opcode= 0x%x 0x%x 0x%x 0x%lx\n",
664 		    cmd->opcode, cmd->word0, cmd->word1, cmd->addr);
665 		break;
666 
667 	case AMDVI_EVENT_IOTLB_TIMEOUT:
668 		printf("\t[IOTLB_INV_TIMEOUT devid:0x%x addr:0x%lx]\n",
669 		    evt->devid, evt->addr);
670 		break;
671 
672 	case AMDVI_EVENT_INVALID_DTE_REQ:
673 		printf("\t[INV_DTE devid:0x%x addr:0x%lx type:0x%x tr:%d]\n",
674 		    evt->devid, evt->addr, evt->flag >> 9,
675 		    (evt->flag >> 8) & 1);
676 		break;
677 
678 	case AMDVI_EVENT_INVALID_PPR_REQ:
679 	case AMDVI_EVENT_COUNTER_ZERO:
680 		printf("AMD-Vi: v2 events.\n");
681 		break;
682 
683 	default:
684 		printf("Unsupported AMD-Vi event:%d\n", evt->opcode);
685 	}
686 }
687 
688 static void
689 amdvi_print_events(struct amdvi_softc *softc)
690 {
691 	struct amdvi_ctrl *ctrl;
692 	struct amdvi_event *event;
693 	int i, size;
694 
695 	ctrl = softc->ctrl;
696 	size = sizeof(struct amdvi_event);
697 	for (i = 0; i < softc->event_max; i++) {
698 		event = &softc->event[ctrl->evt_head / size];
699 		if (!event->opcode)
700 			break;
701 		device_printf(softc->dev, "\t[Event%d: Head:0x%x Tail:0x%x]\n",
702 		    i, ctrl->evt_head, ctrl->evt_tail);
703 		amdvi_decode_evt(event);
704 		ctrl->evt_head = MOD_INC(ctrl->evt_head, size,
705 		    softc->event_max);
706 	}
707 }
708 
709 static int
710 amdvi_init_dte(struct amdvi_softc *softc)
711 {
712 	struct amdvi_ctrl *ctrl;
713 
714 	ctrl = softc->ctrl;
715 	ctrl->dte.base = vtophys(amdvi_dte) / PAGE_SIZE;
716 	ctrl->dte.size = 0x1FF;		/* 2MB device table. */
717 
718 	return (0);
719 }
720 
721 /*
722  * Not all capabilities of IOMMU are available in ACPI IVHD flag
723  * or EFR entry, read directly from device.
724  */
725 static int
726 amdvi_print_pci_cap(device_t dev)
727 {
728 	struct amdvi_softc *softc;
729 	uint32_t off, cap;
730 
731 	softc = device_get_softc(dev);
732 	off = softc->cap_off;
733 
734 	/*
735 	 * Section 3.7.1 of IOMMU sepc rev 2.0.
736 	 * Read capability from device.
737 	 */
738 	cap = amdvi_pci_read(softc, off);
739 
740 	/* Make sure capability type[18:16] is 3. */
741 	KASSERT((((cap >> 16) & 0x7) == 0x3),
742 	    ("Not a IOMMU capability 0x%x@0x%x", cap, off));
743 
744 	softc->pci_cap = cap >> 24;
745 	device_printf(softc->dev, "PCI cap 0x%x@0x%x feature:%b\n",
746 	    cap, off, softc->pci_cap,
747 	    "\20\1IOTLB\2HT\3NPCache\4EFR\5CapExt");
748 
749 	return (0);
750 }
751 
752 static void
753 amdvi_event_intr(void *arg)
754 {
755 	struct amdvi_softc *softc;
756 	struct amdvi_ctrl *ctrl;
757 
758 	softc = (struct amdvi_softc *)arg;
759 	ctrl = softc->ctrl;
760 	device_printf(softc->dev, "EVT INTR %ld Status:0x%x"
761 	    " EVT Head:0x%x Tail:0x%x]\n", softc->event_intr_cnt++,
762 	    ctrl->status, ctrl->evt_head, ctrl->evt_tail);
763 	printf("  [CMD Total 0x%lx] Tail:0x%x, Head:0x%x.\n",
764 	    softc->total_cmd, ctrl->cmd_tail, ctrl->cmd_head);
765 
766 	amdvi_print_events(softc);
767 	ctrl->status &= AMDVI_STATUS_EV_OF | AMDVI_STATUS_EV_INTR;
768 }
769 
770 static void
771 amdvi_free_evt_intr_res(device_t dev)
772 {
773 
774 	struct amdvi_softc *softc;
775 
776 	softc = device_get_softc(dev);
777 	if (softc->event_tag != NULL) {
778 		bus_teardown_intr(dev, softc->event_res, softc->event_tag);
779 	}
780 	if (softc->event_res != NULL) {
781 		bus_release_resource(dev, SYS_RES_IRQ, softc->event_rid,
782 		    softc->event_res);
783 	}
784 	bus_delete_resource(dev, SYS_RES_IRQ, softc->event_rid);
785 	PCIB_RELEASE_MSI(device_get_parent(device_get_parent(dev)),
786 	    dev, 1, &softc->event_irq);
787 }
788 
789 static bool
790 amdvi_alloc_intr_resources(struct amdvi_softc *softc)
791 {
792 	struct amdvi_ctrl *ctrl;
793 	device_t dev, pcib;
794 	device_t mmio_dev;
795 	uint64_t msi_addr;
796 	uint32_t msi_data;
797 	int err;
798 
799 	dev = softc->dev;
800 	pcib = device_get_parent(device_get_parent(dev));
801 	mmio_dev = pci_find_bsf(PCI_RID2BUS(softc->pci_rid),
802             PCI_RID2SLOT(softc->pci_rid), PCI_RID2FUNC(softc->pci_rid));
803 	if (device_is_attached(mmio_dev)) {
804 		device_printf(dev,
805 		    "warning: IOMMU device is claimed by another driver %s\n",
806 		    device_get_driver(mmio_dev)->name);
807 	}
808 
809 	softc->event_irq = -1;
810 	softc->event_rid = 0;
811 
812 	/*
813 	 * Section 3.7.1 of IOMMU rev 2.0. With MSI, there is only one
814 	 * interrupt. XXX: Enable MSI/X support.
815 	 */
816 	err = PCIB_ALLOC_MSI(pcib, dev, 1, 1, &softc->event_irq);
817 	if (err) {
818 		device_printf(dev,
819 		    "Couldn't find event MSI IRQ resource.\n");
820 		return (ENOENT);
821 	}
822 
823 	err = bus_set_resource(dev, SYS_RES_IRQ, softc->event_rid,
824 	    softc->event_irq, 1);
825 	if (err) {
826 		device_printf(dev, "Couldn't set event MSI resource.\n");
827 		return (ENXIO);
828 	}
829 
830 	softc->event_res = bus_alloc_resource_any(dev, SYS_RES_IRQ,
831 	    &softc->event_rid, RF_ACTIVE);
832 	if (!softc->event_res) {
833 		device_printf(dev,
834 		    "Unable to allocate event INTR resource.\n");
835 		return (ENOMEM);
836 	}
837 
838 	if (bus_setup_intr(dev, softc->event_res,
839 	    INTR_TYPE_MISC | INTR_MPSAFE, NULL, amdvi_event_intr,
840 	    softc, &softc->event_tag)) {
841 		device_printf(dev, "Fail to setup event intr\n");
842 		bus_release_resource(softc->dev, SYS_RES_IRQ,
843 		    softc->event_rid, softc->event_res);
844 		softc->event_res = NULL;
845 		return (ENXIO);
846 	}
847 
848 	bus_describe_intr(dev, softc->event_res, softc->event_tag,
849 	    "fault");
850 
851 	err = PCIB_MAP_MSI(pcib, dev, softc->event_irq, &msi_addr,
852 	    &msi_data);
853 	if (err) {
854 		device_printf(dev,
855 		    "Event interrupt config failed, err=%d.\n",
856 		    err);
857 		amdvi_free_evt_intr_res(softc->dev);
858 		return (err);
859 	}
860 
861 	/* Clear interrupt status bits. */
862 	ctrl = softc->ctrl;
863 	ctrl->status &= AMDVI_STATUS_EV_OF | AMDVI_STATUS_EV_INTR;
864 
865 	/* Now enable MSI interrupt. */
866 	pci_enable_msi(mmio_dev, msi_addr, msi_data);
867 	return (0);
868 }
869 
870 static void
871 amdvi_print_dev_cap(struct amdvi_softc *softc)
872 {
873 	struct ivhd_dev_cfg *cfg;
874 	int i;
875 
876 	cfg = softc->dev_cfg;
877 	for (i = 0; i < softc->dev_cfg_cnt; i++) {
878 		device_printf(softc->dev, "device [0x%x - 0x%x]"
879 		    "config:%b%s\n", cfg->start_id, cfg->end_id,
880 		    cfg->data,
881 		    "\020\001INIT\002ExtInt\003NMI"
882 		    "\007LINT0\008LINT1",
883 		    cfg->enable_ats ? "ATS enabled" : "");
884 		cfg++;
885 	}
886 }
887 
888 static int
889 amdvi_handle_sysctl(SYSCTL_HANDLER_ARGS)
890 {
891 	struct amdvi_softc *softc;
892 	int result, type, error = 0;
893 
894 	softc = (struct amdvi_softc *)arg1;
895 	type = arg2;
896 
897 	switch (type) {
898 	case 0:
899 		result = softc->ctrl->cmd_head;
900 		error = sysctl_handle_int(oidp, &result, 0,
901 		    req);
902 		break;
903 	case 1:
904 		result = softc->ctrl->cmd_tail;
905 		error = sysctl_handle_int(oidp, &result, 0,
906 		    req);
907 		break;
908 	case 2:
909 		result = softc->ctrl->evt_head;
910 		error = sysctl_handle_int(oidp, &result, 0,
911 		    req);
912 		break;
913 	case 3:
914 		result = softc->ctrl->evt_tail;
915 		error = sysctl_handle_int(oidp, &result, 0,
916 		    req);
917 		break;
918 
919 	default:
920 		device_printf(softc->dev, "Unknown sysctl:%d\n", type);
921 	}
922 
923 	return (error);
924 }
925 
926 static void
927 amdvi_add_sysctl(struct amdvi_softc *softc)
928 {
929 	struct sysctl_oid_list *child;
930 	struct sysctl_ctx_list *ctx;
931 	device_t dev;
932 
933 	dev = softc->dev;
934 	ctx = device_get_sysctl_ctx(dev);
935 	child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
936 
937 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "event_intr_count", CTLFLAG_RD,
938 	    &softc->event_intr_cnt, "Event interrupt count");
939 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "command_count", CTLFLAG_RD,
940 	    &softc->total_cmd, "Command submitted count");
941 	SYSCTL_ADD_U16(ctx, child, OID_AUTO, "pci_rid", CTLFLAG_RD,
942 	    &softc->pci_rid, 0, "IOMMU RID");
943 	SYSCTL_ADD_U16(ctx, child, OID_AUTO, "start_dev_rid", CTLFLAG_RD,
944 	    &softc->start_dev_rid, 0, "Start of device under this IOMMU");
945 	SYSCTL_ADD_U16(ctx, child, OID_AUTO, "end_dev_rid", CTLFLAG_RD,
946 	    &softc->end_dev_rid, 0, "End of device under this IOMMU");
947 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "command_head",
948 	    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, softc, 0,
949 	    amdvi_handle_sysctl, "IU", "Command head");
950 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "command_tail",
951 	    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, softc, 1,
952 	    amdvi_handle_sysctl, "IU", "Command tail");
953 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "event_head",
954 	    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, softc, 2,
955 	    amdvi_handle_sysctl, "IU", "Command head");
956 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "event_tail",
957 	    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, softc, 3,
958 	    amdvi_handle_sysctl, "IU", "Command tail");
959 }
960 
961 int
962 amdvi_setup_hw(struct amdvi_softc *softc)
963 {
964 	device_t dev;
965 	int status;
966 
967 	dev = softc->dev;
968 
969 	amdvi_hw_enable_iotlb(softc);
970 
971 	amdvi_print_dev_cap(softc);
972 
973 	if ((status = amdvi_print_pci_cap(dev)) != 0) {
974 		device_printf(dev, "PCI capability.\n");
975 		return (status);
976 	}
977 	if ((status = amdvi_init_cmd(softc)) != 0) {
978 		device_printf(dev, "Couldn't configure command buffer.\n");
979 		return (status);
980 	}
981 	if ((status = amdvi_init_event(softc)) != 0) {
982 		device_printf(dev, "Couldn't configure event buffer.\n");
983 		return (status);
984 	}
985 	if ((status = amdvi_init_dte(softc)) != 0) {
986 		device_printf(dev, "Couldn't configure device table.\n");
987 		return (status);
988 	}
989 	if ((status = amdvi_alloc_intr_resources(softc)) != 0) {
990 		return (status);
991 	}
992 	amdvi_add_sysctl(softc);
993 	return (0);
994 }
995 
996 int
997 amdvi_teardown_hw(struct amdvi_softc *softc)
998 {
999 	device_t dev;
1000 
1001 	dev = softc->dev;
1002 
1003 	/*
1004 	 * Called after disable, h/w is stopped by now, free all the resources.
1005 	 */
1006 	amdvi_free_evt_intr_res(dev);
1007 
1008 	if (softc->cmd)
1009 		free(softc->cmd, M_AMDVI);
1010 
1011 	if (softc->event)
1012 		free(softc->event, M_AMDVI);
1013 
1014 	return (0);
1015 }
1016 
1017 /*********** bhyve interfaces *********************/
1018 static int
1019 amdvi_init(void)
1020 {
1021 	if (!ivhd_count) {
1022 		return (EIO);
1023 	}
1024 	if (!amdvi_enable_user && ivhd_count) {
1025 		printf("bhyve: Found %d AMD-Vi/IOMMU device(s), "
1026 		    	"use hw.vmm.amdvi.enable=1 to enable pass-through.\n",
1027 		    ivhd_count);
1028 		return (EINVAL);
1029 	}
1030 	return (0);
1031 }
1032 
1033 static void
1034 amdvi_cleanup(void)
1035 {
1036 	/* Nothing. */
1037 }
1038 
1039 static uint16_t
1040 amdvi_domainId(void)
1041 {
1042 
1043 	/*
1044 	 * If we hit maximum domain limit, rollover leaving host
1045 	 * domain(0).
1046 	 * XXX: make sure that this domain is not used.
1047 	 */
1048 	if (amdvi_dom_id == AMDVI_MAX_DOMAIN)
1049 		amdvi_dom_id = 1;
1050 
1051 	return ((uint16_t)amdvi_dom_id++);
1052 }
1053 
1054 static void
1055 amdvi_do_inv_domain(uint16_t domain_id, bool create)
1056 {
1057 	struct amdvi_softc *softc;
1058 	int i;
1059 
1060 	for (i = 0; i < ivhd_count; i++) {
1061 		softc = device_get_softc(ivhd_devs[i]);
1062 		KASSERT(softc, ("softc is NULL"));
1063 		/*
1064 		 * If not present pages are cached, invalidate page after
1065 		 * creating domain.
1066 		 */
1067 #if 0
1068 		if (create && ((softc->pci_cap & AMDVI_PCI_CAP_NPCACHE) == 0))
1069 			continue;
1070 #endif
1071 		amdvi_inv_domain(softc, domain_id);
1072 		amdvi_wait(softc);
1073 	}
1074 }
1075 
1076 static void *
1077 amdvi_create_domain(vm_paddr_t maxaddr)
1078 {
1079 	struct amdvi_domain *dom;
1080 
1081 	dom = malloc(sizeof(struct amdvi_domain), M_AMDVI, M_ZERO | M_WAITOK);
1082 	dom->id = amdvi_domainId();
1083 	//dom->maxaddr = maxaddr;
1084 #ifdef AMDVI_DEBUG_CMD
1085 	printf("Created domain #%d\n", dom->id);
1086 #endif
1087 	/*
1088 	 * Host domain(#0) don't create translation table.
1089 	 */
1090 	if (dom->id || amdvi_host_ptp)
1091 		dom->ptp = malloc(PAGE_SIZE, M_AMDVI, M_WAITOK | M_ZERO);
1092 
1093 	dom->ptp_level = amdvi_ptp_level;
1094 
1095 	amdvi_do_inv_domain(dom->id, true);
1096 	SLIST_INSERT_HEAD(&dom_head, dom, next);
1097 
1098 	return (dom);
1099 }
1100 
1101 static void
1102 amdvi_free_ptp(uint64_t *ptp, int level)
1103 {
1104 	int i;
1105 
1106 	if (level < 1)
1107 		return;
1108 
1109 	for (i = 0; i < NPTEPG ; i++) {
1110 		if ((ptp[i] & AMDVI_PT_PRESENT) == 0)
1111 			continue;
1112 		/* XXX: Add super-page or PTE mapping > 4KB. */
1113 #ifdef notyet
1114 		/* Super-page mapping. */
1115 		if (AMDVI_PD_SUPER(ptp[i]))
1116 			continue;
1117 #endif
1118 
1119 		amdvi_free_ptp((uint64_t *)PHYS_TO_DMAP(ptp[i]
1120 		    & AMDVI_PT_MASK), level - 1);
1121 	}
1122 
1123 	free(ptp, M_AMDVI);
1124 }
1125 
1126 static void
1127 amdvi_destroy_domain(void *arg)
1128 {
1129 	struct amdvi_domain *domain;
1130 
1131 	domain = (struct amdvi_domain *)arg;
1132 	KASSERT(domain, ("domain is NULL"));
1133 #ifdef AMDVI_DEBUG_CMD
1134 	printf("Destroying domain %d\n", domain->id);
1135 #endif
1136 	if (domain->ptp)
1137 		amdvi_free_ptp(domain->ptp, domain->ptp_level);
1138 
1139 	amdvi_do_inv_domain(domain->id, false);
1140 	SLIST_REMOVE(&dom_head, domain, amdvi_domain, next);
1141 	free(domain, M_AMDVI);
1142 }
1143 
1144 static uint64_t
1145 amdvi_set_pt(uint64_t *pt, int level, vm_paddr_t gpa,
1146     vm_paddr_t hpa, uint64_t pg_size, bool create)
1147 {
1148 	uint64_t *page, pa;
1149 	int shift, index;
1150 	const int PT_SHIFT = 9;
1151 	const int PT_INDEX_MASK = (1 << PT_SHIFT) - 1;	/* Based on PT_SHIFT */
1152 
1153 	if (!pg_size)
1154 		return (0);
1155 
1156 	if (hpa & (pg_size - 1)) {
1157 		printf("HPA is not size aligned.\n");
1158 		return (0);
1159 	}
1160 	if (gpa & (pg_size - 1)) {
1161 		printf("HPA is not size aligned.\n");
1162 		return (0);
1163 	}
1164 	shift = PML4SHIFT;
1165 	while ((shift > PAGE_SHIFT) && (pg_size < (1UL << shift))) {
1166 		index = (gpa >> shift) & PT_INDEX_MASK;
1167 
1168 		if ((pt[index] == 0) && create) {
1169 			page = malloc(PAGE_SIZE, M_AMDVI, M_WAITOK | M_ZERO);
1170 			pa = vtophys(page);
1171 			pt[index] = pa | AMDVI_PT_PRESENT | AMDVI_PT_RW |
1172 			    ((level - 1) << AMDVI_PD_LEVEL_SHIFT);
1173 		}
1174 #ifdef AMDVI_DEBUG_PTE
1175 		if ((gpa % 0x1000000) == 0)
1176 			printf("[level%d, shift = %d]PTE:0x%lx\n",
1177 			    level, shift, pt[index]);
1178 #endif
1179 #define PTE2PA(x)	((uint64_t)(x) & AMDVI_PT_MASK)
1180 		pa = PTE2PA(pt[index]);
1181 		pt = (uint64_t *)PHYS_TO_DMAP(pa);
1182 		shift -= PT_SHIFT;
1183 		level--;
1184 	}
1185 
1186 	/* Leaf entry. */
1187 	index = (gpa >> shift) & PT_INDEX_MASK;
1188 
1189 	if (create) {
1190 		pt[index] = hpa | AMDVI_PT_RW | AMDVI_PT_PRESENT;
1191 	} else
1192 		pt[index] = 0;
1193 
1194 #ifdef AMDVI_DEBUG_PTE
1195 	if ((gpa % 0x1000000) == 0)
1196 		printf("[Last level%d, shift = %d]PTE:0x%lx\n",
1197 		    level, shift, pt[index]);
1198 #endif
1199 	return (1ULL << shift);
1200 }
1201 
1202 static uint64_t
1203 amdvi_update_mapping(struct amdvi_domain *domain, vm_paddr_t gpa,
1204     vm_paddr_t hpa, uint64_t size, bool create)
1205 {
1206 	uint64_t mapped, *ptp, len;
1207 	int level;
1208 
1209 	KASSERT(domain, ("domain is NULL"));
1210 	level = domain->ptp_level;
1211 	KASSERT(level, ("Page table level is 0"));
1212 
1213 	ptp = domain->ptp;
1214 	KASSERT(ptp, ("PTP is NULL"));
1215 	mapped = 0;
1216 	while (mapped < size) {
1217 		len = amdvi_set_pt(ptp, level, gpa + mapped, hpa + mapped,
1218 		    PAGE_SIZE, create);
1219 		if (!len) {
1220 			printf("Error: Couldn't map HPA:0x%lx GPA:0x%lx\n",
1221 			    hpa, gpa);
1222 			return (0);
1223 		}
1224 		mapped += len;
1225 	}
1226 
1227 	return (mapped);
1228 }
1229 
1230 static uint64_t
1231 amdvi_create_mapping(void *arg, vm_paddr_t gpa, vm_paddr_t hpa,
1232     uint64_t len)
1233 {
1234 	struct amdvi_domain *domain;
1235 
1236 	domain = (struct amdvi_domain *)arg;
1237 
1238 	if (domain->id && !domain->ptp) {
1239 		printf("ptp is NULL");
1240 		return (-1);
1241 	}
1242 
1243 	/*
1244 	 * If host domain is created w/o page table, skip IOMMU page
1245 	 * table set-up.
1246 	 */
1247 	if (domain->ptp)
1248 		return (amdvi_update_mapping(domain, gpa, hpa, len, true));
1249 	else
1250 		return (len);
1251 }
1252 
1253 static uint64_t
1254 amdvi_destroy_mapping(void *arg, vm_paddr_t gpa, uint64_t len)
1255 {
1256 	struct amdvi_domain *domain;
1257 
1258 	domain = (struct amdvi_domain *)arg;
1259 	/*
1260 	 * If host domain is created w/o page table, skip IOMMU page
1261 	 * table set-up.
1262 	 */
1263 	if (domain->ptp)
1264 		return (amdvi_update_mapping(domain, gpa, 0, len, false));
1265 	return
1266 	    (len);
1267 }
1268 
1269 static struct amdvi_softc *
1270 amdvi_find_iommu(uint16_t devid)
1271 {
1272 	struct amdvi_softc *softc;
1273 	int i;
1274 
1275 	for (i = 0; i < ivhd_count; i++) {
1276 		softc = device_get_softc(ivhd_devs[i]);
1277 		if ((devid >= softc->start_dev_rid) &&
1278 		    (devid <= softc->end_dev_rid))
1279 			return (softc);
1280 	}
1281 
1282 	/*
1283 	 * XXX: BIOS bug, device not in IVRS table, assume its from first IOMMU.
1284 	 */
1285 	printf("BIOS bug device(%d.%d.%d) doesn't have IVHD entry.\n",
1286 	    RID2PCI_STR(devid));
1287 
1288 	return (device_get_softc(ivhd_devs[0]));
1289 }
1290 
1291 /*
1292  * Set-up device table entry.
1293  * IOMMU spec Rev 2.0, section 3.2.2.2, some of the fields must
1294  * be set concurrently, e.g. read and write bits.
1295  */
1296 static void
1297 amdvi_set_dte(struct amdvi_domain *domain, uint16_t devid, bool enable)
1298 {
1299 	struct amdvi_softc *softc;
1300 	struct amdvi_dte* temp;
1301 
1302 	KASSERT(domain, ("domain is NULL for pci_rid:0x%x\n", devid));
1303 
1304 	softc = amdvi_find_iommu(devid);
1305 	KASSERT(softc, ("softc is NULL for pci_rid:0x%x\n", devid));
1306 
1307 	temp = &amdvi_dte[devid];
1308 
1309 #ifdef AMDVI_ATS_ENABLE
1310 	/* If IOMMU and device support IOTLB, enable it. */
1311 	if (amdvi_dev_support_iotlb(softc, devid) && softc->iotlb)
1312 		temp->iotlb_enable = 1;
1313 #endif
1314 
1315 	/* Avoid duplicate I/O faults. */
1316 	temp->sup_second_io_fault = 1;
1317 	temp->sup_all_io_fault = amdvi_disable_io_fault;
1318 
1319 	temp->dt_valid = 1;
1320 	temp->domain_id = domain->id;
1321 
1322 	if (enable) {
1323 		if (domain->ptp) {
1324 			temp->pt_base = vtophys(domain->ptp) >> 12;
1325 			temp->pt_level = amdvi_ptp_level;
1326 		}
1327 		/*
1328 		 * XXX: Page table valid[TV] bit must be set even if host domain
1329 		 * page tables are not enabled.
1330 		 */
1331 		temp->pt_valid = 1;
1332 		temp->read_allow = 1;
1333 		temp->write_allow = 1;
1334 	}
1335 }
1336 
1337 static void
1338 amdvi_inv_device(uint16_t devid)
1339 {
1340 	struct amdvi_softc *softc;
1341 
1342 	softc = amdvi_find_iommu(devid);
1343 	KASSERT(softc, ("softc is NULL"));
1344 
1345 	amdvi_cmd_inv_dte(softc, devid);
1346 #ifdef AMDVI_ATS_ENABLE
1347 	if (amdvi_dev_support_iotlb(softc, devid))
1348 		amdvi_cmd_inv_iotlb(softc, devid);
1349 #endif
1350 	amdvi_wait(softc);
1351 }
1352 
1353 static void
1354 amdvi_add_device(void *arg, uint16_t devid)
1355 {
1356 	struct amdvi_domain *domain;
1357 
1358 	domain = (struct amdvi_domain *)arg;
1359 	KASSERT(domain != NULL, ("domain is NULL"));
1360 #ifdef AMDVI_DEBUG_CMD
1361 	printf("Assigning device(%d.%d.%d) to domain:%d\n",
1362 	    RID2PCI_STR(devid), domain->id);
1363 #endif
1364 	amdvi_set_dte(domain, devid, true);
1365 	amdvi_inv_device(devid);
1366 }
1367 
1368 static void
1369 amdvi_remove_device(void *arg, uint16_t devid)
1370 {
1371 	struct amdvi_domain *domain;
1372 
1373 	domain = (struct amdvi_domain *)arg;
1374 #ifdef AMDVI_DEBUG_CMD
1375 	printf("Remove device(0x%x) from domain:%d\n",
1376 	       devid, domain->id);
1377 #endif
1378 	amdvi_set_dte(domain, devid, false);
1379 	amdvi_inv_device(devid);
1380 }
1381 
1382 static void
1383 amdvi_enable(void)
1384 {
1385 	struct amdvi_ctrl *ctrl;
1386 	struct amdvi_softc *softc;
1387 	uint64_t val;
1388 	int i;
1389 
1390 	for (i = 0; i < ivhd_count; i++) {
1391 		softc = device_get_softc(ivhd_devs[i]);
1392 		KASSERT(softc, ("softc is NULL\n"));
1393 		ctrl = softc->ctrl;
1394 		KASSERT(ctrl, ("ctrl is NULL\n"));
1395 
1396 		val = (	AMDVI_CTRL_EN 		|
1397 			AMDVI_CTRL_CMD 		|
1398 		    	AMDVI_CTRL_ELOG 	|
1399 		    	AMDVI_CTRL_ELOGINT 	|
1400 		    	AMDVI_CTRL_INV_TO_1S);
1401 
1402 		if (softc->ivhd_flag & IVHD_FLAG_COH)
1403 			val |= AMDVI_CTRL_COH;
1404 		if (softc->ivhd_flag & IVHD_FLAG_HTT)
1405 			val |= AMDVI_CTRL_HTT;
1406 		if (softc->ivhd_flag & IVHD_FLAG_RPPW)
1407 			val |= AMDVI_CTRL_RPPW;
1408 		if (softc->ivhd_flag & IVHD_FLAG_PPW)
1409 			val |= AMDVI_CTRL_PPW;
1410 		if (softc->ivhd_flag & IVHD_FLAG_ISOC)
1411 			val |= AMDVI_CTRL_ISOC;
1412 
1413 		ctrl->control = val;
1414 	}
1415 }
1416 
1417 static void
1418 amdvi_disable(void)
1419 {
1420 	struct amdvi_ctrl *ctrl;
1421 	struct amdvi_softc *softc;
1422 	int i;
1423 
1424 	for (i = 0; i < ivhd_count; i++) {
1425 		softc = device_get_softc(ivhd_devs[i]);
1426 		KASSERT(softc, ("softc is NULL\n"));
1427 		ctrl = softc->ctrl;
1428 		KASSERT(ctrl, ("ctrl is NULL\n"));
1429 
1430 		ctrl->control = 0;
1431 	}
1432 }
1433 
1434 static void
1435 amdvi_inv_tlb(void *arg)
1436 {
1437 	struct amdvi_domain *domain;
1438 
1439 	domain = (struct amdvi_domain *)arg;
1440 	KASSERT(domain, ("domain is NULL"));
1441 	amdvi_do_inv_domain(domain->id, false);
1442 }
1443 
1444 struct iommu_ops iommu_ops_amd = {
1445 	amdvi_init,
1446 	amdvi_cleanup,
1447 	amdvi_enable,
1448 	amdvi_disable,
1449 	amdvi_create_domain,
1450 	amdvi_destroy_domain,
1451 	amdvi_create_mapping,
1452 	amdvi_destroy_mapping,
1453 	amdvi_add_device,
1454 	amdvi_remove_device,
1455 	amdvi_inv_tlb
1456 };
1457