xref: /freebsd/usr.sbin/bhyve/pci_passthru.c (revision 43a5ec4eb41567cc92586503212743d89686d78f)
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)
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 		sc->psc_bar[i].lobits = 0;
535 
536 		/* Allocate the BAR in the guest I/O or MMIO space */
537 		error = pci_emul_alloc_bar(pi, i, bartype, size);
538 		if (error)
539 			return (-1);
540 
541 		/* Use same lobits as physical bar */
542 		uint8_t lobits = read_config(&sc->psc_sel, PCIR_BAR(i), 0x01);
543 		if (bartype == PCIBAR_MEM32 || bartype == PCIBAR_MEM64) {
544 			lobits &= ~PCIM_BAR_MEM_BASE;
545 		} else {
546 			lobits &= ~PCIM_BAR_IO_BASE;
547 		}
548 		sc->psc_bar[i].lobits = lobits;
549 		pi->pi_bar[i].lobits = lobits;
550 
551 		/*
552 		 * 64-bit BAR takes up two slots so skip the next one.
553 		 */
554 		if (bartype == PCIBAR_MEM64) {
555 			i++;
556 			assert(i <= PCI_BARMAX);
557 			sc->psc_bar[i].type = PCIBAR_MEMHI64;
558 		}
559 	}
560 	return (0);
561 }
562 
563 static int
564 cfginit(struct vmctx *ctx, struct pci_devinst *pi, int bus, int slot, int func)
565 {
566 	int error;
567 	struct passthru_softc *sc;
568 
569 	error = 1;
570 	sc = pi->pi_arg;
571 
572 	bzero(&sc->psc_sel, sizeof(struct pcisel));
573 	sc->psc_sel.pc_bus = bus;
574 	sc->psc_sel.pc_dev = slot;
575 	sc->psc_sel.pc_func = func;
576 
577 	if (cfginitmsi(sc) != 0) {
578 		warnx("failed to initialize MSI for PCI %d/%d/%d",
579 		    bus, slot, func);
580 		goto done;
581 	}
582 
583 	if (cfginitbar(ctx, sc) != 0) {
584 		warnx("failed to initialize BARs for PCI %d/%d/%d",
585 		    bus, slot, func);
586 		goto done;
587 	}
588 
589 	write_config(&sc->psc_sel, PCIR_COMMAND, 2,
590 	    pci_get_cfgdata16(pi, PCIR_COMMAND));
591 
592 	/*
593 	 * We need to do this after PCIR_COMMAND got possibly updated, e.g.,
594 	 * a BAR was enabled, as otherwise the PCIOCBARMMAP might fail on us.
595 	 */
596 	if (pci_msix_table_bar(pi) >= 0) {
597 		error = init_msix_table(ctx, sc);
598 		if (error != 0) {
599 			warnx(
600 			    "failed to initialize MSI-X table for PCI %d/%d/%d: %d",
601 			    bus, slot, func, error);
602 			goto done;
603 		}
604 	}
605 
606 	error = 0;				/* success */
607 done:
608 	return (error);
609 }
610 
611 static int
612 passthru_legacy_config(nvlist_t *nvl, const char *opts)
613 {
614 	char value[16];
615 	int bus, slot, func;
616 
617 	if (opts == NULL)
618 		return (0);
619 
620 	if (sscanf(opts, "%d/%d/%d", &bus, &slot, &func) != 3) {
621 		EPRINTLN("passthru: invalid options \"%s\"", opts);
622 		return (-1);
623 	}
624 
625 	snprintf(value, sizeof(value), "%d", bus);
626 	set_config_value_node(nvl, "bus", value);
627 	snprintf(value, sizeof(value), "%d", slot);
628 	set_config_value_node(nvl, "slot", value);
629 	snprintf(value, sizeof(value), "%d", func);
630 	set_config_value_node(nvl, "func", value);
631 	return (0);
632 }
633 
634 static int
635 passthru_init(struct vmctx *ctx, struct pci_devinst *pi, nvlist_t *nvl)
636 {
637 	int bus, slot, func, error, memflags;
638 	struct passthru_softc *sc;
639 	const char *value;
640 #ifndef WITHOUT_CAPSICUM
641 	cap_rights_t rights;
642 	cap_ioctl_t pci_ioctls[] =
643 	    { PCIOCREAD, PCIOCWRITE, PCIOCGETBAR, PCIOCBARIO, PCIOCBARMMAP };
644 #endif
645 
646 	sc = NULL;
647 	error = 1;
648 
649 #ifndef WITHOUT_CAPSICUM
650 	cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_WRITE);
651 #endif
652 
653 	memflags = vm_get_memflags(ctx);
654 	if (!(memflags & VM_MEM_F_WIRED)) {
655 		warnx("passthru requires guest memory to be wired");
656 		return (error);
657 	}
658 
659 	if (pcifd < 0) {
660 		pcifd = open(_PATH_DEVPCI, O_RDWR, 0);
661 		if (pcifd < 0) {
662 			warn("failed to open %s", _PATH_DEVPCI);
663 			return (error);
664 		}
665 	}
666 
667 #ifndef WITHOUT_CAPSICUM
668 	if (caph_rights_limit(pcifd, &rights) == -1)
669 		errx(EX_OSERR, "Unable to apply rights for sandbox");
670 	if (caph_ioctls_limit(pcifd, pci_ioctls, nitems(pci_ioctls)) == -1)
671 		errx(EX_OSERR, "Unable to apply rights for sandbox");
672 #endif
673 
674 #define GET_INT_CONFIG(var, name) do {					\
675 	value = get_config_value_node(nvl, name);			\
676 	if (value == NULL) {						\
677 		EPRINTLN("passthru: missing required %s setting", name); \
678 		return (error);						\
679 	}								\
680 	var = atoi(value);						\
681 } while (0)
682 
683 	GET_INT_CONFIG(bus, "bus");
684 	GET_INT_CONFIG(slot, "slot");
685 	GET_INT_CONFIG(func, "func");
686 
687 	if (vm_assign_pptdev(ctx, bus, slot, func) != 0) {
688 		warnx("PCI device at %d/%d/%d is not using the ppt(4) driver",
689 		    bus, slot, func);
690 		goto done;
691 	}
692 
693 	sc = calloc(1, sizeof(struct passthru_softc));
694 
695 	pi->pi_arg = sc;
696 	sc->psc_pi = pi;
697 
698 	/* initialize config space */
699 	error = cfginit(ctx, pi, bus, slot, func);
700 done:
701 	if (error) {
702 		free(sc);
703 		vm_unassign_pptdev(ctx, bus, slot, func);
704 	}
705 	return (error);
706 }
707 
708 static int
709 bar_access(int coff)
710 {
711 	if (coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1))
712 		return (1);
713 	else
714 		return (0);
715 }
716 
717 static int
718 msicap_access(struct passthru_softc *sc, int coff)
719 {
720 	int caplen;
721 
722 	if (sc->psc_msi.capoff == 0)
723 		return (0);
724 
725 	caplen = msi_caplen(sc->psc_msi.msgctrl);
726 
727 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
728 		return (1);
729 	else
730 		return (0);
731 }
732 
733 static int
734 msixcap_access(struct passthru_softc *sc, int coff)
735 {
736 	if (sc->psc_msix.capoff == 0)
737 		return (0);
738 
739 	return (coff >= sc->psc_msix.capoff &&
740 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
741 }
742 
743 static int
744 passthru_cfgread(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
745 		 int coff, int bytes, uint32_t *rv)
746 {
747 	struct passthru_softc *sc;
748 
749 	sc = pi->pi_arg;
750 
751 	/*
752 	 * PCI BARs and MSI capability is emulated.
753 	 */
754 	if (bar_access(coff) || msicap_access(sc, coff) ||
755 	    msixcap_access(sc, coff))
756 		return (-1);
757 
758 #ifdef LEGACY_SUPPORT
759 	/*
760 	 * Emulate PCIR_CAP_PTR if this device does not support MSI capability
761 	 * natively.
762 	 */
763 	if (sc->psc_msi.emulated) {
764 		if (coff >= PCIR_CAP_PTR && coff < PCIR_CAP_PTR + 4)
765 			return (-1);
766 	}
767 #endif
768 
769 	/*
770 	 * Emulate the command register.  If a single read reads both the
771 	 * command and status registers, read the status register from the
772 	 * device's config space.
773 	 */
774 	if (coff == PCIR_COMMAND) {
775 		if (bytes <= 2)
776 			return (-1);
777 		*rv = read_config(&sc->psc_sel, PCIR_STATUS, 2) << 16 |
778 		    pci_get_cfgdata16(pi, PCIR_COMMAND);
779 		return (0);
780 	}
781 
782 	/* Everything else just read from the device's config space */
783 	*rv = read_config(&sc->psc_sel, coff, bytes);
784 
785 	return (0);
786 }
787 
788 static int
789 passthru_cfgwrite(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
790 		  int coff, int bytes, uint32_t val)
791 {
792 	int error, msix_table_entries, i;
793 	struct passthru_softc *sc;
794 	uint16_t cmd_old;
795 
796 	sc = pi->pi_arg;
797 
798 	/*
799 	 * PCI BARs are emulated
800 	 */
801 	if (bar_access(coff))
802 		return (-1);
803 
804 	/*
805 	 * MSI capability is emulated
806 	 */
807 	if (msicap_access(sc, coff)) {
808 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
809 		    PCIY_MSI);
810 		error = vm_setup_pptdev_msi(ctx, vcpu, sc->psc_sel.pc_bus,
811 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
812 			pi->pi_msi.addr, pi->pi_msi.msg_data,
813 			pi->pi_msi.maxmsgnum);
814 		if (error != 0)
815 			err(1, "vm_setup_pptdev_msi");
816 		return (0);
817 	}
818 
819 	if (msixcap_access(sc, coff)) {
820 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
821 		    PCIY_MSIX);
822 		if (pi->pi_msix.enabled) {
823 			msix_table_entries = pi->pi_msix.table_count;
824 			for (i = 0; i < msix_table_entries; i++) {
825 				error = vm_setup_pptdev_msix(ctx, vcpu,
826 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
827 				    sc->psc_sel.pc_func, i,
828 				    pi->pi_msix.table[i].addr,
829 				    pi->pi_msix.table[i].msg_data,
830 				    pi->pi_msix.table[i].vector_control);
831 
832 				if (error)
833 					err(1, "vm_setup_pptdev_msix");
834 			}
835 		} else {
836 			error = vm_disable_pptdev_msix(ctx, sc->psc_sel.pc_bus,
837 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
838 			if (error)
839 				err(1, "vm_disable_pptdev_msix");
840 		}
841 		return (0);
842 	}
843 
844 #ifdef LEGACY_SUPPORT
845 	/*
846 	 * If this device does not support MSI natively then we cannot let
847 	 * the guest disable legacy interrupts from the device. It is the
848 	 * legacy interrupt that is triggering the virtual MSI to the guest.
849 	 */
850 	if (sc->psc_msi.emulated && pci_msi_enabled(pi)) {
851 		if (coff == PCIR_COMMAND && bytes == 2)
852 			val &= ~PCIM_CMD_INTxDIS;
853 	}
854 #endif
855 
856 	write_config(&sc->psc_sel, coff, bytes, val);
857 	if (coff == PCIR_COMMAND) {
858 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
859 		if (bytes == 1)
860 			pci_set_cfgdata8(pi, PCIR_COMMAND, val);
861 		else if (bytes == 2)
862 			pci_set_cfgdata16(pi, PCIR_COMMAND, val);
863 		pci_emul_cmd_changed(pi, cmd_old);
864 	}
865 
866 	return (0);
867 }
868 
869 static void
870 passthru_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
871 	       uint64_t offset, int size, uint64_t value)
872 {
873 	struct passthru_softc *sc;
874 	struct pci_bar_ioreq pio;
875 
876 	sc = pi->pi_arg;
877 
878 	if (baridx == pci_msix_table_bar(pi)) {
879 		msix_table_write(ctx, vcpu, sc, offset, size, value);
880 	} else {
881 		assert(pi->pi_bar[baridx].type == PCIBAR_IO);
882 		assert(size == 1 || size == 2 || size == 4);
883 		assert(offset <= UINT32_MAX && offset + size <= UINT32_MAX);
884 
885 		bzero(&pio, sizeof(pio));
886 		pio.pbi_sel = sc->psc_sel;
887 		pio.pbi_op = PCIBARIO_WRITE;
888 		pio.pbi_bar = baridx;
889 		pio.pbi_offset = (uint32_t)offset;
890 		pio.pbi_width = size;
891 		pio.pbi_value = (uint32_t)value;
892 
893 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
894 	}
895 }
896 
897 static uint64_t
898 passthru_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
899 	      uint64_t offset, int size)
900 {
901 	struct passthru_softc *sc;
902 	struct pci_bar_ioreq pio;
903 	uint64_t val;
904 
905 	sc = pi->pi_arg;
906 
907 	if (baridx == pci_msix_table_bar(pi)) {
908 		val = msix_table_read(sc, offset, size);
909 	} else {
910 		assert(pi->pi_bar[baridx].type == PCIBAR_IO);
911 		assert(size == 1 || size == 2 || size == 4);
912 		assert(offset <= UINT32_MAX && offset + size <= UINT32_MAX);
913 
914 		bzero(&pio, sizeof(pio));
915 		pio.pbi_sel = sc->psc_sel;
916 		pio.pbi_op = PCIBARIO_READ;
917 		pio.pbi_bar = baridx;
918 		pio.pbi_offset = (uint32_t)offset;
919 		pio.pbi_width = size;
920 
921 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
922 
923 		val = pio.pbi_value;
924 	}
925 
926 	return (val);
927 }
928 
929 static void
930 passthru_msix_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
931 		   int enabled, uint64_t address)
932 {
933 	struct passthru_softc *sc;
934 	size_t remaining;
935 	uint32_t table_size, table_offset;
936 
937 	sc = pi->pi_arg;
938 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
939 	if (table_offset > 0) {
940 		if (!enabled) {
941 			if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
942 						 sc->psc_sel.pc_dev,
943 						 sc->psc_sel.pc_func, address,
944 						 table_offset) != 0)
945 				warnx("pci_passthru: unmap_pptdev_mmio failed");
946 		} else {
947 			if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
948 					       sc->psc_sel.pc_dev,
949 					       sc->psc_sel.pc_func, address,
950 					       table_offset,
951 					       sc->psc_bar[baridx].addr) != 0)
952 				warnx("pci_passthru: map_pptdev_mmio failed");
953 		}
954 	}
955 	table_size = pi->pi_msix.table_offset - table_offset;
956 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
957 	table_size = roundup2(table_size, 4096);
958 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
959 	if (remaining > 0) {
960 		address += table_offset + table_size;
961 		if (!enabled) {
962 			if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
963 						 sc->psc_sel.pc_dev,
964 						 sc->psc_sel.pc_func, address,
965 						 remaining) != 0)
966 				warnx("pci_passthru: unmap_pptdev_mmio failed");
967 		} else {
968 			if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
969 					       sc->psc_sel.pc_dev,
970 					       sc->psc_sel.pc_func, address,
971 					       remaining,
972 					       sc->psc_bar[baridx].addr +
973 					       table_offset + table_size) != 0)
974 				warnx("pci_passthru: map_pptdev_mmio failed");
975 		}
976 	}
977 }
978 
979 static void
980 passthru_mmio_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
981 		   int enabled, uint64_t address)
982 {
983 	struct passthru_softc *sc;
984 
985 	sc = pi->pi_arg;
986 	if (!enabled) {
987 		if (vm_unmap_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
988 					 sc->psc_sel.pc_dev,
989 					 sc->psc_sel.pc_func, address,
990 					 sc->psc_bar[baridx].size) != 0)
991 			warnx("pci_passthru: unmap_pptdev_mmio failed");
992 	} else {
993 		if (vm_map_pptdev_mmio(ctx, sc->psc_sel.pc_bus,
994 				       sc->psc_sel.pc_dev,
995 				       sc->psc_sel.pc_func, address,
996 				       sc->psc_bar[baridx].size,
997 				       sc->psc_bar[baridx].addr) != 0)
998 			warnx("pci_passthru: map_pptdev_mmio failed");
999 	}
1000 }
1001 
1002 static void
1003 passthru_addr(struct vmctx *ctx, struct pci_devinst *pi, int baridx,
1004 	      int enabled, uint64_t address)
1005 {
1006 
1007 	if (pi->pi_bar[baridx].type == PCIBAR_IO)
1008 		return;
1009 	if (baridx == pci_msix_table_bar(pi))
1010 		passthru_msix_addr(ctx, pi, baridx, enabled, address);
1011 	else
1012 		passthru_mmio_addr(ctx, pi, baridx, enabled, address);
1013 }
1014 
1015 struct pci_devemu passthru = {
1016 	.pe_emu		= "passthru",
1017 	.pe_init	= passthru_init,
1018 	.pe_legacy_config = passthru_legacy_config,
1019 	.pe_cfgwrite	= passthru_cfgwrite,
1020 	.pe_cfgread	= passthru_cfgread,
1021 	.pe_barwrite 	= passthru_write,
1022 	.pe_barread    	= passthru_read,
1023 	.pe_baraddr	= passthru_addr,
1024 };
1025 PCI_EMUL_SET(passthru);
1026