xref: /freebsd/usr.sbin/bhyve/pci_passthru.c (revision 3b90096cf9bcaec70b717e9ff0a9e23d14b600b6)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 
29 #include <sys/param.h>
30 #ifndef WITHOUT_CAPSICUM
31 #include <sys/capsicum.h>
32 #endif
33 #include <sys/types.h>
34 #include <sys/mman.h>
35 #include <sys/pciio.h>
36 #include <sys/ioctl.h>
37 #include <sys/stat.h>
38 
39 #include <dev/io/iodev.h>
40 #include <dev/pci/pcireg.h>
41 #include <dev/vmm/vmm_mem.h>
42 
43 #include <vm/vm.h>
44 
45 #include <machine/iodev.h>
46 #include <machine/vm.h>
47 
48 #ifndef WITHOUT_CAPSICUM
49 #include <capsicum_helpers.h>
50 #endif
51 #include <ctype.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <pthread.h>
59 #include <sysexits.h>
60 #include <unistd.h>
61 
62 #include <machine/vmm.h>
63 
64 #include "debug.h"
65 #include "mem.h"
66 #include "pci_passthru.h"
67 
68 #ifndef _PATH_DEVPCI
69 #define	_PATH_DEVPCI	"/dev/pci"
70 #endif
71 
72 #define	LEGACY_SUPPORT	1
73 
74 #define MSIX_TABLE_COUNT(ctrl) (((ctrl) & PCIM_MSIXCTRL_TABLE_SIZE) + 1)
75 #define MSIX_CAPLEN 12
76 
77 #define PASSTHRU_MMIO_MAX 3
78 
79 static int pcifd = -1;
80 
81 SET_DECLARE(passthru_dev_set, struct passthru_dev);
82 
83 struct passthru_bar_handler {
84 	TAILQ_ENTRY(passthru_bar_handler) chain;
85 	uint64_t off;
86 	uint64_t size;
87 	passthru_read_handler read;
88 	passthru_write_handler write;
89 };
90 
91 struct passthru_softc {
92 	struct pci_devinst *psc_pi;
93 	/* ROM is handled like a BAR */
94 	struct pcibar psc_bar[PCI_BARMAX_WITH_ROM + 1];
95 	struct {
96 		int		capoff;
97 		int		msgctrl;
98 		int		emulated;
99 	} psc_msi;
100 	struct {
101 		int		capoff;
102 	} psc_msix;
103 	struct {
104 		int		capoff;
105 		uint16_t	pmcsr;
106 		uint16_t	reset_pmcsr;
107 	} psc_pm;
108 	struct {
109 		int		capoff;
110 		uint16_t	devctl;
111 		uint16_t	reset_devctl;
112 		uint16_t	devctl2;
113 		uint16_t	reset_devctl2;
114 		bool		has_devctl2;
115 	} psc_pcie;
116 	struct pcisel psc_sel;
117 	pthread_mutex_t	psc_io_mtx;
118 	bool		psc_resetting;
119 
120 	struct passthru_mmio_mapping psc_mmio_map[PASSTHRU_MMIO_MAX];
121 	cfgread_handler psc_pcir_rhandler[PCI_REGMAX + 1];
122 	cfgwrite_handler psc_pcir_whandler[PCI_REGMAX + 1];
123 
124 	TAILQ_HEAD(,
125 	    passthru_bar_handler) psc_bar_handler[PCI_BARMAX_WITH_ROM + 1];
126 };
127 
128 static int
msi_caplen(int msgctrl)129 msi_caplen(int msgctrl)
130 {
131 	int len;
132 
133 	len = 10;		/* minimum length of msi capability */
134 
135 	if (msgctrl & PCIM_MSICTRL_64BIT)
136 		len += 4;
137 
138 #if 0
139 	/*
140 	 * Ignore the 'mask' and 'pending' bits in the MSI capability.
141 	 * We'll let the guest manipulate them directly.
142 	 */
143 	if (msgctrl & PCIM_MSICTRL_VECTOR)
144 		len += 10;
145 #endif
146 
147 	return (len);
148 }
149 
150 static int
pcifd_open(void)151 pcifd_open(void)
152 {
153 	int fd;
154 
155 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
156 	if (fd < 0) {
157 		warn("failed to open %s", _PATH_DEVPCI);
158 		return (-1);
159 	}
160 	return (fd);
161 }
162 
163 static int
pcifd_init(void)164 pcifd_init(void)
165 {
166 	pcifd = pcifd_open();
167 	if (pcifd < 0)
168 		return (1);
169 
170 #ifndef WITHOUT_CAPSICUM
171 	cap_rights_t pcifd_rights;
172 	cap_rights_init(&pcifd_rights, CAP_IOCTL, CAP_READ, CAP_WRITE);
173 	if (caph_rights_limit(pcifd, &pcifd_rights) == -1)
174 		errx(EX_OSERR, "Unable to apply rights for sandbox");
175 
176 	const cap_ioctl_t pcifd_ioctls[] = { PCIOCREAD, PCIOCWRITE, PCIOCGETBAR,
177 		PCIOCBARIO, PCIOCBARMMAP, PCIOCGETCONF };
178 	if (caph_ioctls_limit(pcifd, pcifd_ioctls, nitems(pcifd_ioctls)) == -1)
179 		errx(EX_OSERR, "Unable to apply rights for sandbox");
180 #endif
181 
182 	return (0);
183 }
184 
185 static uint32_t
host_read_config(int fd,const struct pcisel * sel,long reg,int width)186 host_read_config(int fd, const struct pcisel *sel, long reg, int width)
187 {
188 	struct pci_io pi;
189 
190 	bzero(&pi, sizeof(pi));
191 	pi.pi_sel = *sel;
192 	pi.pi_reg = reg;
193 	pi.pi_width = width;
194 
195 	if (ioctl(fd, PCIOCREAD, &pi) < 0)
196 		return (0);			/* XXX */
197 	else
198 		return (pi.pi_data);
199 }
200 
201 static uint32_t
passthru_read_config(const struct pcisel * sel,long reg,int width)202 passthru_read_config(const struct pcisel *sel, long reg, int width)
203 {
204 	return (host_read_config(pcifd, sel, reg, width));
205 }
206 
207 uint32_t
pci_host_read_config(const struct pcisel * sel,long reg,int width)208 pci_host_read_config(const struct pcisel *sel, long reg, int width)
209 {
210 	uint32_t ret;
211 	int fd;
212 
213 	fd = pcifd_open();
214 	if (fd < 0)
215 		return (0);
216 	ret = host_read_config(fd, sel, reg, width);
217 	(void)close(fd);
218 	return (ret);
219 }
220 
221 static void
host_write_config(int fd,const struct pcisel * sel,long reg,int width,uint32_t data)222 host_write_config(int fd, const struct pcisel *sel, long reg, int width,
223     uint32_t data)
224 {
225 	struct pci_io pi;
226 
227 	bzero(&pi, sizeof(pi));
228 	pi.pi_sel = *sel;
229 	pi.pi_reg = reg;
230 	pi.pi_width = width;
231 	pi.pi_data = data;
232 
233 	(void)ioctl(fd, PCIOCWRITE, &pi);		/* XXX */
234 }
235 
236 static void
passthru_write_config(const struct pcisel * sel,long reg,int width,uint32_t data)237 passthru_write_config(const struct pcisel *sel, long reg, int width,
238     uint32_t data)
239 {
240 	host_write_config(pcifd, sel, reg, width, data);
241 }
242 
243 void
pci_host_write_config(const struct pcisel * sel,long reg,int width,uint32_t data)244 pci_host_write_config(const struct pcisel *sel, long reg, int width,
245     uint32_t data)
246 {
247 	int fd;
248 
249 	fd = pcifd_open();
250 	if (fd < 0)
251 		return;
252 	host_write_config(fd, sel, reg, width, data);
253 	(void)close(fd);
254 }
255 
256 #ifdef LEGACY_SUPPORT
257 static int
passthru_add_msicap(struct pci_devinst * pi,int msgnum,int nextptr)258 passthru_add_msicap(struct pci_devinst *pi, int msgnum, int nextptr)
259 {
260 	int capoff;
261 	struct msicap msicap;
262 	u_char *capdata;
263 
264 	pci_populate_msicap(&msicap, msgnum, nextptr);
265 
266 	/*
267 	 * XXX
268 	 * Copy the msi capability structure in the last 16 bytes of the
269 	 * config space. This is wrong because it could shadow something
270 	 * useful to the device.
271 	 */
272 	capoff = 256 - roundup(sizeof(msicap), 4);
273 	capdata = (u_char *)&msicap;
274 	for (size_t i = 0; i < sizeof(msicap); i++)
275 		pci_set_cfgdata8(pi, capoff + i, capdata[i]);
276 
277 	return (capoff);
278 }
279 #endif	/* LEGACY_SUPPORT */
280 
281 static int
cfginitcaps(struct passthru_softc * sc)282 cfginitcaps(struct passthru_softc *sc)
283 {
284 	int i, ptr, capptr, cap, sts, caplen, table_size;
285 	uint16_t flags;
286 	uint32_t u32;
287 	struct pcisel sel;
288 	struct pci_devinst *pi;
289 	struct msixcap msixcap;
290 	char *msixcap_ptr;
291 
292 	pi = sc->psc_pi;
293 	sel = sc->psc_sel;
294 
295 	/*
296 	 * Parse the capabilities and cache the location of the MSI
297 	 * and MSI-X capabilities.
298 	 */
299 	sts = passthru_read_config(&sel, PCIR_STATUS, 2);
300 	if (sts & PCIM_STATUS_CAPPRESENT) {
301 		ptr = passthru_read_config(&sel, PCIR_CAP_PTR, 1);
302 		while (ptr != 0 && ptr != 0xff) {
303 			cap = passthru_read_config(&sel, ptr + PCICAP_ID, 1);
304 			if (cap == PCIY_MSI) {
305 				/*
306 				 * Copy the MSI capability into the config
307 				 * space of the emulated pci device
308 				 */
309 				sc->psc_msi.capoff = ptr;
310 				sc->psc_msi.msgctrl =
311 				    passthru_read_config(&sel, ptr + 2, 2);
312 				sc->psc_msi.emulated = 0;
313 				caplen = msi_caplen(sc->psc_msi.msgctrl);
314 				capptr = ptr;
315 				while (caplen > 0) {
316 					u32 = passthru_read_config(&sel, capptr,
317 					    4);
318 					pci_set_cfgdata32(pi, capptr, u32);
319 					caplen -= 4;
320 					capptr += 4;
321 				}
322 			} else if (cap == PCIY_MSIX) {
323 				/*
324 				 * Copy the MSI-X capability
325 				 */
326 				sc->psc_msix.capoff = ptr;
327 				caplen = 12;
328 				msixcap_ptr = (char *)&msixcap;
329 				capptr = ptr;
330 				while (caplen > 0) {
331 					u32 = passthru_read_config(&sel, capptr,
332 					    4);
333 					memcpy(msixcap_ptr, &u32, 4);
334 					pci_set_cfgdata32(pi, capptr, u32);
335 					caplen -= 4;
336 					capptr += 4;
337 					msixcap_ptr += 4;
338 				}
339 			} else if (cap == PCIY_PMG) {
340 				sc->psc_pm.capoff = ptr;
341 			} else if (cap == PCIY_EXPRESS) {
342 				sc->psc_pcie.capoff = ptr;
343 			}
344 			ptr = passthru_read_config(&sel, ptr + PCICAP_NEXTPTR,
345 			    1);
346 		}
347 	}
348 	if (sc->psc_pm.capoff != 0) {
349 		sc->psc_pm.pmcsr = passthru_read_config(&sel,
350 		    sc->psc_pm.capoff + PCIR_POWER_STATUS, 2);
351 		/* The physical function remains in its host-owned power state. */
352 		sc->psc_pm.pmcsr |= PCIM_PSTAT_NOSOFTRESET;
353 		sc->psc_pm.reset_pmcsr = sc->psc_pm.pmcsr;
354 	}
355 	if (sc->psc_pcie.capoff != 0) {
356 		sc->psc_pcie.devctl = passthru_read_config(&sel,
357 		    sc->psc_pcie.capoff + PCIER_DEVICE_CTL, 2);
358 		/*
359 		 * Use the assignment-time guest view as the virtual reset baseline.
360 		 * Host firmware and the PCI bus may already have tuned Device Control,
361 		 * so restoring the hardware reset defaults would expose a different
362 		 * configuration after the first guest FLR.
363 		 */
364 		sc->psc_pcie.reset_devctl = sc->psc_pcie.devctl;
365 		flags = passthru_read_config(&sel,
366 		    sc->psc_pcie.capoff + PCIER_FLAGS, 2);
367 		if ((flags & PCIEM_FLAGS_VERSION) >= 2) {
368 			sc->psc_pcie.has_devctl2 = true;
369 			sc->psc_pcie.devctl2 = passthru_read_config(&sel,
370 			    sc->psc_pcie.capoff + PCIER_DEVICE_CTL2, 2);
371 			sc->psc_pcie.reset_devctl2 = sc->psc_pcie.devctl2;
372 		}
373 	}
374 
375 	if (sc->psc_msix.capoff != 0) {
376 		pi->pi_msix.pba_bar =
377 		    msixcap.pba_info & PCIM_MSIX_BIR_MASK;
378 		pi->pi_msix.pba_offset =
379 		    msixcap.pba_info & ~PCIM_MSIX_BIR_MASK;
380 		pi->pi_msix.table_bar =
381 		    msixcap.table_info & PCIM_MSIX_BIR_MASK;
382 		pi->pi_msix.table_offset =
383 		    msixcap.table_info & ~PCIM_MSIX_BIR_MASK;
384 		pi->pi_msix.table_count = MSIX_TABLE_COUNT(msixcap.msgctrl);
385 		pi->pi_msix.pba_size = PBA_SIZE(pi->pi_msix.table_count);
386 
387 		/* Allocate the emulated MSI-X table array */
388 		table_size = pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
389 		pi->pi_msix.table = calloc(1, table_size);
390 		if (pi->pi_msix.table == NULL)
391 			return (-1);
392 
393 		/* Mask all table entries */
394 		for (i = 0; i < pi->pi_msix.table_count; i++) {
395 			pi->pi_msix.table[i].vector_control |=
396 						PCIM_MSIX_VCTRL_MASK;
397 		}
398 	}
399 
400 #ifdef LEGACY_SUPPORT
401 	/*
402 	 * If the passthrough device does not support MSI then craft a
403 	 * MSI capability for it. We link the new MSI capability at the
404 	 * head of the list of capabilities.
405 	 */
406 	if ((sts & PCIM_STATUS_CAPPRESENT) != 0 && sc->psc_msi.capoff == 0) {
407 		int origptr, msiptr;
408 		origptr = passthru_read_config(&sel, PCIR_CAP_PTR, 1);
409 		msiptr = passthru_add_msicap(pi, 1, origptr);
410 		sc->psc_msi.capoff = msiptr;
411 		sc->psc_msi.msgctrl = pci_get_cfgdata16(pi, msiptr + 2);
412 		sc->psc_msi.emulated = 1;
413 		pci_set_cfgdata8(pi, PCIR_CAP_PTR, msiptr);
414 	}
415 #endif
416 
417 	/* Make sure one of the capabilities is present */
418 	if (sc->psc_msi.capoff == 0 && sc->psc_msix.capoff == 0)
419 		return (-1);
420 	else
421 		return (0);
422 }
423 
424 static uint64_t
msix_table_read(struct passthru_softc * sc,uint64_t offset,int size)425 msix_table_read(struct passthru_softc *sc, uint64_t offset, int size)
426 {
427 	struct pci_devinst *pi;
428 	struct msix_table_entry *entry;
429 	uint8_t *src8;
430 	uint16_t *src16;
431 	uint32_t *src32;
432 	uint64_t *src64;
433 	uint64_t data;
434 	size_t entry_offset;
435 	uint32_t table_offset;
436 	int index, table_count;
437 
438 	pi = sc->psc_pi;
439 
440 	table_offset = pi->pi_msix.table_offset;
441 	table_count = pi->pi_msix.table_count;
442 	if (offset < table_offset ||
443 	    offset >= table_offset + table_count * MSIX_TABLE_ENTRY_SIZE) {
444 		switch (size) {
445 		case 1:
446 			src8 = (uint8_t *)(pi->pi_msix.mapped_addr + offset);
447 			data = *src8;
448 			break;
449 		case 2:
450 			src16 = (uint16_t *)(pi->pi_msix.mapped_addr + offset);
451 			data = *src16;
452 			break;
453 		case 4:
454 			src32 = (uint32_t *)(pi->pi_msix.mapped_addr + offset);
455 			data = *src32;
456 			break;
457 		case 8:
458 			src64 = (uint64_t *)(pi->pi_msix.mapped_addr + offset);
459 			data = *src64;
460 			break;
461 		default:
462 			return (-1);
463 		}
464 		return (data);
465 	}
466 
467 	offset -= table_offset;
468 	index = offset / MSIX_TABLE_ENTRY_SIZE;
469 	assert(index < table_count);
470 
471 	entry = &pi->pi_msix.table[index];
472 	entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
473 
474 	switch (size) {
475 	case 1:
476 		src8 = (uint8_t *)((uint8_t *)entry + entry_offset);
477 		data = *src8;
478 		break;
479 	case 2:
480 		src16 = (uint16_t *)((uint8_t *)entry + entry_offset);
481 		data = *src16;
482 		break;
483 	case 4:
484 		src32 = (uint32_t *)((uint8_t *)entry + entry_offset);
485 		data = *src32;
486 		break;
487 	case 8:
488 		src64 = (uint64_t *)((uint8_t *)entry + entry_offset);
489 		data = *src64;
490 		break;
491 	default:
492 		return (-1);
493 	}
494 
495 	return (data);
496 }
497 
498 static void
msix_table_write(struct passthru_softc * sc,uint64_t offset,int size,uint64_t data)499 msix_table_write(struct passthru_softc *sc, uint64_t offset, int size,
500     uint64_t data)
501 {
502 	struct pci_devinst *pi;
503 	struct msix_table_entry *entry;
504 	uint8_t *dest8;
505 	uint16_t *dest16;
506 	uint32_t *dest32;
507 	uint64_t *dest64;
508 	size_t entry_offset;
509 	uint32_t table_offset, vector_control;
510 	int index, table_count;
511 
512 	pi = sc->psc_pi;
513 
514 	table_offset = pi->pi_msix.table_offset;
515 	table_count = pi->pi_msix.table_count;
516 	if (offset < table_offset ||
517 	    offset >= table_offset + table_count * MSIX_TABLE_ENTRY_SIZE) {
518 		switch (size) {
519 		case 1:
520 			dest8 = (uint8_t *)(pi->pi_msix.mapped_addr + offset);
521 			*dest8 = data;
522 			break;
523 		case 2:
524 			dest16 = (uint16_t *)(pi->pi_msix.mapped_addr + offset);
525 			*dest16 = data;
526 			break;
527 		case 4:
528 			dest32 = (uint32_t *)(pi->pi_msix.mapped_addr + offset);
529 			*dest32 = data;
530 			break;
531 		case 8:
532 			dest64 = (uint64_t *)(pi->pi_msix.mapped_addr + offset);
533 			*dest64 = data;
534 			break;
535 		}
536 		return;
537 	}
538 
539 	offset -= table_offset;
540 	index = offset / MSIX_TABLE_ENTRY_SIZE;
541 	assert(index < table_count);
542 
543 	entry = &pi->pi_msix.table[index];
544 	entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
545 
546 	/* Only 4 byte naturally-aligned writes are supported */
547 	assert(size == 4);
548 	assert(entry_offset % 4 == 0);
549 
550 	vector_control = entry->vector_control;
551 	dest32 = (uint32_t *)((uint8_t *)entry + entry_offset);
552 	*dest32 = data;
553 	/* If MSI-X hasn't been enabled, do nothing */
554 	if (pi->pi_msix.enabled) {
555 		/* If the entry is masked, don't set it up */
556 		if ((entry->vector_control & PCIM_MSIX_VCTRL_MASK) == 0 ||
557 		    (vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
558 			(void)vm_setup_pptdev_msix(sc->psc_pi->pi_vmctx,
559 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
560 			    sc->psc_sel.pc_func, index, entry->addr,
561 			    entry->msg_data, entry->vector_control);
562 		}
563 	}
564 }
565 
566 static int
init_msix_table(struct passthru_softc * sc)567 init_msix_table(struct passthru_softc *sc)
568 {
569 	struct pci_devinst *pi = sc->psc_pi;
570 	struct pci_bar_mmap pbm;
571 	int b, s, f;
572 	uint32_t table_size, table_offset;
573 
574 	assert(pci_msix_table_bar(pi) >= 0 && pci_msix_pba_bar(pi) >= 0);
575 
576 	b = sc->psc_sel.pc_bus;
577 	s = sc->psc_sel.pc_dev;
578 	f = sc->psc_sel.pc_func;
579 
580 	/*
581 	 * Map the region of the BAR containing the MSI-X table.  This is
582 	 * necessary for two reasons:
583 	 * 1. The PBA may reside in the first or last page containing the MSI-X
584 	 *    table.
585 	 * 2. While PCI devices are not supposed to use the page(s) containing
586 	 *    the MSI-X table for other purposes, some do in practice.
587 	 */
588 	memset(&pbm, 0, sizeof(pbm));
589 	pbm.pbm_sel = sc->psc_sel;
590 	pbm.pbm_flags = PCIIO_BAR_MMAP_RW;
591 	pbm.pbm_reg = PCIR_BAR(pi->pi_msix.table_bar);
592 	pbm.pbm_memattr = VM_MEMATTR_DEVICE;
593 
594 	if (ioctl(pcifd, PCIOCBARMMAP, &pbm) != 0) {
595 		warn("Failed to map MSI-X table BAR on %d/%d/%d", b, s, f);
596 		return (-1);
597 	}
598 	assert(pbm.pbm_bar_off == 0);
599 	pi->pi_msix.mapped_addr = (uint8_t *)(uintptr_t)pbm.pbm_map_base;
600 	pi->pi_msix.mapped_size = pbm.pbm_map_length;
601 
602 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
603 
604 	table_size = pi->pi_msix.table_offset - table_offset;
605 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
606 	table_size = roundup2(table_size, 4096);
607 
608 	/*
609 	 * Unmap any pages not containing the table, we do not need to emulate
610 	 * accesses to them.  Avoid releasing address space to help ensure that
611 	 * a buggy out-of-bounds access causes a crash.
612 	 */
613 	if (table_offset != 0)
614 		if (mprotect(pi->pi_msix.mapped_addr, table_offset,
615 		    PROT_NONE) != 0)
616 			warn("Failed to unmap MSI-X table BAR region");
617 	if (table_offset + table_size != pi->pi_msix.mapped_size)
618 		if (mprotect(
619 		    pi->pi_msix.mapped_addr + table_offset + table_size,
620 		    pi->pi_msix.mapped_size - (table_offset + table_size),
621 		    PROT_NONE) != 0)
622 			warn("Failed to unmap MSI-X table BAR region");
623 
624 	return (0);
625 }
626 
627 static int
cfginitbar(struct passthru_softc * sc)628 cfginitbar(struct passthru_softc *sc)
629 {
630 	int i, error;
631 	struct pci_devinst *pi;
632 	struct pci_bar_io bar;
633 	enum pcibar_type bartype;
634 	uint64_t base, size;
635 
636 	pi = sc->psc_pi;
637 
638 	/*
639 	 * Initialize BAR registers
640 	 */
641 	for (i = 0; i <= PCI_BARMAX; i++) {
642 		uint8_t lobits;
643 
644 		bzero(&bar, sizeof(bar));
645 		bar.pbi_sel = sc->psc_sel;
646 		bar.pbi_reg = PCIR_BAR(i);
647 
648 		if (ioctl(pcifd, PCIOCGETBAR, &bar) < 0)
649 			continue;
650 
651 		if (PCI_BAR_IO(bar.pbi_base)) {
652 			bartype = PCIBAR_IO;
653 			base = bar.pbi_base & PCIM_BAR_IO_BASE;
654 		} else {
655 			switch (bar.pbi_base & PCIM_BAR_MEM_TYPE) {
656 			case PCIM_BAR_MEM_64:
657 				bartype = PCIBAR_MEM64;
658 				break;
659 			default:
660 				bartype = PCIBAR_MEM32;
661 				break;
662 			}
663 			base = bar.pbi_base & PCIM_BAR_MEM_BASE;
664 		}
665 		size = bar.pbi_length;
666 
667 		if (bartype != PCIBAR_IO) {
668 			if (((base | size) & PAGE_MASK) != 0) {
669 				warnx("passthru device %d/%d/%d BAR %d: "
670 				    "base %#lx or size %#lx not page aligned\n",
671 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
672 				    sc->psc_sel.pc_func, i, base, size);
673 				return (-1);
674 			}
675 		}
676 
677 		/* Cache information about the "real" BAR */
678 		sc->psc_bar[i].type = bartype;
679 		sc->psc_bar[i].size = size;
680 		sc->psc_bar[i].addr = base;
681 		sc->psc_bar[i].lobits = 0;
682 
683 		/* Allocate the BAR in the guest I/O or MMIO space */
684 		error = pci_emul_alloc_bar(pi, i, bartype, size);
685 		if (error)
686 			return (-1);
687 
688 		/* Use same lobits as physical bar */
689 		lobits = (uint8_t)passthru_read_config(&sc->psc_sel,
690 		    PCIR_BAR(i), 0x01);
691 		if (bartype == PCIBAR_MEM32 || bartype == PCIBAR_MEM64) {
692 			lobits &= ~PCIM_BAR_MEM_BASE;
693 		} else {
694 			lobits &= ~PCIM_BAR_IO_BASE;
695 		}
696 		sc->psc_bar[i].lobits = lobits;
697 		pi->pi_bar[i].lobits = lobits;
698 
699 		/*
700 		 * 64-bit BAR takes up two slots so skip the next one.
701 		 */
702 		if (bartype == PCIBAR_MEM64) {
703 			i++;
704 			assert(i <= PCI_BARMAX);
705 			sc->psc_bar[i].type = PCIBAR_MEMHI64;
706 		}
707 	}
708 	return (0);
709 }
710 
711 static int
cfginit(struct pci_devinst * pi,int bus,int slot,int func)712 cfginit(struct pci_devinst *pi, int bus, int slot, int func)
713 {
714 	int error;
715 	struct passthru_softc *sc;
716 	uint16_t cmd;
717 	uint8_t intline, intpin;
718 
719 	error = 1;
720 	sc = pi->pi_arg;
721 
722 	bzero(&sc->psc_sel, sizeof(struct pcisel));
723 	sc->psc_sel.pc_bus = bus;
724 	sc->psc_sel.pc_dev = slot;
725 	sc->psc_sel.pc_func = func;
726 
727 	/*
728 	 * Copy physical PCI header to virtual config space.  COMMAND,
729 	 * INTLINE, and INTPIN shouldn't be aligned with their
730 	 * physical value and they are already set by pci_emul_init().
731 	 */
732 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
733 	intline = pci_get_cfgdata8(pi, PCIR_INTLINE);
734 	intpin = pci_get_cfgdata8(pi, PCIR_INTPIN);
735 	for (int i = 0; i <= PCIR_MAXLAT; i += 4) {
736 		pci_set_cfgdata32(pi, i,
737 		    passthru_read_config(&sc->psc_sel, i, 4));
738 	}
739 	pci_set_cfgdata16(pi, PCIR_COMMAND, cmd);
740 	pci_set_cfgdata8(pi, PCIR_INTLINE, intline);
741 	pci_set_cfgdata8(pi, PCIR_INTPIN, intpin);
742 
743 	if (cfginitcaps(sc) != 0) {
744 		warnx("failed to initialize PCI capabilities for %d/%d/%d",
745 		    bus, slot, func);
746 		goto done;
747 	}
748 
749 	if (cfginitbar(sc) != 0) {
750 		warnx("failed to initialize BARs for PCI %d/%d/%d",
751 		    bus, slot, func);
752 		goto done;
753 	}
754 
755 	if (pci_msix_table_bar(pi) >= 0) {
756 		error = init_msix_table(sc);
757 		if (error != 0) {
758 			warnx(
759 			    "failed to initialize MSI-X table for PCI %d/%d/%d: %d",
760 			    bus, slot, func, error);
761 			goto done;
762 		}
763 	}
764 
765 	error = 0;				/* success */
766 done:
767 	return (error);
768 }
769 
770 struct passthru_mmio_mapping *
passthru_get_mmio(struct passthru_softc * sc,int num)771 passthru_get_mmio(struct passthru_softc *sc, int num)
772 {
773 	assert(sc != NULL);
774 	assert(num < PASSTHRU_MMIO_MAX);
775 
776 	return (&sc->psc_mmio_map[num]);
777 }
778 
779 struct pcisel *
passthru_get_sel(struct passthru_softc * sc)780 passthru_get_sel(struct passthru_softc *sc)
781 {
782 	assert(sc != NULL);
783 
784 	return (&sc->psc_sel);
785 }
786 
787 int
set_pcir_handler(struct passthru_softc * sc,int reg,int len,cfgread_handler rhandler,cfgwrite_handler whandler)788 set_pcir_handler(struct passthru_softc *sc, int reg, int len,
789     cfgread_handler rhandler, cfgwrite_handler whandler)
790 {
791 	if (reg > PCI_REGMAX || reg + len > PCI_REGMAX + 1)
792 		return (-1);
793 
794 	for (int i = reg; i < reg + len; ++i) {
795 		assert(sc->psc_pcir_rhandler[i] == NULL || rhandler == NULL);
796 		assert(sc->psc_pcir_whandler[i] == NULL || whandler == NULL);
797 		sc->psc_pcir_rhandler[i] = rhandler;
798 		sc->psc_pcir_whandler[i] = whandler;
799 	}
800 
801 	return (0);
802 }
803 
804 int
passthru_set_bar_handler(struct passthru_softc * sc,int baridx,uint64_t off,uint64_t size,passthru_read_handler rhandler,passthru_write_handler whandler)805 passthru_set_bar_handler(struct passthru_softc *sc, int baridx, uint64_t off,
806     uint64_t size, passthru_read_handler rhandler,
807     passthru_write_handler whandler)
808 {
809 	struct passthru_bar_handler *handler_new;
810 	struct passthru_bar_handler *handler;
811 
812 	assert(sc->psc_bar[baridx].type == PCIBAR_IO ||
813 	    sc->psc_bar[baridx].type == PCIBAR_MEM32 ||
814 	    sc->psc_bar[baridx].type == PCIBAR_MEM64);
815 	assert(sc->psc_bar[baridx].size >= off + size);
816 	assert(off < off + size);
817 
818 	handler_new = malloc(sizeof(struct passthru_bar_handler));
819 	if (handler_new == NULL) {
820 		return (ENOMEM);
821 	}
822 
823 	handler_new->off = off;
824 	handler_new->size = size;
825 	handler_new->read = rhandler;
826 	handler_new->write = whandler;
827 
828 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
829 		if (handler->off < handler_new->off) {
830 			assert(handler->off + handler->size < handler_new->off);
831 			continue;
832 		}
833 		assert(handler->off > handler_new->off + handler_new->size);
834 		TAILQ_INSERT_BEFORE(handler, handler_new, chain);
835 		return (0);
836 	}
837 
838 	TAILQ_INSERT_TAIL(&sc->psc_bar_handler[baridx], handler_new, chain);
839 
840 	return (0);
841 }
842 
843 static int
passthru_legacy_config(nvlist_t * nvl,const char * opts)844 passthru_legacy_config(nvlist_t *nvl, const char *opts)
845 {
846 	const char *cp;
847 	char *tofree;
848 	char value[16];
849 	int bus, slot, func;
850 
851 	if (opts == NULL)
852 		return (0);
853 
854 	cp = strchr(opts, ',');
855 
856 	if (strncmp(opts, "ppt", strlen("ppt")) == 0) {
857 		tofree = strndup(opts, cp - opts);
858 		set_config_value_node(nvl, "pptdev", tofree);
859 		free(tofree);
860 	} else if (sscanf(opts, "pci0:%d:%d:%d", &bus, &slot, &func) == 3 ||
861 	    sscanf(opts, "pci%d:%d:%d", &bus, &slot, &func) == 3 ||
862 	    sscanf(opts, "%d/%d/%d", &bus, &slot, &func) == 3) {
863 		snprintf(value, sizeof(value), "%d", bus);
864 		set_config_value_node(nvl, "bus", value);
865 		snprintf(value, sizeof(value), "%d", slot);
866 		set_config_value_node(nvl, "slot", value);
867 		snprintf(value, sizeof(value), "%d", func);
868 		set_config_value_node(nvl, "func", value);
869 	} else {
870 		EPRINTLN("passthru: invalid options \"%s\"", opts);
871 		return (-1);
872 	}
873 
874 	if (cp == NULL) {
875 		return (0);
876 	}
877 
878 	return (pci_parse_legacy_config(nvl, cp + 1));
879 }
880 
881 static int
passthru_init_rom(struct passthru_softc * const sc,const char * const romfile)882 passthru_init_rom(struct passthru_softc *const sc, const char *const romfile)
883 {
884 	if (romfile == NULL) {
885 		return (0);
886 	}
887 
888 	const int fd = open(romfile, O_RDONLY);
889 	if (fd < 0) {
890 		warnx("%s: can't open romfile \"%s\"", __func__, romfile);
891 		return (-1);
892 	}
893 
894 	struct stat sbuf;
895 	if (fstat(fd, &sbuf) < 0) {
896 		warnx("%s: can't fstat romfile \"%s\"", __func__, romfile);
897 		close(fd);
898 		return (-1);
899 	}
900 	const uint64_t rom_size = sbuf.st_size;
901 
902 	void *const rom_data = mmap(NULL, rom_size, PROT_READ, MAP_SHARED, fd,
903 	    0);
904 	if (rom_data == MAP_FAILED) {
905 		warnx("%s: unable to mmap romfile \"%s\" (%d)", __func__,
906 		    romfile, errno);
907 		close(fd);
908 		return (-1);
909 	}
910 
911 	void *rom_addr;
912 	int error = pci_emul_alloc_rom(sc->psc_pi, rom_size, &rom_addr);
913 	if (error) {
914 		warnx("%s: failed to alloc rom segment", __func__);
915 		munmap(rom_data, rom_size);
916 		close(fd);
917 		return (error);
918 	}
919 	memcpy(rom_addr, rom_data, rom_size);
920 
921 	sc->psc_bar[PCI_ROM_IDX].type = PCIBAR_ROM;
922 	sc->psc_bar[PCI_ROM_IDX].addr = (uint64_t)rom_addr;
923 	sc->psc_bar[PCI_ROM_IDX].size = rom_size;
924 
925 	munmap(rom_data, rom_size);
926 	close(fd);
927 
928 	return (0);
929 }
930 
931 static bool
passthru_lookup_pptdev(const char * name,int * bus,int * slot,int * func)932 passthru_lookup_pptdev(const char *name, int *bus, int *slot, int *func)
933 {
934 	struct pci_conf_io pc;
935 	struct pci_conf conf[1];
936 	struct pci_match_conf patterns[1];
937 	char *cp;
938 
939 	bzero(&pc, sizeof(struct pci_conf_io));
940 	pc.match_buf_len = sizeof(conf);
941 	pc.matches = conf;
942 
943 	bzero(&patterns, sizeof(patterns));
944 
945 	/*
946 	 * The pattern structure requires the unit to be split out from
947 	 * the driver name.  Walk backwards from the end of the name to
948 	 * find the start of the unit.
949 	 */
950 	cp = strchr(name, '\0');
951 	assert(cp != NULL);
952 	while (cp != name && isdigit(cp[-1]))
953 		cp--;
954 	if (cp == name || !isdigit(*cp)) {
955 		EPRINTLN("Invalid passthru device name %s", name);
956 		return (false);
957 	}
958 	if ((size_t)(cp - name) + 1 > sizeof(patterns[0].pd_name)) {
959 		EPRINTLN("Passthru device name %s is too long", name);
960 		return (false);
961 	}
962 	memcpy(patterns[0].pd_name, name, cp - name);
963 	patterns[0].pd_unit = strtol(cp, &cp, 10);
964 	if (*cp != '\0') {
965 		EPRINTLN("Invalid passthru device name %s", name);
966 		return (false);
967 	}
968 	patterns[0].flags = PCI_GETCONF_MATCH_NAME | PCI_GETCONF_MATCH_UNIT;
969 	pc.num_patterns = 1;
970 	pc.pat_buf_len = sizeof(patterns);
971 	pc.patterns = patterns;
972 
973 	if (ioctl(pcifd, PCIOCGETCONF, &pc) == -1) {
974 		EPRINTLN("ioctl(PCIOCGETCONF): %s", strerror(errno));
975 		return (false);
976 	}
977 	if (pc.status != PCI_GETCONF_LAST_DEVICE &&
978 	    pc.status != PCI_GETCONF_MORE_DEVS) {
979 		EPRINTLN("error returned from PCIOCGETCONF ioctl");
980 		return (false);
981 	}
982 	if (pc.num_matches == 0) {
983 		EPRINTLN("Passthru device %s not found", name);
984 		return (false);
985 	}
986 
987 	if (conf[0].pc_sel.pc_domain != 0) {
988 		EPRINTLN("Passthru device %s on unsupported domain", name);
989 		return (false);
990 	}
991 	*bus = conf[0].pc_sel.pc_bus;
992 	*slot = conf[0].pc_sel.pc_dev;
993 	*func = conf[0].pc_sel.pc_func;
994 	return (true);
995 }
996 
997 static int
passthru_init(struct pci_devinst * pi,nvlist_t * nvl)998 passthru_init(struct pci_devinst *pi, nvlist_t *nvl)
999 {
1000 	int bus, slot, func, error, memflags;
1001 	struct passthru_softc *sc;
1002 	struct passthru_dev **devpp;
1003 	struct passthru_dev *devp, *dev = NULL;
1004 	const char *value;
1005 
1006 	sc = NULL;
1007 	error = 1;
1008 
1009 	memflags = vm_get_memflags(pi->pi_vmctx);
1010 	if (!(memflags & VM_MEM_F_WIRED)) {
1011 		warnx("passthru requires guest memory to be wired");
1012 		return (error);
1013 	}
1014 
1015 	if (pcifd < 0 && pcifd_init()) {
1016 		return (error);
1017 	}
1018 
1019 #define GET_INT_CONFIG(var, name) do {					\
1020 	value = get_config_value_node(nvl, name);			\
1021 	if (value == NULL) {						\
1022 		EPRINTLN("passthru: missing required %s setting", name); \
1023 		return (error);						\
1024 	}								\
1025 	var = atoi(value);						\
1026 } while (0)
1027 
1028 	value = get_config_value_node(nvl, "pptdev");
1029 	if (value != NULL) {
1030 		if (!passthru_lookup_pptdev(value, &bus, &slot, &func))
1031 			return (error);
1032 	} else {
1033 		GET_INT_CONFIG(bus, "bus");
1034 		GET_INT_CONFIG(slot, "slot");
1035 		GET_INT_CONFIG(func, "func");
1036 	}
1037 
1038 	if (vm_assign_pptdev(pi->pi_vmctx, bus, slot, func) != 0) {
1039 		if (errno == ENOENT) {
1040 			EPRINTLN(
1041 		    "PCI device at %d/%d/%d is not using the ppt driver",
1042 			    bus, slot, func);
1043 		} else {
1044 			EPRINTLN("vm_assign_pptdev: %s", strerror(errno));
1045 		}
1046 		goto done;
1047 	}
1048 
1049 	sc = calloc(1, sizeof(struct passthru_softc));
1050 	if (sc == NULL)
1051 		goto done;
1052 	pthread_mutex_init(&sc->psc_io_mtx, NULL);
1053 
1054 	pi->pi_arg = sc;
1055 	sc->psc_pi = pi;
1056 
1057 	for (uint8_t i = 0; i < PCI_BARMAX_WITH_ROM + 1; ++i)
1058 		TAILQ_INIT(&sc->psc_bar_handler[i]);
1059 
1060 	/* initialize config space */
1061 	if ((error = cfginit(pi, bus, slot, func)) != 0)
1062 		goto done;
1063 
1064 	/* initialize ROM */
1065 	if ((error = passthru_init_rom(sc,
1066             get_config_value_node(nvl, "rom"))) != 0)
1067 		goto done;
1068 
1069 	/* Emulate most PCI header register. */
1070 	if ((error = set_pcir_handler(sc, 0, PCIR_MAXLAT + 1,
1071 	    passthru_cfgread_emulate, passthru_cfgwrite_emulate)) != 0)
1072 		goto done;
1073 
1074 	/* Allow access to the physical status register. */
1075 	if ((error = set_pcir_handler(sc, PCIR_COMMAND, 0x04, NULL, NULL)) != 0)
1076 		goto done;
1077 
1078 	SET_FOREACH(devpp, passthru_dev_set) {
1079 		devp = *devpp;
1080 		assert(devp->probe != NULL);
1081 		if (devp->probe(pi) == 0) {
1082 			dev = devp;
1083 			break;
1084 		}
1085 	}
1086 
1087 	if (dev != NULL) {
1088 		error = dev->init(pi, nvl);
1089 		if (error != 0)
1090 			goto done;
1091 	}
1092 
1093 	error = 0;		/* success */
1094 done:
1095 	if (error) {
1096 		if (dev != NULL)
1097 			dev->deinit(pi);
1098 		if (sc != NULL)
1099 			pthread_mutex_destroy(&sc->psc_io_mtx);
1100 		free(sc);
1101 		vm_unassign_pptdev(pi->pi_vmctx, bus, slot, func);
1102 	}
1103 	return (error);
1104 }
1105 
1106 static int
msicap_access(struct passthru_softc * sc,int coff)1107 msicap_access(struct passthru_softc *sc, int coff)
1108 {
1109 	int caplen;
1110 
1111 	if (sc->psc_msi.capoff == 0)
1112 		return (0);
1113 
1114 	caplen = msi_caplen(sc->psc_msi.msgctrl);
1115 
1116 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
1117 		return (1);
1118 	else
1119 		return (0);
1120 }
1121 
1122 static int
msixcap_access(struct passthru_softc * sc,int coff)1123 msixcap_access(struct passthru_softc *sc, int coff)
1124 {
1125 	if (sc->psc_msix.capoff == 0)
1126 		return (0);
1127 
1128 	return (coff >= sc->psc_msix.capoff &&
1129 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
1130 }
1131 
1132 #define	PASSTHRU_DEVCTL_VIRT	(PCIEM_CTL_MAX_PAYLOAD | \
1133 				 PCIEM_CTL_MAX_READ_REQUEST)
1134 #define	PASSTHRU_DEVCTL_NO_WRITE	PCIEM_CTL_PHANTHOM_FUNCS
1135 #define	PASSTHRU_DEVCTL2_VIRT	(PCIEM_CTL2_COMP_TIMO_VAL | \
1136 				 PCIEM_CTL2_COMP_TIMO_DISABLE)
1137 #define	PASSTHRU_PMCSR_VIRT	(PCIM_PSTAT_DMASK | \
1138 				 PCIM_PSTAT_NOSOFTRESET)
1139 
1140 static uint32_t
passthru_cfg_field_mask(int coff,int bytes,int fieldoff,uint16_t mask)1141 passthru_cfg_field_mask(int coff, int bytes, int fieldoff, uint16_t mask)
1142 {
1143 	uint32_t access_mask;
1144 	int i, pos;
1145 
1146 	access_mask = 0;
1147 	for (i = 0; i < bytes; i++) {
1148 		pos = coff + i;
1149 		if (pos >= fieldoff && pos < fieldoff + 2)
1150 			access_mask |= ((mask >> ((pos - fieldoff) * NBBY)) &
1151 			    0xff) << (i * NBBY);
1152 	}
1153 	return (access_mask);
1154 }
1155 
1156 static uint32_t
passthru_cfg_field_value(int coff,int bytes,int fieldoff,uint16_t value)1157 passthru_cfg_field_value(int coff, int bytes, int fieldoff, uint16_t value)
1158 {
1159 	uint32_t access_value;
1160 	int i, pos;
1161 
1162 	access_value = 0;
1163 	for (i = 0; i < bytes; i++) {
1164 		pos = coff + i;
1165 		if (pos >= fieldoff && pos < fieldoff + 2)
1166 			access_value |= ((value >> ((pos - fieldoff) * NBBY)) &
1167 			    0xff) << (i * NBBY);
1168 	}
1169 	return (access_value);
1170 }
1171 
1172 /*
1173  * Replace selected bits of a 16-bit field within an arbitrarily aligned
1174  * configuration-space access.  Preserve every byte and field bit outside
1175  * the supplied mask.
1176  */
1177 static uint32_t
passthru_cfg_overlay_field(int coff,int bytes,uint32_t access,int fieldoff,uint16_t field,uint16_t field_mask)1178 passthru_cfg_overlay_field(int coff, int bytes, uint32_t access, int fieldoff,
1179     uint16_t field, uint16_t field_mask)
1180 {
1181 	uint32_t access_mask;
1182 
1183 	access_mask = passthru_cfg_field_mask(coff, bytes, fieldoff,
1184 	    field_mask);
1185 	return ((access & ~access_mask) |
1186 	    (passthru_cfg_field_value(coff, bytes, fieldoff, field) &
1187 	    access_mask));
1188 }
1189 
1190 static void
passthru_cfg_update_field(int coff,int bytes,uint32_t value,int fieldoff,uint16_t mask,uint16_t * field)1191 passthru_cfg_update_field(int coff, int bytes, uint32_t value, int fieldoff,
1192     uint16_t mask, uint16_t *field)
1193 {
1194 	uint16_t byte_mask, byte_value;
1195 	int i, pos, shift;
1196 
1197 	for (i = 0; i < bytes; i++) {
1198 		pos = coff + i;
1199 		if (pos < fieldoff || pos >= fieldoff + 2)
1200 			continue;
1201 		shift = (pos - fieldoff) * NBBY;
1202 		byte_mask = mask & (0xff << shift);
1203 		byte_value = ((value >> (i * NBBY)) & 0xff) << shift;
1204 		*field = (*field & ~byte_mask) | (byte_value & byte_mask);
1205 	}
1206 }
1207 
1208 static void
passthru_reset_interrupt_state(struct passthru_softc * sc)1209 passthru_reset_interrupt_state(struct passthru_softc *sc)
1210 {
1211 	struct pci_devinst *pi;
1212 	uint16_t msgctrl;
1213 	int caplen, i;
1214 
1215 	pi = sc->psc_pi;
1216 	if (sc->psc_msi.capoff != 0) {
1217 		caplen = msi_caplen(sc->psc_msi.msgctrl);
1218 		msgctrl = pci_get_cfgdata16(pi, sc->psc_msi.capoff + 2);
1219 		msgctrl &= ~(PCIM_MSICTRL_MME_MASK | PCIM_MSICTRL_MSI_ENABLE);
1220 		memset(pi->pi_cfgdata + sc->psc_msi.capoff + 4, 0, caplen - 4);
1221 		pci_set_cfgdata16(pi, sc->psc_msi.capoff + 2, msgctrl);
1222 		pi->pi_msi.enabled = 0;
1223 		pi->pi_msi.addr = 0;
1224 		pi->pi_msi.msg_data = 0;
1225 		pi->pi_msi.maxmsgnum = 0;
1226 	}
1227 	if (sc->psc_msix.capoff != 0) {
1228 		msgctrl = pci_get_cfgdata16(pi, sc->psc_msix.capoff + 2);
1229 		msgctrl &= ~(PCIM_MSIXCTRL_MSIX_ENABLE |
1230 		    PCIM_MSIXCTRL_FUNCTION_MASK);
1231 		pci_set_cfgdata16(pi, sc->psc_msix.capoff + 2, msgctrl);
1232 		pi->pi_msix.enabled = 0;
1233 		pi->pi_msix.function_mask = 0;
1234 		bzero(pi->pi_msix.table, pi->pi_msix.table_count *
1235 		    sizeof(pi->pi_msix.table[0]));
1236 		for (i = 0; i < pi->pi_msix.table_count; i++)
1237 			pi->pi_msix.table[i].vector_control =
1238 			    PCIM_MSIX_VCTRL_MASK;
1239 	}
1240 }
1241 
1242 static void
passthru_reset_capability_state(struct passthru_softc * sc)1243 passthru_reset_capability_state(struct passthru_softc *sc)
1244 {
1245 	uint16_t devctl, guest_mps;
1246 	int offset;
1247 
1248 	/* MPS is explicitly preserved across FLR by the PCIe specification. */
1249 	guest_mps = sc->psc_pcie.devctl & PCIEM_CTL_MAX_PAYLOAD;
1250 	offset = sc->psc_pcie.capoff + PCIER_DEVICE_CTL;
1251 	devctl = passthru_read_config(&sc->psc_sel, offset, 2);
1252 	if (devctl != 0xffff) {
1253 		devctl &= ~PCIEM_CTL_MAX_READ_REQUEST;
1254 		devctl |= sc->psc_pcie.reset_devctl &
1255 		    PCIEM_CTL_MAX_READ_REQUEST;
1256 		passthru_write_config(&sc->psc_sel, offset, 2, devctl);
1257 	}
1258 	sc->psc_pcie.devctl =
1259 	    (sc->psc_pcie.reset_devctl & ~PCIEM_CTL_MAX_PAYLOAD) | guest_mps;
1260 	if (sc->psc_pcie.has_devctl2)
1261 		sc->psc_pcie.devctl2 = sc->psc_pcie.reset_devctl2;
1262 	if (sc->psc_pm.capoff != 0)
1263 		sc->psc_pm.pmcsr = sc->psc_pm.reset_pmcsr;
1264 }
1265 
1266 static int
passthru_reset(struct passthru_softc * sc)1267 passthru_reset(struct passthru_softc *sc)
1268 {
1269 	struct pci_devinst *pi;
1270 	uint16_t command;
1271 	int error;
1272 
1273 	pi = sc->psc_pi;
1274 	command = pci_get_cfgdata16(pi, PCIR_COMMAND);
1275 
1276 	/*
1277 	 * Stop trapped BAR accesses and drain any handler already touching the
1278 	 * device.  pci_cfgrw() holds pi_cfg_lock for this entire transaction,
1279 	 * so another vCPU cannot re-enable or move a BAR around the reset.
1280 	 */
1281 	pthread_mutex_lock(&sc->psc_io_mtx);
1282 	sc->psc_resetting = true;
1283 	pthread_mutex_unlock(&sc->psc_io_mtx);
1284 
1285 	if (pi->pi_lintr.pin != 0)
1286 		pci_lintr_deassert(pi);
1287 	pci_set_cfgdata16(pi, PCIR_COMMAND, 0);
1288 	pci_emul_cmd_changed(pi, command);
1289 
1290 	if (vm_reset_pptdev(pi->pi_vmctx, sc->psc_sel.pc_bus,
1291 	    sc->psc_sel.pc_dev, sc->psc_sel.pc_func) == 0)
1292 		error = 0;
1293 	else
1294 		error = errno;
1295 
1296 	/*
1297 	 * EIO means PPT crossed the destructive preparation boundary.  The FLR
1298 	 * either ran or failed after host interrupt resources were torn down, so
1299 	 * the corresponding guest state must be discarded in either case.
1300 	 */
1301 	if (error != 0 && error != EIO) {
1302 		pci_set_cfgdata16(pi, PCIR_COMMAND, command);
1303 		pci_emul_cmd_changed(pi, 0);
1304 	} else {
1305 		passthru_reset_interrupt_state(sc);
1306 		passthru_reset_capability_state(sc);
1307 	}
1308 	pthread_mutex_lock(&sc->psc_io_mtx);
1309 	sc->psc_resetting = false;
1310 	pthread_mutex_unlock(&sc->psc_io_mtx);
1311 	return (error);
1312 }
1313 
1314 static int
passthru_cfgread_default(struct passthru_softc * sc,struct pci_devinst * pi __unused,int coff,int bytes,uint32_t * rv)1315 passthru_cfgread_default(struct passthru_softc *sc,
1316     struct pci_devinst *pi __unused, int coff, int bytes, uint32_t *rv)
1317 {
1318 	/*
1319 	 * MSI capability is emulated.
1320 	 */
1321 	if (msicap_access(sc, coff) || msixcap_access(sc, coff))
1322 		return (-1);
1323 
1324 	/*
1325 	 * Emulate the command register.  If a single read reads both the
1326 	 * command and status registers, read the status register from the
1327 	 * device's config space.
1328 	 */
1329 	if (coff == PCIR_COMMAND) {
1330 		uint32_t st;
1331 
1332 		if (bytes <= 2)
1333 			return (-1);
1334 		st = passthru_read_config(&sc->psc_sel, PCIR_STATUS, 2);
1335 		*rv = (st << 16) | pci_get_cfgdata16(pi, PCIR_COMMAND);
1336 		return (0);
1337 	}
1338 
1339 	/* Everything else just read from the device's config space. */
1340 	*rv = passthru_read_config(&sc->psc_sel, coff, bytes);
1341 	if (sc->psc_pm.capoff != 0) {
1342 		int pmcsr;
1343 
1344 		pmcsr = sc->psc_pm.capoff + PCIR_POWER_STATUS;
1345 		*rv = passthru_cfg_overlay_field(coff, bytes, *rv, pmcsr,
1346 		    sc->psc_pm.pmcsr, PASSTHRU_PMCSR_VIRT);
1347 	}
1348 	if (sc->psc_pcie.capoff != 0) {
1349 		int devctl;
1350 
1351 		devctl = sc->psc_pcie.capoff + PCIER_DEVICE_CTL;
1352 		*rv = passthru_cfg_overlay_field(coff, bytes, *rv, devctl,
1353 		    sc->psc_pcie.devctl, PASSTHRU_DEVCTL_VIRT);
1354 		if (sc->psc_pcie.has_devctl2) {
1355 			devctl = sc->psc_pcie.capoff + PCIER_DEVICE_CTL2;
1356 			*rv = passthru_cfg_overlay_field(coff, bytes, *rv, devctl,
1357 			    sc->psc_pcie.devctl2, PASSTHRU_DEVCTL2_VIRT);
1358 		}
1359 	}
1360 
1361 	return (0);
1362 }
1363 
1364 int
passthru_cfgread_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t * rv __unused)1365 passthru_cfgread_emulate(struct passthru_softc *sc __unused,
1366     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1367     uint32_t *rv __unused)
1368 {
1369 	return (-1);
1370 }
1371 
1372 static int
passthru_cfgread(struct pci_devinst * pi,int coff,int bytes,uint32_t * rv)1373 passthru_cfgread(struct pci_devinst *pi, int coff, int bytes, uint32_t *rv)
1374 {
1375 	struct passthru_softc *sc;
1376 
1377 	sc = pi->pi_arg;
1378 
1379 	if (sc->psc_pcir_rhandler[coff] != NULL)
1380 		return (sc->psc_pcir_rhandler[coff](sc, pi, coff, bytes, rv));
1381 
1382 	return (passthru_cfgread_default(sc, pi, coff, bytes, rv));
1383 }
1384 
1385 static int
passthru_cfgwrite_default(struct passthru_softc * sc,struct pci_devinst * pi,int coff,int bytes,uint32_t val)1386 passthru_cfgwrite_default(struct passthru_softc *sc, struct pci_devinst *pi,
1387     int coff, int bytes, uint32_t val)
1388 {
1389 	uint32_t flr_mask, transport_mask;
1390 	uint16_t physical_devctl, physical_pmcsr;
1391 	int devctl, devctl2, host_mps, guest_mrrs, pmcsr;
1392 	int error, msix_table_entries, i;
1393 	uint16_t cmd_old;
1394 
1395 	/*
1396 	 * MSI capability is emulated
1397 	 */
1398 	if (msicap_access(sc, coff)) {
1399 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
1400 		    PCIY_MSI);
1401 		error = vm_setup_pptdev_msi(pi->pi_vmctx, sc->psc_sel.pc_bus,
1402 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
1403 			pi->pi_msi.addr, pi->pi_msi.msg_data,
1404 			pi->pi_msi.maxmsgnum);
1405 		if (error != 0)
1406 			err(1, "vm_setup_pptdev_msi");
1407 		return (0);
1408 	}
1409 
1410 	if (msixcap_access(sc, coff)) {
1411 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
1412 		    PCIY_MSIX);
1413 		if (pi->pi_msix.enabled) {
1414 			msix_table_entries = pi->pi_msix.table_count;
1415 			for (i = 0; i < msix_table_entries; i++) {
1416 				error = vm_setup_pptdev_msix(pi->pi_vmctx,
1417 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1418 				    sc->psc_sel.pc_func, i,
1419 				    pi->pi_msix.table[i].addr,
1420 				    pi->pi_msix.table[i].msg_data,
1421 				    pi->pi_msix.table[i].vector_control);
1422 
1423 				if (error)
1424 					err(1, "vm_setup_pptdev_msix");
1425 			}
1426 		} else {
1427 			error = vm_disable_pptdev_msix(pi->pi_vmctx,
1428 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1429 			    sc->psc_sel.pc_func);
1430 			if (error)
1431 				err(1, "vm_disable_pptdev_msix");
1432 		}
1433 		return (0);
1434 	}
1435 
1436 	/*
1437 	 * A physical D3hot-to-D0 transition may reset the function and clear
1438 	 * Command behind bhyve's emulated copy.  Keep the physical D-state
1439 	 * host-owned, emulate the guest D-state, and advertise No_Soft_Reset so
1440 	 * the guest does not rely on this cycle as a function reset.
1441 	 */
1442 	pmcsr = sc->psc_pm.capoff + PCIR_POWER_STATUS;
1443 	if (sc->psc_pm.capoff != 0 && coff < pmcsr + 2 &&
1444 	    coff + bytes > pmcsr) {
1445 		physical_pmcsr = passthru_read_config(&sc->psc_sel, pmcsr, 2);
1446 		if (physical_pmcsr == 0xffff) {
1447 			warnx("configuration space unavailable for passthru "
1448 			    "device %d/%d/%d", sc->psc_sel.pc_bus,
1449 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
1450 			return (0);
1451 		}
1452 		passthru_cfg_update_field(coff, bytes, val, pmcsr,
1453 		    PCIM_PSTAT_DMASK, &sc->psc_pm.pmcsr);
1454 		val = passthru_cfg_overlay_field(coff, bytes, val, pmcsr,
1455 		    physical_pmcsr, PASSTHRU_PMCSR_VIRT);
1456 		passthru_write_config(&sc->psc_sel, coff, bytes, val);
1457 		return (0);
1458 	}
1459 
1460 	/*
1461 	 * A direct FLR would clear physical Command while the guest sees its
1462 	 * emulated copy remain enabled.  Route FLR through ppt so it restores
1463 	 * host-owned state.  MPS is shared-path policy, and Phantom Functions
1464 	 * Enable changes IOMMU-visible requester IDs, so keep both host-owned.
1465 	 * Floor physical MRRS at physical MPS because the guest lacks the
1466 	 * hierarchy view.  ppt also applies FLR quirks for VFs such as 82599.
1467 	 */
1468 	devctl = sc->psc_pcie.capoff + PCIER_DEVICE_CTL;
1469 	if (sc->psc_pcie.capoff != 0 && coff < devctl + 2 &&
1470 	    coff + bytes > devctl) {
1471 		transport_mask = passthru_cfg_field_mask(coff, bytes, devctl,
1472 		    PASSTHRU_DEVCTL_VIRT);
1473 		physical_devctl = passthru_read_config(&sc->psc_sel, devctl, 2);
1474 		if (physical_devctl == 0xffff) {
1475 			warnx("configuration space unavailable for passthru "
1476 			    "device %d/%d/%d", sc->psc_sel.pc_bus,
1477 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
1478 			return (0);
1479 		}
1480 		passthru_cfg_update_field(coff, bytes, val, devctl,
1481 		    PASSTHRU_DEVCTL_VIRT, &sc->psc_pcie.devctl);
1482 		if ((transport_mask & passthru_cfg_field_mask(coff, bytes,
1483 		    devctl, PCIEM_CTL_MAX_READ_REQUEST)) != 0) {
1484 			host_mps = (physical_devctl & PCIEM_CTL_MAX_PAYLOAD) >> 5;
1485 			guest_mrrs = (sc->psc_pcie.devctl &
1486 			    PCIEM_CTL_MAX_READ_REQUEST) >> 12;
1487 			if (guest_mrrs <= 5) {
1488 				if (guest_mrrs < host_mps)
1489 					guest_mrrs = host_mps;
1490 				physical_devctl &= ~PCIEM_CTL_MAX_READ_REQUEST;
1491 				physical_devctl |= guest_mrrs << 12;
1492 			}
1493 		}
1494 		val = passthru_cfg_overlay_field(coff, bytes, val, devctl,
1495 		    physical_devctl,
1496 		    PASSTHRU_DEVCTL_VIRT | PASSTHRU_DEVCTL_NO_WRITE);
1497 
1498 		flr_mask = passthru_cfg_field_mask(coff, bytes, devctl,
1499 		    PCIEM_CTL_INITIATE_FLR);
1500 		passthru_write_config(&sc->psc_sel, coff, bytes,
1501 		    val & ~flr_mask);
1502 		if ((val & flr_mask) != 0) {
1503 			error = passthru_reset(sc);
1504 			if (error != 0)
1505 				warnx("failed to reset passthru device "
1506 				    "%d/%d/%d: %s", sc->psc_sel.pc_bus,
1507 				    sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
1508 				    strerror(error));
1509 		}
1510 		return (0);
1511 	}
1512 
1513 	/*
1514 	 * Completion Timeout controls how long the host must protect against an
1515 	 * in-flight completion after a forced FLR.  Keep the physical policy
1516 	 * host-owned so a guest cannot extend the reset ioctl for tens of
1517 	 * seconds, but retain a guest-visible value for normal PCI semantics.
1518 	 */
1519 	devctl2 = sc->psc_pcie.capoff + PCIER_DEVICE_CTL2;
1520 	if (sc->psc_pcie.has_devctl2 && coff < devctl2 + 2 &&
1521 	    coff + bytes > devctl2) {
1522 		physical_devctl = passthru_read_config(&sc->psc_sel, devctl2, 2);
1523 		if (physical_devctl == 0xffff) {
1524 			warnx("configuration space unavailable for passthru "
1525 			    "device %d/%d/%d", sc->psc_sel.pc_bus,
1526 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
1527 			return (0);
1528 		}
1529 		passthru_cfg_update_field(coff, bytes, val, devctl2,
1530 		    PASSTHRU_DEVCTL2_VIRT, &sc->psc_pcie.devctl2);
1531 		val = passthru_cfg_overlay_field(coff, bytes, val, devctl2,
1532 		    physical_devctl, PASSTHRU_DEVCTL2_VIRT);
1533 		passthru_write_config(&sc->psc_sel, coff, bytes, val);
1534 		return (0);
1535 	}
1536 
1537 	/*
1538 	 * The command register is emulated, but the status register
1539 	 * is passed through.
1540 	 */
1541 	if (coff == PCIR_COMMAND) {
1542 		if (bytes <= 2)
1543 			return (-1);
1544 
1545 		/* Update the physical status register. */
1546 		passthru_write_config(&sc->psc_sel, PCIR_STATUS, val >> 16, 2);
1547 
1548 		/* Update the virtual command register. */
1549 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
1550 		pci_set_cfgdata16(pi, PCIR_COMMAND, val & 0xffff);
1551 		pci_emul_cmd_changed(pi, cmd_old);
1552 		return (0);
1553 	}
1554 
1555 	passthru_write_config(&sc->psc_sel, coff, bytes, val);
1556 
1557 	return (0);
1558 }
1559 
1560 int
passthru_cfgwrite_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t val __unused)1561 passthru_cfgwrite_emulate(struct passthru_softc *sc __unused,
1562     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1563     uint32_t val __unused)
1564 {
1565 	return (-1);
1566 }
1567 
1568 static int
passthru_cfgwrite(struct pci_devinst * pi,int coff,int bytes,uint32_t val)1569 passthru_cfgwrite(struct pci_devinst *pi, int coff, int bytes, uint32_t val)
1570 {
1571 	struct passthru_softc *sc;
1572 
1573 	sc = pi->pi_arg;
1574 
1575 	if (sc->psc_pcir_whandler[coff] != NULL)
1576 		return (sc->psc_pcir_whandler[coff](sc, pi, coff, bytes, val));
1577 
1578 	return (passthru_cfgwrite_default(sc, pi, coff, bytes, val));
1579 }
1580 
1581 static void
passthru_write_locked(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)1582 passthru_write_locked(struct pci_devinst *pi, int baridx, uint64_t offset,
1583     int size, uint64_t value)
1584 {
1585 	struct passthru_softc *sc;
1586 	struct passthru_bar_handler *handler;
1587 	struct pci_bar_ioreq pio;
1588 
1589 	sc = pi->pi_arg;
1590 
1591 	if (baridx == pci_msix_table_bar(pi)) {
1592 		msix_table_write(sc, offset, size, value);
1593 	} else {
1594 		assert(size == 1 || size == 2 || size == 4);
1595 
1596 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1597 			if (offset >= handler->off + handler->size) {
1598 				continue;
1599 			} else if (offset < handler->off) {
1600 				assert(offset + size < handler->off);
1601 				/*
1602 				 * The list is sorted in ascending order, so all
1603 				 * remaining handlers will have an even larger
1604 				 * offset.
1605 				 */
1606 				break;
1607 			}
1608 
1609 			assert(offset + size <= handler->off + handler->size);
1610 
1611 			handler->write(pi, baridx,
1612 			    offset - handler->off, size, value);
1613 			return;
1614 		}
1615 
1616 		bzero(&pio, sizeof(pio));
1617 		pio.pbi_sel = sc->psc_sel;
1618 		pio.pbi_op = PCIBARIO_WRITE;
1619 		pio.pbi_bar = baridx;
1620 		pio.pbi_offset = (uint32_t)offset;
1621 		pio.pbi_width = size;
1622 		pio.pbi_value = (uint32_t)value;
1623 
1624 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1625 	}
1626 }
1627 
1628 static uint64_t
passthru_read_locked(struct pci_devinst * pi,int baridx,uint64_t offset,int size)1629 passthru_read_locked(struct pci_devinst *pi, int baridx, uint64_t offset,
1630     int size)
1631 {
1632 	struct passthru_softc *sc;
1633 	struct passthru_bar_handler *handler;
1634 	struct pci_bar_ioreq pio;
1635 	uint64_t val;
1636 
1637 	sc = pi->pi_arg;
1638 
1639 	if (baridx == pci_msix_table_bar(pi)) {
1640 		val = msix_table_read(sc, offset, size);
1641 	} else {
1642 		assert(size == 1 || size == 2 || size == 4);
1643 
1644 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1645 			if (offset >= handler->off + handler->size) {
1646 				continue;
1647 			} else if (offset < handler->off) {
1648 				assert(offset + size < handler->off);
1649 				/*
1650 				 * The list is sorted in ascending order, so all
1651 				 * remaining handlers will have an even larger
1652 				 * offset.
1653 				 */
1654 				break;
1655 			}
1656 
1657 			assert(offset + size <= handler->off + handler->size);
1658 
1659 			return (handler->read(pi, baridx,
1660 			    offset - handler->off, size));
1661 		}
1662 
1663 		bzero(&pio, sizeof(pio));
1664 		pio.pbi_sel = sc->psc_sel;
1665 		pio.pbi_op = PCIBARIO_READ;
1666 		pio.pbi_bar = baridx;
1667 		pio.pbi_offset = (uint32_t)offset;
1668 		pio.pbi_width = size;
1669 
1670 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1671 
1672 		val = pio.pbi_value;
1673 	}
1674 
1675 	return (val);
1676 }
1677 
1678 static void
passthru_write(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)1679 passthru_write(struct pci_devinst *pi, int baridx, uint64_t offset, int size,
1680     uint64_t value)
1681 {
1682 	struct passthru_softc *sc;
1683 
1684 	sc = pi->pi_arg;
1685 	pthread_mutex_lock(&sc->psc_io_mtx);
1686 	if (!sc->psc_resetting)
1687 		passthru_write_locked(pi, baridx, offset, size, value);
1688 	pthread_mutex_unlock(&sc->psc_io_mtx);
1689 }
1690 
1691 static uint64_t
passthru_read(struct pci_devinst * pi,int baridx,uint64_t offset,int size)1692 passthru_read(struct pci_devinst *pi, int baridx, uint64_t offset, int size)
1693 {
1694 	struct passthru_softc *sc;
1695 	uint64_t value;
1696 
1697 	sc = pi->pi_arg;
1698 	pthread_mutex_lock(&sc->psc_io_mtx);
1699 	if (sc->psc_resetting)
1700 		value = UINT64_MAX;
1701 	else
1702 		value = passthru_read_locked(pi, baridx, offset, size);
1703 	pthread_mutex_unlock(&sc->psc_io_mtx);
1704 	return (value);
1705 }
1706 
1707 static int
passthru_mmio_map(struct pci_devinst * pi,int baridx,int enabled,uint64_t address,uint64_t off,uint64_t size)1708 passthru_mmio_map(struct pci_devinst *pi, int baridx, int enabled,
1709     uint64_t address, uint64_t off, uint64_t size)
1710 {
1711 	struct passthru_softc *sc;
1712 
1713 	sc = pi->pi_arg;
1714 	if (!enabled) {
1715 		if (vm_unmap_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1716 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1717 		    size) != 0) {
1718 			EPRINTLN("pci_passthru: unmap_pptdev_mmio failed: %s",
1719 			    strerror(errno));
1720 			return (-1);
1721 		}
1722 	} else {
1723 		if (vm_map_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1724 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1725 		    size, sc->psc_bar[baridx].addr + off) != 0) {
1726 			EPRINTLN("pci_passthru: map_pptdev_mmio failed: %s",
1727 			    strerror(errno));
1728 			return (-1);
1729 		}
1730 	}
1731 
1732 	return (0);
1733 }
1734 
1735 static void
passthru_msix_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1736 passthru_msix_addr(struct pci_devinst *pi, int baridx, int enabled,
1737     uint64_t address)
1738 {
1739 	size_t remaining;
1740 	uint32_t table_size, table_offset;
1741 
1742 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
1743 	if (table_offset > 0) {
1744 		(void)passthru_mmio_map(pi, baridx, enabled, address, 0,
1745 		    table_offset);
1746 	}
1747 	table_size = pi->pi_msix.table_offset - table_offset;
1748 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
1749 	table_size = roundup2(table_size, 4096);
1750 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
1751 	if (remaining > 0) {
1752 		(void)passthru_mmio_map(pi, baridx, enabled, address,
1753 		    table_offset + table_size, remaining);
1754 	}
1755 }
1756 
1757 static void
passthru_mmio_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1758 passthru_mmio_addr(struct pci_devinst *pi, int baridx, int enabled,
1759     uint64_t address)
1760 {
1761 	struct passthru_softc *sc;
1762 	struct passthru_bar_handler *handler;
1763 	uint64_t off;
1764 
1765 	sc = pi->pi_arg;
1766 
1767 	off = 0;
1768 
1769 	/* The queue is sorted by offset in ascending order. */
1770 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1771 		uint64_t handler_off = trunc_page(handler->off);
1772 		uint64_t handler_end = round_page(handler->off + handler->size);
1773 
1774 		/*
1775 		 * When two handlers point to the same page, handler_off can be
1776 		 * lower than off. That's fine because we have nothing to do in
1777 		 * that case.
1778 		 */
1779 		if (handler_off > off) {
1780 			passthru_mmio_map(pi, baridx, enabled, address, off,
1781 			    handler_off - off);
1782 		}
1783 
1784 		off = handler_end;
1785 	}
1786 
1787 	passthru_mmio_map(pi, baridx, enabled, address, off,
1788 	    sc->psc_bar[baridx].size - off);
1789 }
1790 
1791 static void
passthru_addr_rom(struct pci_devinst * const pi,const int idx,const int enabled)1792 passthru_addr_rom(struct pci_devinst *const pi, const int idx,
1793     const int enabled)
1794 {
1795 	const uint64_t addr = pi->pi_bar[idx].addr;
1796 	const uint64_t size = pi->pi_bar[idx].size;
1797 
1798 	if (!enabled) {
1799 		if (vm_munmap_memseg(pi->pi_vmctx, addr, size) != 0) {
1800 			errx(4, "%s: munmap_memseg @ [%016lx - %016lx] failed",
1801 			    __func__, addr, addr + size);
1802 		}
1803 
1804 	} else {
1805 		if (vm_mmap_memseg(pi->pi_vmctx, addr, VM_PCIROM,
1806 			pi->pi_romoffset, size, PROT_READ | PROT_EXEC) != 0) {
1807 			errx(4, "%s: mmap_memseg @ [%016lx - %016lx]  failed",
1808 			    __func__, addr, addr + size);
1809 		}
1810 	}
1811 }
1812 
1813 static void
passthru_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1814 passthru_addr(struct pci_devinst *pi, int baridx, int enabled, uint64_t address)
1815 {
1816 	switch (pi->pi_bar[baridx].type) {
1817 	case PCIBAR_IO:
1818 		/* IO BARs are emulated */
1819 		break;
1820 	case PCIBAR_ROM:
1821 		passthru_addr_rom(pi, baridx, enabled);
1822 		break;
1823 	case PCIBAR_MEM32:
1824 	case PCIBAR_MEM64:
1825 		if (baridx == pci_msix_table_bar(pi))
1826 			passthru_msix_addr(pi, baridx, enabled, address);
1827 		else
1828 			passthru_mmio_addr(pi, baridx, enabled, address);
1829 		break;
1830 	default:
1831 		errx(4, "%s: invalid BAR type %d", __func__,
1832 		    pi->pi_bar[baridx].type);
1833 	}
1834 }
1835 
1836 static const struct pci_devemu passthru = {
1837 	.pe_emu		= "passthru",
1838 	.pe_init	= passthru_init,
1839 	.pe_legacy_config = passthru_legacy_config,
1840 	.pe_cfgwrite	= passthru_cfgwrite,
1841 	.pe_cfgread	= passthru_cfgread,
1842 	.pe_barwrite 	= passthru_write,
1843 	.pe_barread    	= passthru_read,
1844 	.pe_baraddr	= passthru_addr,
1845 };
1846 PCI_EMUL_SET(passthru);
1847