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