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