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