xref: /freebsd/usr.sbin/bhyve/pci_passthru.c (revision b3b50e64d7e4c28bd0fd6323591ed811633826e4)
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 	return (pci_parse_legacy_config(nvl, strchr(opts, ',')));
666 }
667 
668 static int
669 passthru_init_rom(struct vmctx *const ctx, struct passthru_softc *const sc,
670     const char *const romfile)
671 {
672 	if (romfile == NULL) {
673 		return (0);
674 	}
675 
676 	const int fd = open(romfile, O_RDONLY);
677 	if (fd < 0) {
678 		warnx("%s: can't open romfile \"%s\"", __func__, romfile);
679 		return (-1);
680 	}
681 
682 	struct stat sbuf;
683 	if (fstat(fd, &sbuf) < 0) {
684 		warnx("%s: can't fstat romfile \"%s\"", __func__, romfile);
685 		close(fd);
686 		return (-1);
687 	}
688 	const uint64_t rom_size = sbuf.st_size;
689 
690 	void *const rom_data = mmap(NULL, rom_size, PROT_READ, MAP_SHARED, fd,
691 	    0);
692 	if (rom_data == MAP_FAILED) {
693 		warnx("%s: unable to mmap romfile \"%s\" (%d)", __func__,
694 		    romfile, errno);
695 		close(fd);
696 		return (-1);
697 	}
698 
699 	void *rom_addr;
700 	int error = pci_emul_alloc_rom(sc->psc_pi, rom_size, &rom_addr);
701 	if (error) {
702 		warnx("%s: failed to alloc rom segment", __func__);
703 		munmap(rom_data, rom_size);
704 		close(fd);
705 		return (error);
706 	}
707 	memcpy(rom_addr, rom_data, rom_size);
708 
709 	sc->psc_bar[PCI_ROM_IDX].type = PCIBAR_ROM;
710 	sc->psc_bar[PCI_ROM_IDX].addr = (uint64_t)rom_addr;
711 	sc->psc_bar[PCI_ROM_IDX].size = rom_size;
712 
713 	munmap(rom_data, rom_size);
714 	close(fd);
715 
716 	return (0);
717 }
718 
719 static int
720 passthru_init(struct vmctx *ctx, struct pci_devinst *pi, nvlist_t *nvl)
721 {
722 	int bus, slot, func, error, memflags;
723 	struct passthru_softc *sc;
724 	const char *value;
725 
726 	sc = NULL;
727 	error = 1;
728 
729 	memflags = vm_get_memflags(ctx);
730 	if (!(memflags & VM_MEM_F_WIRED)) {
731 		warnx("passthru requires guest memory to be wired");
732 		return (error);
733 	}
734 
735 	if (pcifd < 0 && pcifd_init()) {
736 		return (error);
737 	}
738 
739 #define GET_INT_CONFIG(var, name) do {					\
740 	value = get_config_value_node(nvl, name);			\
741 	if (value == NULL) {						\
742 		EPRINTLN("passthru: missing required %s setting", name); \
743 		return (error);						\
744 	}								\
745 	var = atoi(value);						\
746 } while (0)
747 
748 	GET_INT_CONFIG(bus, "bus");
749 	GET_INT_CONFIG(slot, "slot");
750 	GET_INT_CONFIG(func, "func");
751 
752 	if (vm_assign_pptdev(ctx, bus, slot, func) != 0) {
753 		warnx("PCI device at %d/%d/%d is not using the ppt(4) driver",
754 		    bus, slot, func);
755 		goto done;
756 	}
757 
758 	sc = calloc(1, sizeof(struct passthru_softc));
759 
760 	pi->pi_arg = sc;
761 	sc->psc_pi = pi;
762 
763 	/* initialize config space */
764 	if ((error = cfginit(ctx, pi, bus, slot, func)) != 0)
765 		goto done;
766 
767 	/* initialize ROM */
768 	if ((error = passthru_init_rom(ctx, sc,
769             get_config_value_node(nvl, "rom"))) != 0)
770 		goto done;
771 
772 	error = 0;		/* success */
773 done:
774 	if (error) {
775 		free(sc);
776 		vm_unassign_pptdev(ctx, bus, slot, func);
777 	}
778 	return (error);
779 }
780 
781 static int
782 bar_access(int coff)
783 {
784 	if ((coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1)) ||
785 	    coff == PCIR_BIOS)
786 		return (1);
787 	else
788 		return (0);
789 }
790 
791 static int
792 msicap_access(struct passthru_softc *sc, int coff)
793 {
794 	int caplen;
795 
796 	if (sc->psc_msi.capoff == 0)
797 		return (0);
798 
799 	caplen = msi_caplen(sc->psc_msi.msgctrl);
800 
801 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
802 		return (1);
803 	else
804 		return (0);
805 }
806 
807 static int
808 msixcap_access(struct passthru_softc *sc, int coff)
809 {
810 	if (sc->psc_msix.capoff == 0)
811 		return (0);
812 
813 	return (coff >= sc->psc_msix.capoff &&
814 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
815 }
816 
817 static int
818 passthru_cfgread(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
819 		 int coff, int bytes, uint32_t *rv)
820 {
821 	struct passthru_softc *sc;
822 
823 	sc = pi->pi_arg;
824 
825 	/*
826 	 * PCI BARs and MSI capability is emulated.
827 	 */
828 	if (bar_access(coff) || msicap_access(sc, coff) ||
829 	    msixcap_access(sc, coff))
830 		return (-1);
831 
832 #ifdef LEGACY_SUPPORT
833 	/*
834 	 * Emulate PCIR_CAP_PTR if this device does not support MSI capability
835 	 * natively.
836 	 */
837 	if (sc->psc_msi.emulated) {
838 		if (coff >= PCIR_CAP_PTR && coff < PCIR_CAP_PTR + 4)
839 			return (-1);
840 	}
841 #endif
842 
843 	/*
844 	 * Emulate the command register.  If a single read reads both the
845 	 * command and status registers, read the status register from the
846 	 * device's config space.
847 	 */
848 	if (coff == PCIR_COMMAND) {
849 		if (bytes <= 2)
850 			return (-1);
851 		*rv = read_config(&sc->psc_sel, PCIR_STATUS, 2) << 16 |
852 		    pci_get_cfgdata16(pi, PCIR_COMMAND);
853 		return (0);
854 	}
855 
856 	/* Everything else just read from the device's config space */
857 	*rv = read_config(&sc->psc_sel, coff, bytes);
858 
859 	return (0);
860 }
861 
862 static int
863 passthru_cfgwrite(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
864 		  int coff, int bytes, uint32_t val)
865 {
866 	int error, msix_table_entries, i;
867 	struct passthru_softc *sc;
868 	uint16_t cmd_old;
869 
870 	sc = pi->pi_arg;
871 
872 	/*
873 	 * PCI BARs are emulated
874 	 */
875 	if (bar_access(coff))
876 		return (-1);
877 
878 	/*
879 	 * MSI capability is emulated
880 	 */
881 	if (msicap_access(sc, coff)) {
882 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
883 		    PCIY_MSI);
884 		error = vm_setup_pptdev_msi(ctx, vcpu, sc->psc_sel.pc_bus,
885 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
886 			pi->pi_msi.addr, pi->pi_msi.msg_data,
887 			pi->pi_msi.maxmsgnum);
888 		if (error != 0)
889 			err(1, "vm_setup_pptdev_msi");
890 		return (0);
891 	}
892 
893 	if (msixcap_access(sc, coff)) {
894 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
895 		    PCIY_MSIX);
896 		if (pi->pi_msix.enabled) {
897 			msix_table_entries = pi->pi_msix.table_count;
898 			for (i = 0; i < msix_table_entries; i++) {
899 				error = vm_setup_pptdev_msix(ctx, vcpu,
900 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
901 				    sc->psc_sel.pc_func, i,
902 				    pi->pi_msix.table[i].addr,
903 				    pi->pi_msix.table[i].msg_data,
904 				    pi->pi_msix.table[i].vector_control);
905 
906 				if (error)
907 					err(1, "vm_setup_pptdev_msix");
908 			}
909 		} else {
910 			error = vm_disable_pptdev_msix(ctx, sc->psc_sel.pc_bus,
911 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
912 			if (error)
913 				err(1, "vm_disable_pptdev_msix");
914 		}
915 		return (0);
916 	}
917 
918 #ifdef LEGACY_SUPPORT
919 	/*
920 	 * If this device does not support MSI natively then we cannot let
921 	 * the guest disable legacy interrupts from the device. It is the
922 	 * legacy interrupt that is triggering the virtual MSI to the guest.
923 	 */
924 	if (sc->psc_msi.emulated && pci_msi_enabled(pi)) {
925 		if (coff == PCIR_COMMAND && bytes == 2)
926 			val &= ~PCIM_CMD_INTxDIS;
927 	}
928 #endif
929 
930 	write_config(&sc->psc_sel, coff, bytes, val);
931 	if (coff == PCIR_COMMAND) {
932 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
933 		if (bytes == 1)
934 			pci_set_cfgdata8(pi, PCIR_COMMAND, val);
935 		else if (bytes == 2)
936 			pci_set_cfgdata16(pi, PCIR_COMMAND, val);
937 		pci_emul_cmd_changed(pi, cmd_old);
938 	}
939 
940 	return (0);
941 }
942 
943 static void
944 passthru_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
945 	       uint64_t offset, int size, uint64_t value)
946 {
947 	struct passthru_softc *sc;
948 	struct pci_bar_ioreq pio;
949 
950 	sc = pi->pi_arg;
951 
952 	if (baridx == pci_msix_table_bar(pi)) {
953 		msix_table_write(ctx, vcpu, sc, offset, size, value);
954 	} else {
955 		assert(pi->pi_bar[baridx].type == PCIBAR_IO);
956 		assert(size == 1 || size == 2 || size == 4);
957 		assert(offset <= UINT32_MAX && offset + size <= UINT32_MAX);
958 
959 		bzero(&pio, sizeof(pio));
960 		pio.pbi_sel = sc->psc_sel;
961 		pio.pbi_op = PCIBARIO_WRITE;
962 		pio.pbi_bar = baridx;
963 		pio.pbi_offset = (uint32_t)offset;
964 		pio.pbi_width = size;
965 		pio.pbi_value = (uint32_t)value;
966 
967 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
968 	}
969 }
970 
971 static uint64_t
972 passthru_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
973 	      uint64_t offset, int size)
974 {
975 	struct passthru_softc *sc;
976 	struct pci_bar_ioreq pio;
977 	uint64_t val;
978 
979 	sc = pi->pi_arg;
980 
981 	if (baridx == pci_msix_table_bar(pi)) {
982 		val = msix_table_read(sc, offset, size);
983 	} else {
984 		assert(pi->pi_bar[baridx].type == PCIBAR_IO);
985 		assert(size == 1 || size == 2 || size == 4);
986 		assert(offset <= UINT32_MAX && offset + size <= UINT32_MAX);
987 
988 		bzero(&pio, sizeof(pio));
989 		pio.pbi_sel = sc->psc_sel;
990 		pio.pbi_op = PCIBARIO_READ;
991 		pio.pbi_bar = baridx;
992 		pio.pbi_offset = (uint32_t)offset;
993 		pio.pbi_width = size;
994 
995 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
996 
997 		val = pio.pbi_value;
998 	}
999 
1000 	return (val);
1001 }
1002 
1003 static void
1004 passthru_msix_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1005 		   int enabled, uint64_t address)
1006 {
1007 	struct passthru_softc *sc;
1008 	size_t remaining;
1009 	uint32_t table_size, table_offset;
1010 
1011 	sc = pi->pi_arg;
1012 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
1013 	if (table_offset > 0) {
1014 		if (!enabled) {
1015 			if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1016 						 sc->psc_sel.pc_dev,
1017 						 sc->psc_sel.pc_func, address,
1018 						 table_offset) != 0)
1019 				warnx("pci_passthru: unmap_pptdev_mmio failed");
1020 		} else {
1021 			if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1022 					       sc->psc_sel.pc_dev,
1023 					       sc->psc_sel.pc_func, address,
1024 					       table_offset,
1025 					       sc->psc_bar[baridx].addr) != 0)
1026 				warnx("pci_passthru: map_pptdev_mmio failed");
1027 		}
1028 	}
1029 	table_size = pi->pi_msix.table_offset - table_offset;
1030 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
1031 	table_size = roundup2(table_size, 4096);
1032 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
1033 	if (remaining > 0) {
1034 		address += table_offset + table_size;
1035 		if (!enabled) {
1036 			if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1037 						 sc->psc_sel.pc_dev,
1038 						 sc->psc_sel.pc_func, address,
1039 						 remaining) != 0)
1040 				warnx("pci_passthru: unmap_pptdev_mmio failed");
1041 		} else {
1042 			if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1043 					       sc->psc_sel.pc_dev,
1044 					       sc->psc_sel.pc_func, address,
1045 					       remaining,
1046 					       sc->psc_bar[baridx].addr +
1047 					       table_offset + table_size) != 0)
1048 				warnx("pci_passthru: map_pptdev_mmio failed");
1049 		}
1050 	}
1051 }
1052 
1053 static void
1054 passthru_mmio_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1055 		   int enabled, uint64_t address)
1056 {
1057 	struct passthru_softc *sc;
1058 
1059 	sc = pi->pi_arg;
1060 	if (!enabled) {
1061 		if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1062 					 sc->psc_sel.pc_dev,
1063 					 sc->psc_sel.pc_func, address,
1064 					 sc->psc_bar[baridx].size) != 0)
1065 			warnx("pci_passthru: unmap_pptdev_mmio failed");
1066 	} else {
1067 		if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
1068 				       sc->psc_sel.pc_dev,
1069 				       sc->psc_sel.pc_func, address,
1070 				       sc->psc_bar[baridx].size,
1071 				       sc->psc_bar[baridx].addr) != 0)
1072 			warnx("pci_passthru: map_pptdev_mmio failed");
1073 	}
1074 }
1075 
1076 static void
1077 passthru_addr_rom(struct pci_devinst *const pi, const int idx,
1078     const int enabled)
1079 {
1080 	const uint64_t addr = pi->pi_bar[idx].addr;
1081 	const uint64_t size = pi->pi_bar[idx].size;
1082 
1083 	if (!enabled) {
1084 		if (vm_munmap_memseg(pi->pi_vmctx, addr, size) != 0) {
1085 			errx(4, "%s: munmap_memseg @ [%016lx - %016lx] failed",
1086 			    __func__, addr, addr + size);
1087 		}
1088 
1089 	} else {
1090 		if (vm_mmap_memseg(pi->pi_vmctx, addr, VM_PCIROM,
1091 			pi->pi_romoffset, size, PROT_READ | PROT_EXEC) != 0) {
1092 			errx(4, "%s: mnmap_memseg @ [%016lx - %016lx]  failed",
1093 			    __func__, addr, addr + size);
1094 		}
1095 	}
1096 }
1097 
1098 static void
1099 passthru_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1100     int enabled, uint64_t address)
1101 {
1102 	switch (pi->pi_bar[baridx].type) {
1103 	case PCIBAR_IO:
1104 		/* IO BARs are emulated */
1105 		break;
1106 	case PCIBAR_ROM:
1107 		passthru_addr_rom(pi, baridx, enabled);
1108 		break;
1109 	case PCIBAR_MEM32:
1110 	case PCIBAR_MEM64:
1111 		if (baridx == pci_msix_table_bar(pi))
1112 			passthru_msix_addr(ctx, pi, baridx, enabled, address);
1113 		else
1114 			passthru_mmio_addr(ctx, pi, baridx, enabled, address);
1115 		break;
1116 	default:
1117 		errx(4, "%s: invalid BAR type %d", __func__,
1118 		    pi->pi_bar[baridx].type);
1119 	}
1120 }
1121 
1122 struct pci_devemu passthru = {
1123 	.pe_emu		= "passthru",
1124 	.pe_init	= passthru_init,
1125 	.pe_legacy_config = passthru_legacy_config,
1126 	.pe_cfgwrite	= passthru_cfgwrite,
1127 	.pe_cfgread	= passthru_cfgread,
1128 	.pe_barwrite 	= passthru_write,
1129 	.pe_barread    	= passthru_read,
1130 	.pe_baraddr	= passthru_addr,
1131 };
1132 PCI_EMUL_SET(passthru);
1133