xref: /freebsd/usr.sbin/bhyve/pci_passthru.c (revision ee28ad11b7635715ed7d2f5815ace34c433992d1)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
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, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #endif
38 #include <sys/types.h>
39 #include <sys/mman.h>
40 #include <sys/pciio.h>
41 #include <sys/ioctl.h>
42 #include <sys/stat.h>
43 
44 #include <dev/io/iodev.h>
45 #include <dev/pci/pcireg.h>
46 
47 #include <vm/vm.h>
48 
49 #include <machine/iodev.h>
50 #include <machine/vm.h>
51 
52 #ifndef WITHOUT_CAPSICUM
53 #include <capsicum_helpers.h>
54 #endif
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <sysexits.h>
62 #include <unistd.h>
63 
64 #include <machine/vmm.h>
65 
66 #include "config.h"
67 #include "debug.h"
68 #include "mem.h"
69 #include "pci_passthru.h"
70 
71 #ifndef _PATH_DEVPCI
72 #define	_PATH_DEVPCI	"/dev/pci"
73 #endif
74 
75 #define	LEGACY_SUPPORT	1
76 
77 #define MSIX_TABLE_COUNT(ctrl) (((ctrl) & PCIM_MSIXCTRL_TABLE_SIZE) + 1)
78 #define MSIX_CAPLEN 12
79 
80 static int pcifd = -1;
81 
82 struct passthru_softc {
83 	struct pci_devinst *psc_pi;
84 	/* ROM is handled like a BAR */
85 	struct pcibar psc_bar[PCI_BARMAX_WITH_ROM + 1];
86 	struct {
87 		int		capoff;
88 		int		msgctrl;
89 		int		emulated;
90 	} psc_msi;
91 	struct {
92 		int		capoff;
93 	} psc_msix;
94 	struct pcisel psc_sel;
95 };
96 
97 static int
98 msi_caplen(int msgctrl)
99 {
100 	int len;
101 
102 	len = 10;		/* minimum length of msi capability */
103 
104 	if (msgctrl & PCIM_MSICTRL_64BIT)
105 		len += 4;
106 
107 #if 0
108 	/*
109 	 * Ignore the 'mask' and 'pending' bits in the MSI capability.
110 	 * We'll let the guest manipulate them directly.
111 	 */
112 	if (msgctrl & PCIM_MSICTRL_VECTOR)
113 		len += 10;
114 #endif
115 
116 	return (len);
117 }
118 
119 static int
120 pcifd_init() {
121 	pcifd = open(_PATH_DEVPCI, O_RDWR, 0);
122 	if (pcifd < 0) {
123 		warn("failed to open %s", _PATH_DEVPCI);
124 		return (1);
125 	}
126 
127 #ifndef WITHOUT_CAPSICUM
128 	cap_rights_t pcifd_rights;
129 	cap_rights_init(&pcifd_rights, CAP_IOCTL, CAP_READ, CAP_WRITE);
130 	if (caph_rights_limit(pcifd, &pcifd_rights) == -1)
131 		errx(EX_OSERR, "Unable to apply rights for sandbox");
132 
133 	const cap_ioctl_t pcifd_ioctls[] = { PCIOCREAD, PCIOCWRITE, PCIOCGETBAR,
134 		PCIOCBARIO, PCIOCBARMMAP };
135 	if (caph_ioctls_limit(pcifd, pcifd_ioctls, nitems(pcifd_ioctls)) == -1)
136 		errx(EX_OSERR, "Unable to apply rights for sandbox");
137 #endif
138 
139 	return (0);
140 }
141 
142 uint32_t
143 read_config(const struct pcisel *sel, long reg, int width)
144 {
145 	if (pcifd < 0 && pcifd_init()) {
146 		return (0);
147 	}
148 
149 	struct pci_io pi;
150 
151 	bzero(&pi, sizeof(pi));
152 	pi.pi_sel = *sel;
153 	pi.pi_reg = reg;
154 	pi.pi_width = width;
155 
156 	if (ioctl(pcifd, PCIOCREAD, &pi) < 0)
157 		return (0);				/* XXX */
158 	else
159 		return (pi.pi_data);
160 }
161 
162 void
163 write_config(const struct pcisel *sel, long reg, int width, uint32_t data)
164 {
165 	if (pcifd < 0 && pcifd_init()) {
166 		return;
167 	}
168 
169 	struct pci_io pi;
170 
171 	bzero(&pi, sizeof(pi));
172 	pi.pi_sel = *sel;
173 	pi.pi_reg = reg;
174 	pi.pi_width = width;
175 	pi.pi_data = data;
176 
177 	(void)ioctl(pcifd, PCIOCWRITE, &pi);		/* XXX */
178 }
179 
180 #ifdef LEGACY_SUPPORT
181 static int
182 passthru_add_msicap(struct pci_devinst *pi, int msgnum, int nextptr)
183 {
184 	int capoff, i;
185 	struct msicap msicap;
186 	u_char *capdata;
187 
188 	pci_populate_msicap(&msicap, msgnum, nextptr);
189 
190 	/*
191 	 * XXX
192 	 * Copy the msi capability structure in the last 16 bytes of the
193 	 * config space. This is wrong because it could shadow something
194 	 * useful to the device.
195 	 */
196 	capoff = 256 - roundup(sizeof(msicap), 4);
197 	capdata = (u_char *)&msicap;
198 	for (i = 0; i < sizeof(msicap); i++)
199 		pci_set_cfgdata8(pi, capoff + i, capdata[i]);
200 
201 	return (capoff);
202 }
203 #endif	/* LEGACY_SUPPORT */
204 
205 static int
206 cfginitmsi(struct passthru_softc *sc)
207 {
208 	int i, ptr, capptr, cap, sts, caplen, table_size;
209 	uint32_t u32;
210 	struct pcisel sel;
211 	struct pci_devinst *pi;
212 	struct msixcap msixcap;
213 	uint32_t *msixcap_ptr;
214 
215 	pi = sc->psc_pi;
216 	sel = sc->psc_sel;
217 
218 	/*
219 	 * Parse the capabilities and cache the location of the MSI
220 	 * and MSI-X capabilities.
221 	 */
222 	sts = read_config(&sel, PCIR_STATUS, 2);
223 	if (sts & PCIM_STATUS_CAPPRESENT) {
224 		ptr = read_config(&sel, PCIR_CAP_PTR, 1);
225 		while (ptr != 0 && ptr != 0xff) {
226 			cap = read_config(&sel, ptr + PCICAP_ID, 1);
227 			if (cap == PCIY_MSI) {
228 				/*
229 				 * Copy the MSI capability into the config
230 				 * space of the emulated pci device
231 				 */
232 				sc->psc_msi.capoff = ptr;
233 				sc->psc_msi.msgctrl = read_config(&sel,
234 								  ptr + 2, 2);
235 				sc->psc_msi.emulated = 0;
236 				caplen = msi_caplen(sc->psc_msi.msgctrl);
237 				capptr = ptr;
238 				while (caplen > 0) {
239 					u32 = read_config(&sel, capptr, 4);
240 					pci_set_cfgdata32(pi, capptr, u32);
241 					caplen -= 4;
242 					capptr += 4;
243 				}
244 			} else if (cap == PCIY_MSIX) {
245 				/*
246 				 * Copy the MSI-X capability
247 				 */
248 				sc->psc_msix.capoff = ptr;
249 				caplen = 12;
250 				msixcap_ptr = (uint32_t*) &msixcap;
251 				capptr = ptr;
252 				while (caplen > 0) {
253 					u32 = read_config(&sel, capptr, 4);
254 					*msixcap_ptr = u32;
255 					pci_set_cfgdata32(pi, capptr, u32);
256 					caplen -= 4;
257 					capptr += 4;
258 					msixcap_ptr++;
259 				}
260 			}
261 			ptr = read_config(&sel, ptr + PCICAP_NEXTPTR, 1);
262 		}
263 	}
264 
265 	if (sc->psc_msix.capoff != 0) {
266 		pi->pi_msix.pba_bar =
267 		    msixcap.pba_info & PCIM_MSIX_BIR_MASK;
268 		pi->pi_msix.pba_offset =
269 		    msixcap.pba_info & ~PCIM_MSIX_BIR_MASK;
270 		pi->pi_msix.table_bar =
271 		    msixcap.table_info & PCIM_MSIX_BIR_MASK;
272 		pi->pi_msix.table_offset =
273 		    msixcap.table_info & ~PCIM_MSIX_BIR_MASK;
274 		pi->pi_msix.table_count = MSIX_TABLE_COUNT(msixcap.msgctrl);
275 		pi->pi_msix.pba_size = PBA_SIZE(pi->pi_msix.table_count);
276 
277 		/* Allocate the emulated MSI-X table array */
278 		table_size = pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
279 		pi->pi_msix.table = calloc(1, table_size);
280 
281 		/* Mask all table entries */
282 		for (i = 0; i < pi->pi_msix.table_count; i++) {
283 			pi->pi_msix.table[i].vector_control |=
284 						PCIM_MSIX_VCTRL_MASK;
285 		}
286 	}
287 
288 #ifdef LEGACY_SUPPORT
289 	/*
290 	 * If the passthrough device does not support MSI then craft a
291 	 * MSI capability for it. We link the new MSI capability at the
292 	 * head of the list of capabilities.
293 	 */
294 	if ((sts & PCIM_STATUS_CAPPRESENT) != 0 && sc->psc_msi.capoff == 0) {
295 		int origptr, msiptr;
296 		origptr = read_config(&sel, PCIR_CAP_PTR, 1);
297 		msiptr = passthru_add_msicap(pi, 1, origptr);
298 		sc->psc_msi.capoff = msiptr;
299 		sc->psc_msi.msgctrl = pci_get_cfgdata16(pi, msiptr + 2);
300 		sc->psc_msi.emulated = 1;
301 		pci_set_cfgdata8(pi, PCIR_CAP_PTR, msiptr);
302 	}
303 #endif
304 
305 	/* Make sure one of the capabilities is present */
306 	if (sc->psc_msi.capoff == 0 && sc->psc_msix.capoff == 0)
307 		return (-1);
308 	else
309 		return (0);
310 }
311 
312 static uint64_t
313 msix_table_read(struct passthru_softc *sc, uint64_t offset, int size)
314 {
315 	struct pci_devinst *pi;
316 	struct msix_table_entry *entry;
317 	uint8_t *src8;
318 	uint16_t *src16;
319 	uint32_t *src32;
320 	uint64_t *src64;
321 	uint64_t data;
322 	size_t entry_offset;
323 	uint32_t table_offset;
324 	int index, table_count;
325 
326 	pi = sc->psc_pi;
327 
328 	table_offset = pi->pi_msix.table_offset;
329 	table_count = pi->pi_msix.table_count;
330 	if (offset < table_offset ||
331 	    offset >= table_offset + table_count * MSIX_TABLE_ENTRY_SIZE) {
332 		switch (size) {
333 		case 1:
334 			src8 = (uint8_t *)(pi->pi_msix.mapped_addr + offset);
335 			data = *src8;
336 			break;
337 		case 2:
338 			src16 = (uint16_t *)(pi->pi_msix.mapped_addr + offset);
339 			data = *src16;
340 			break;
341 		case 4:
342 			src32 = (uint32_t *)(pi->pi_msix.mapped_addr + offset);
343 			data = *src32;
344 			break;
345 		case 8:
346 			src64 = (uint64_t *)(pi->pi_msix.mapped_addr + offset);
347 			data = *src64;
348 			break;
349 		default:
350 			return (-1);
351 		}
352 		return (data);
353 	}
354 
355 	offset -= table_offset;
356 	index = offset / MSIX_TABLE_ENTRY_SIZE;
357 	assert(index < table_count);
358 
359 	entry = &pi->pi_msix.table[index];
360 	entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
361 
362 	switch (size) {
363 	case 1:
364 		src8 = (uint8_t *)((uint8_t *)entry + entry_offset);
365 		data = *src8;
366 		break;
367 	case 2:
368 		src16 = (uint16_t *)((uint8_t *)entry + entry_offset);
369 		data = *src16;
370 		break;
371 	case 4:
372 		src32 = (uint32_t *)((uint8_t *)entry + entry_offset);
373 		data = *src32;
374 		break;
375 	case 8:
376 		src64 = (uint64_t *)((uint8_t *)entry + entry_offset);
377 		data = *src64;
378 		break;
379 	default:
380 		return (-1);
381 	}
382 
383 	return (data);
384 }
385 
386 static void
387 msix_table_write(struct vmctx *ctx, int vcpu, struct passthru_softc *sc,
388 		 uint64_t offset, int size, uint64_t data)
389 {
390 	struct pci_devinst *pi;
391 	struct msix_table_entry *entry;
392 	uint8_t *dest8;
393 	uint16_t *dest16;
394 	uint32_t *dest32;
395 	uint64_t *dest64;
396 	size_t entry_offset;
397 	uint32_t table_offset, vector_control;
398 	int index, table_count;
399 
400 	pi = sc->psc_pi;
401 
402 	table_offset = pi->pi_msix.table_offset;
403 	table_count = pi->pi_msix.table_count;
404 	if (offset < table_offset ||
405 	    offset >= table_offset + table_count * MSIX_TABLE_ENTRY_SIZE) {
406 		switch (size) {
407 		case 1:
408 			dest8 = (uint8_t *)(pi->pi_msix.mapped_addr + offset);
409 			*dest8 = data;
410 			break;
411 		case 2:
412 			dest16 = (uint16_t *)(pi->pi_msix.mapped_addr + offset);
413 			*dest16 = data;
414 			break;
415 		case 4:
416 			dest32 = (uint32_t *)(pi->pi_msix.mapped_addr + offset);
417 			*dest32 = data;
418 			break;
419 		case 8:
420 			dest64 = (uint64_t *)(pi->pi_msix.mapped_addr + offset);
421 			*dest64 = data;
422 			break;
423 		}
424 		return;
425 	}
426 
427 	offset -= table_offset;
428 	index = offset / MSIX_TABLE_ENTRY_SIZE;
429 	assert(index < table_count);
430 
431 	entry = &pi->pi_msix.table[index];
432 	entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
433 
434 	/* Only 4 byte naturally-aligned writes are supported */
435 	assert(size == 4);
436 	assert(entry_offset % 4 == 0);
437 
438 	vector_control = entry->vector_control;
439 	dest32 = (uint32_t *)((void *)entry + entry_offset);
440 	*dest32 = data;
441 	/* If MSI-X hasn't been enabled, do nothing */
442 	if (pi->pi_msix.enabled) {
443 		/* If the entry is masked, don't set it up */
444 		if ((entry->vector_control & PCIM_MSIX_VCTRL_MASK) == 0 ||
445 		    (vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
446 			(void)vm_setup_pptdev_msix(ctx, vcpu,
447 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
448 			    sc->psc_sel.pc_func, index, entry->addr,
449 			    entry->msg_data, entry->vector_control);
450 		}
451 	}
452 }
453 
454 static int
455 init_msix_table(struct vmctx *ctx, struct passthru_softc *sc)
456 {
457 	struct pci_devinst *pi = sc->psc_pi;
458 	struct pci_bar_mmap pbm;
459 	int b, s, f;
460 	uint32_t table_size, table_offset;
461 
462 	assert(pci_msix_table_bar(pi) >= 0 && pci_msix_pba_bar(pi) >= 0);
463 
464 	b = sc->psc_sel.pc_bus;
465 	s = sc->psc_sel.pc_dev;
466 	f = sc->psc_sel.pc_func;
467 
468 	/*
469 	 * Map the region of the BAR containing the MSI-X table.  This is
470 	 * necessary for two reasons:
471 	 * 1. The PBA may reside in the first or last page containing the MSI-X
472 	 *    table.
473 	 * 2. While PCI devices are not supposed to use the page(s) containing
474 	 *    the MSI-X table for other purposes, some do in practice.
475 	 */
476 	memset(&pbm, 0, sizeof(pbm));
477 	pbm.pbm_sel = sc->psc_sel;
478 	pbm.pbm_flags = PCIIO_BAR_MMAP_RW;
479 	pbm.pbm_reg = PCIR_BAR(pi->pi_msix.table_bar);
480 	pbm.pbm_memattr = VM_MEMATTR_DEVICE;
481 
482 	if (ioctl(pcifd, PCIOCBARMMAP, &pbm) != 0) {
483 		warn("Failed to map MSI-X table BAR on %d/%d/%d", b, s, f);
484 		return (-1);
485 	}
486 	assert(pbm.pbm_bar_off == 0);
487 	pi->pi_msix.mapped_addr = (uint8_t *)(uintptr_t)pbm.pbm_map_base;
488 	pi->pi_msix.mapped_size = pbm.pbm_map_length;
489 
490 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
491 
492 	table_size = pi->pi_msix.table_offset - table_offset;
493 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
494 	table_size = roundup2(table_size, 4096);
495 
496 	/*
497 	 * Unmap any pages not containing the table, we do not need to emulate
498 	 * accesses to them.  Avoid releasing address space to help ensure that
499 	 * a buggy out-of-bounds access causes a crash.
500 	 */
501 	if (table_offset != 0)
502 		if (mprotect(pi->pi_msix.mapped_addr, table_offset,
503 		    PROT_NONE) != 0)
504 			warn("Failed to unmap MSI-X table BAR region");
505 	if (table_offset + table_size != pi->pi_msix.mapped_size)
506 		if (mprotect(
507 		    pi->pi_msix.mapped_addr + table_offset + table_size,
508 		    pi->pi_msix.mapped_size - (table_offset + table_size),
509 		    PROT_NONE) != 0)
510 			warn("Failed to unmap MSI-X table BAR region");
511 
512 	return (0);
513 }
514 
515 static int
516 cfginitbar(struct vmctx *ctx, struct passthru_softc *sc)
517 {
518 	int i, error;
519 	struct pci_devinst *pi;
520 	struct pci_bar_io bar;
521 	enum pcibar_type bartype;
522 	uint64_t base, size;
523 
524 	pi = sc->psc_pi;
525 
526 	/*
527 	 * Initialize BAR registers
528 	 */
529 	for (i = 0; i <= PCI_BARMAX; i++) {
530 		bzero(&bar, sizeof(bar));
531 		bar.pbi_sel = sc->psc_sel;
532 		bar.pbi_reg = PCIR_BAR(i);
533 
534 		if (ioctl(pcifd, PCIOCGETBAR, &bar) < 0)
535 			continue;
536 
537 		if (PCI_BAR_IO(bar.pbi_base)) {
538 			bartype = PCIBAR_IO;
539 			base = bar.pbi_base & PCIM_BAR_IO_BASE;
540 		} else {
541 			switch (bar.pbi_base & PCIM_BAR_MEM_TYPE) {
542 			case PCIM_BAR_MEM_64:
543 				bartype = PCIBAR_MEM64;
544 				break;
545 			default:
546 				bartype = PCIBAR_MEM32;
547 				break;
548 			}
549 			base = bar.pbi_base & PCIM_BAR_MEM_BASE;
550 		}
551 		size = bar.pbi_length;
552 
553 		if (bartype != PCIBAR_IO) {
554 			if (((base | size) & PAGE_MASK) != 0) {
555 				warnx("passthru device %d/%d/%d BAR %d: "
556 				    "base %#lx or size %#lx not page aligned\n",
557 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
558 				    sc->psc_sel.pc_func, i, base, size);
559 				return (-1);
560 			}
561 		}
562 
563 		/* Cache information about the "real" BAR */
564 		sc->psc_bar[i].type = bartype;
565 		sc->psc_bar[i].size = size;
566 		sc->psc_bar[i].addr = base;
567 		sc->psc_bar[i].lobits = 0;
568 
569 		/* Allocate the BAR in the guest I/O or MMIO space */
570 		error = pci_emul_alloc_bar(pi, i, bartype, size);
571 		if (error)
572 			return (-1);
573 
574 		/* Use same lobits as physical bar */
575 		uint8_t lobits = read_config(&sc->psc_sel, PCIR_BAR(i), 0x01);
576 		if (bartype == PCIBAR_MEM32 || bartype == PCIBAR_MEM64) {
577 			lobits &= ~PCIM_BAR_MEM_BASE;
578 		} else {
579 			lobits &= ~PCIM_BAR_IO_BASE;
580 		}
581 		sc->psc_bar[i].lobits = lobits;
582 		pi->pi_bar[i].lobits = lobits;
583 
584 		/*
585 		 * 64-bit BAR takes up two slots so skip the next one.
586 		 */
587 		if (bartype == PCIBAR_MEM64) {
588 			i++;
589 			assert(i <= PCI_BARMAX);
590 			sc->psc_bar[i].type = PCIBAR_MEMHI64;
591 		}
592 	}
593 	return (0);
594 }
595 
596 static int
597 cfginit(struct vmctx *ctx, struct pci_devinst *pi, int bus, int slot, int func)
598 {
599 	int error;
600 	struct passthru_softc *sc;
601 
602 	error = 1;
603 	sc = pi->pi_arg;
604 
605 	bzero(&sc->psc_sel, sizeof(struct pcisel));
606 	sc->psc_sel.pc_bus = bus;
607 	sc->psc_sel.pc_dev = slot;
608 	sc->psc_sel.pc_func = func;
609 
610 	if (cfginitmsi(sc) != 0) {
611 		warnx("failed to initialize MSI for PCI %d/%d/%d",
612 		    bus, slot, func);
613 		goto done;
614 	}
615 
616 	if (cfginitbar(ctx, sc) != 0) {
617 		warnx("failed to initialize BARs for PCI %d/%d/%d",
618 		    bus, slot, func);
619 		goto done;
620 	}
621 
622 	write_config(&sc->psc_sel, PCIR_COMMAND, 2,
623 	    pci_get_cfgdata16(pi, PCIR_COMMAND));
624 
625 	/*
626 	 * We need to do this after PCIR_COMMAND got possibly updated, e.g.,
627 	 * a BAR was enabled, as otherwise the PCIOCBARMMAP might fail on us.
628 	 */
629 	if (pci_msix_table_bar(pi) >= 0) {
630 		error = init_msix_table(ctx, sc);
631 		if (error != 0) {
632 			warnx(
633 			    "failed to initialize MSI-X table for PCI %d/%d/%d: %d",
634 			    bus, slot, func, error);
635 			goto done;
636 		}
637 	}
638 
639 	error = 0;				/* success */
640 done:
641 	return (error);
642 }
643 
644 static int
645 passthru_legacy_config(nvlist_t *nvl, const char *opts)
646 {
647 	char value[16];
648 	int bus, slot, func;
649 
650 	if (opts == NULL)
651 		return (0);
652 
653 	if (sscanf(opts, "%d/%d/%d", &bus, &slot, &func) != 3) {
654 		EPRINTLN("passthru: invalid options \"%s\"", opts);
655 		return (-1);
656 	}
657 
658 	snprintf(value, sizeof(value), "%d", bus);
659 	set_config_value_node(nvl, "bus", value);
660 	snprintf(value, sizeof(value), "%d", slot);
661 	set_config_value_node(nvl, "slot", value);
662 	snprintf(value, sizeof(value), "%d", func);
663 	set_config_value_node(nvl, "func", value);
664 
665 	opts = strchr(opts, ',');
666 	if (opts == NULL) {
667 		return (0);
668 	}
669 
670 	return pci_parse_legacy_config(nvl, opts + 1);
671 }
672 
673 static int
674 passthru_init_rom(struct vmctx *const ctx, struct passthru_softc *const sc,
675     const char *const romfile)
676 {
677 	if (romfile == NULL) {
678 		return (0);
679 	}
680 
681 	const int fd = open(romfile, O_RDONLY);
682 	if (fd < 0) {
683 		warnx("%s: can't open romfile \"%s\"", __func__, romfile);
684 		return (-1);
685 	}
686 
687 	struct stat sbuf;
688 	if (fstat(fd, &sbuf) < 0) {
689 		warnx("%s: can't fstat romfile \"%s\"", __func__, romfile);
690 		close(fd);
691 		return (-1);
692 	}
693 	const uint64_t rom_size = sbuf.st_size;
694 
695 	void *const rom_data = mmap(NULL, rom_size, PROT_READ, MAP_SHARED, fd,
696 	    0);
697 	if (rom_data == MAP_FAILED) {
698 		warnx("%s: unable to mmap romfile \"%s\" (%d)", __func__,
699 		    romfile, errno);
700 		close(fd);
701 		return (-1);
702 	}
703 
704 	void *rom_addr;
705 	int error = pci_emul_alloc_rom(sc->psc_pi, rom_size, &rom_addr);
706 	if (error) {
707 		warnx("%s: failed to alloc rom segment", __func__);
708 		munmap(rom_data, rom_size);
709 		close(fd);
710 		return (error);
711 	}
712 	memcpy(rom_addr, rom_data, rom_size);
713 
714 	sc->psc_bar[PCI_ROM_IDX].type = PCIBAR_ROM;
715 	sc->psc_bar[PCI_ROM_IDX].addr = (uint64_t)rom_addr;
716 	sc->psc_bar[PCI_ROM_IDX].size = rom_size;
717 
718 	munmap(rom_data, rom_size);
719 	close(fd);
720 
721 	return (0);
722 }
723 
724 static int
725 passthru_init(struct vmctx *ctx, struct pci_devinst *pi, nvlist_t *nvl)
726 {
727 	int bus, slot, func, error, memflags;
728 	struct passthru_softc *sc;
729 	const char *value;
730 
731 	sc = NULL;
732 	error = 1;
733 
734 	memflags = vm_get_memflags(ctx);
735 	if (!(memflags & VM_MEM_F_WIRED)) {
736 		warnx("passthru requires guest memory to be wired");
737 		return (error);
738 	}
739 
740 	if (pcifd < 0 && pcifd_init()) {
741 		return (error);
742 	}
743 
744 #define GET_INT_CONFIG(var, name) do {					\
745 	value = get_config_value_node(nvl, name);			\
746 	if (value == NULL) {						\
747 		EPRINTLN("passthru: missing required %s setting", name); \
748 		return (error);						\
749 	}								\
750 	var = atoi(value);						\
751 } while (0)
752 
753 	GET_INT_CONFIG(bus, "bus");
754 	GET_INT_CONFIG(slot, "slot");
755 	GET_INT_CONFIG(func, "func");
756 
757 	if (vm_assign_pptdev(ctx, bus, slot, func) != 0) {
758 		warnx("PCI device at %d/%d/%d is not using the ppt(4) driver",
759 		    bus, slot, func);
760 		goto done;
761 	}
762 
763 	sc = calloc(1, sizeof(struct passthru_softc));
764 
765 	pi->pi_arg = sc;
766 	sc->psc_pi = pi;
767 
768 	/* initialize config space */
769 	if ((error = cfginit(ctx, pi, bus, slot, func)) != 0)
770 		goto done;
771 
772 	/* initialize ROM */
773 	if ((error = passthru_init_rom(ctx, sc,
774             get_config_value_node(nvl, "rom"))) != 0)
775 		goto done;
776 
777 	error = 0;		/* success */
778 done:
779 	if (error) {
780 		free(sc);
781 		vm_unassign_pptdev(ctx, bus, slot, func);
782 	}
783 	return (error);
784 }
785 
786 static int
787 bar_access(int coff)
788 {
789 	if ((coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1)) ||
790 	    coff == PCIR_BIOS)
791 		return (1);
792 	else
793 		return (0);
794 }
795 
796 static int
797 msicap_access(struct passthru_softc *sc, int coff)
798 {
799 	int caplen;
800 
801 	if (sc->psc_msi.capoff == 0)
802 		return (0);
803 
804 	caplen = msi_caplen(sc->psc_msi.msgctrl);
805 
806 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
807 		return (1);
808 	else
809 		return (0);
810 }
811 
812 static int
813 msixcap_access(struct passthru_softc *sc, int coff)
814 {
815 	if (sc->psc_msix.capoff == 0)
816 		return (0);
817 
818 	return (coff >= sc->psc_msix.capoff &&
819 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
820 }
821 
822 static int
823 passthru_cfgread(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
824 		 int coff, int bytes, uint32_t *rv)
825 {
826 	struct passthru_softc *sc;
827 
828 	sc = pi->pi_arg;
829 
830 	/*
831 	 * PCI BARs and MSI capability is emulated.
832 	 */
833 	if (bar_access(coff) || msicap_access(sc, coff) ||
834 	    msixcap_access(sc, coff))
835 		return (-1);
836 
837 #ifdef LEGACY_SUPPORT
838 	/*
839 	 * Emulate PCIR_CAP_PTR if this device does not support MSI capability
840 	 * natively.
841 	 */
842 	if (sc->psc_msi.emulated) {
843 		if (coff >= PCIR_CAP_PTR && coff < PCIR_CAP_PTR + 4)
844 			return (-1);
845 	}
846 #endif
847 
848 	/*
849 	 * Emulate the command register.  If a single read reads both the
850 	 * command and status registers, read the status register from the
851 	 * device's config space.
852 	 */
853 	if (coff == PCIR_COMMAND) {
854 		if (bytes <= 2)
855 			return (-1);
856 		*rv = read_config(&sc->psc_sel, PCIR_STATUS, 2) << 16 |
857 		    pci_get_cfgdata16(pi, PCIR_COMMAND);
858 		return (0);
859 	}
860 
861 	/* Everything else just read from the device's config space */
862 	*rv = read_config(&sc->psc_sel, coff, bytes);
863 
864 	return (0);
865 }
866 
867 static int
868 passthru_cfgwrite(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
869 		  int coff, int bytes, uint32_t val)
870 {
871 	int error, msix_table_entries, i;
872 	struct passthru_softc *sc;
873 	uint16_t cmd_old;
874 
875 	sc = pi->pi_arg;
876 
877 	/*
878 	 * PCI BARs are emulated
879 	 */
880 	if (bar_access(coff))
881 		return (-1);
882 
883 	/*
884 	 * MSI capability is emulated
885 	 */
886 	if (msicap_access(sc, coff)) {
887 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
888 		    PCIY_MSI);
889 		error = vm_setup_pptdev_msi(ctx, vcpu, sc->psc_sel.pc_bus,
890 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
891 			pi->pi_msi.addr, pi->pi_msi.msg_data,
892 			pi->pi_msi.maxmsgnum);
893 		if (error != 0)
894 			err(1, "vm_setup_pptdev_msi");
895 		return (0);
896 	}
897 
898 	if (msixcap_access(sc, coff)) {
899 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
900 		    PCIY_MSIX);
901 		if (pi->pi_msix.enabled) {
902 			msix_table_entries = pi->pi_msix.table_count;
903 			for (i = 0; i < msix_table_entries; i++) {
904 				error = vm_setup_pptdev_msix(ctx, vcpu,
905 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
906 				    sc->psc_sel.pc_func, i,
907 				    pi->pi_msix.table[i].addr,
908 				    pi->pi_msix.table[i].msg_data,
909 				    pi->pi_msix.table[i].vector_control);
910 
911 				if (error)
912 					err(1, "vm_setup_pptdev_msix");
913 			}
914 		} else {
915 			error = vm_disable_pptdev_msix(ctx, sc->psc_sel.pc_bus,
916 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
917 			if (error)
918 				err(1, "vm_disable_pptdev_msix");
919 		}
920 		return (0);
921 	}
922 
923 #ifdef LEGACY_SUPPORT
924 	/*
925 	 * If this device does not support MSI natively then we cannot let
926 	 * the guest disable legacy interrupts from the device. It is the
927 	 * legacy interrupt that is triggering the virtual MSI to the guest.
928 	 */
929 	if (sc->psc_msi.emulated && pci_msi_enabled(pi)) {
930 		if (coff == PCIR_COMMAND && bytes == 2)
931 			val &= ~PCIM_CMD_INTxDIS;
932 	}
933 #endif
934 
935 	write_config(&sc->psc_sel, coff, bytes, val);
936 	if (coff == PCIR_COMMAND) {
937 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
938 		if (bytes == 1)
939 			pci_set_cfgdata8(pi, PCIR_COMMAND, val);
940 		else if (bytes == 2)
941 			pci_set_cfgdata16(pi, PCIR_COMMAND, val);
942 		pci_emul_cmd_changed(pi, cmd_old);
943 	}
944 
945 	return (0);
946 }
947 
948 static void
949 passthru_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
950 	       uint64_t offset, int size, uint64_t value)
951 {
952 	struct passthru_softc *sc;
953 	struct pci_bar_ioreq pio;
954 
955 	sc = pi->pi_arg;
956 
957 	if (baridx == pci_msix_table_bar(pi)) {
958 		msix_table_write(ctx, vcpu, sc, offset, size, value);
959 	} else {
960 		assert(pi->pi_bar[baridx].type == PCIBAR_IO);
961 		assert(size == 1 || size == 2 || size == 4);
962 		assert(offset <= UINT32_MAX && offset + size <= UINT32_MAX);
963 
964 		bzero(&pio, sizeof(pio));
965 		pio.pbi_sel = sc->psc_sel;
966 		pio.pbi_op = PCIBARIO_WRITE;
967 		pio.pbi_bar = baridx;
968 		pio.pbi_offset = (uint32_t)offset;
969 		pio.pbi_width = size;
970 		pio.pbi_value = (uint32_t)value;
971 
972 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
973 	}
974 }
975 
976 static uint64_t
977 passthru_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
978 	      uint64_t offset, int size)
979 {
980 	struct passthru_softc *sc;
981 	struct pci_bar_ioreq pio;
982 	uint64_t val;
983 
984 	sc = pi->pi_arg;
985 
986 	if (baridx == pci_msix_table_bar(pi)) {
987 		val = msix_table_read(sc, offset, size);
988 	} else {
989 		assert(pi->pi_bar[baridx].type == PCIBAR_IO);
990 		assert(size == 1 || size == 2 || size == 4);
991 		assert(offset <= UINT32_MAX && offset + size <= UINT32_MAX);
992 
993 		bzero(&pio, sizeof(pio));
994 		pio.pbi_sel = sc->psc_sel;
995 		pio.pbi_op = PCIBARIO_READ;
996 		pio.pbi_bar = baridx;
997 		pio.pbi_offset = (uint32_t)offset;
998 		pio.pbi_width = size;
999 
1000 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1001 
1002 		val = pio.pbi_value;
1003 	}
1004 
1005 	return (val);
1006 }
1007 
1008 static void
1009 passthru_msix_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1010 		   int enabled, uint64_t address)
1011 {
1012 	struct passthru_softc *sc;
1013 	size_t remaining;
1014 	uint32_t table_size, table_offset;
1015 
1016 	sc = pi->pi_arg;
1017 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
1018 	if (table_offset > 0) {
1019 		if (!enabled) {
1020 			if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1021 						 sc->psc_sel.pc_dev,
1022 						 sc->psc_sel.pc_func, address,
1023 						 table_offset) != 0)
1024 				warnx("pci_passthru: unmap_pptdev_mmio failed");
1025 		} else {
1026 			if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1027 					       sc->psc_sel.pc_dev,
1028 					       sc->psc_sel.pc_func, address,
1029 					       table_offset,
1030 					       sc->psc_bar[baridx].addr) != 0)
1031 				warnx("pci_passthru: map_pptdev_mmio failed");
1032 		}
1033 	}
1034 	table_size = pi->pi_msix.table_offset - table_offset;
1035 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
1036 	table_size = roundup2(table_size, 4096);
1037 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
1038 	if (remaining > 0) {
1039 		address += table_offset + table_size;
1040 		if (!enabled) {
1041 			if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1042 						 sc->psc_sel.pc_dev,
1043 						 sc->psc_sel.pc_func, address,
1044 						 remaining) != 0)
1045 				warnx("pci_passthru: unmap_pptdev_mmio failed");
1046 		} else {
1047 			if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1048 					       sc->psc_sel.pc_dev,
1049 					       sc->psc_sel.pc_func, address,
1050 					       remaining,
1051 					       sc->psc_bar[baridx].addr +
1052 					       table_offset + table_size) != 0)
1053 				warnx("pci_passthru: map_pptdev_mmio failed");
1054 		}
1055 	}
1056 }
1057 
1058 static void
1059 passthru_mmio_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1060 		   int enabled, uint64_t address)
1061 {
1062 	struct passthru_softc *sc;
1063 
1064 	sc = pi->pi_arg;
1065 	if (!enabled) {
1066 		if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1067 					 sc->psc_sel.pc_dev,
1068 					 sc->psc_sel.pc_func, address,
1069 					 sc->psc_bar[baridx].size) != 0)
1070 			warnx("pci_passthru: unmap_pptdev_mmio failed");
1071 	} else {
1072 		if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1073 				       sc->psc_sel.pc_dev,
1074 				       sc->psc_sel.pc_func, address,
1075 				       sc->psc_bar[baridx].size,
1076 				       sc->psc_bar[baridx].addr) != 0)
1077 			warnx("pci_passthru: map_pptdev_mmio failed");
1078 	}
1079 }
1080 
1081 static void
1082 passthru_addr_rom(struct pci_devinst *const pi, const int idx,
1083     const int enabled)
1084 {
1085 	const uint64_t addr = pi->pi_bar[idx].addr;
1086 	const uint64_t size = pi->pi_bar[idx].size;
1087 
1088 	if (!enabled) {
1089 		if (vm_munmap_memseg(pi->pi_vmctx, addr, size) != 0) {
1090 			errx(4, "%s: munmap_memseg @ [%016lx - %016lx] failed",
1091 			    __func__, addr, addr + size);
1092 		}
1093 
1094 	} else {
1095 		if (vm_mmap_memseg(pi->pi_vmctx, addr, VM_PCIROM,
1096 			pi->pi_romoffset, size, PROT_READ | PROT_EXEC) != 0) {
1097 			errx(4, "%s: mnmap_memseg @ [%016lx - %016lx]  failed",
1098 			    __func__, addr, addr + size);
1099 		}
1100 	}
1101 }
1102 
1103 static void
1104 passthru_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1105     int enabled, uint64_t address)
1106 {
1107 	switch (pi->pi_bar[baridx].type) {
1108 	case PCIBAR_IO:
1109 		/* IO BARs are emulated */
1110 		break;
1111 	case PCIBAR_ROM:
1112 		passthru_addr_rom(pi, baridx, enabled);
1113 		break;
1114 	case PCIBAR_MEM32:
1115 	case PCIBAR_MEM64:
1116 		if (baridx == pci_msix_table_bar(pi))
1117 			passthru_msix_addr(ctx, pi, baridx, enabled, address);
1118 		else
1119 			passthru_mmio_addr(ctx, pi, baridx, enabled, address);
1120 		break;
1121 	default:
1122 		errx(4, "%s: invalid BAR type %d", __func__,
1123 		    pi->pi_bar[baridx].type);
1124 	}
1125 }
1126 
1127 struct pci_devemu passthru = {
1128 	.pe_emu		= "passthru",
1129 	.pe_init	= passthru_init,
1130 	.pe_legacy_config = passthru_legacy_config,
1131 	.pe_cfgwrite	= passthru_cfgwrite,
1132 	.pe_cfgread	= passthru_cfgread,
1133 	.pe_barwrite 	= passthru_write,
1134 	.pe_barread    	= passthru_read,
1135 	.pe_baraddr	= passthru_addr,
1136 };
1137 PCI_EMUL_SET(passthru);
1138