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