xref: /freebsd/usr.sbin/bhyve/pci_passthru.c (revision 0ffad4ce5655cbe412b79185d2b7924d0d72983e)
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;
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 
682 		/* Allocate the BAR in the guest I/O or MMIO space */
683 		pci_emul_alloc_bar(pi, i, bartype, size);
684 
685 		/*
686 		 * Use same lobits as physical BAR to preserve
687 		 * prefetch flag.
688 		 */
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 		pi->pi_bar[i].lobits = lobits;
697 
698 		/*
699 		 * 64-bit BAR takes up two slots so skip the next one.
700 		 */
701 		if (bartype == PCIBAR_MEM64) {
702 			i++;
703 			assert(i <= PCI_BARMAX);
704 			sc->psc_bar[i].type = PCIBAR_MEMHI64;
705 		}
706 	}
707 	return (0);
708 }
709 
710 static int
cfginit(struct pci_devinst * pi,int bus,int slot,int func)711 cfginit(struct pci_devinst *pi, int bus, int slot, int func)
712 {
713 	int error;
714 	struct passthru_softc *sc;
715 	uint16_t cmd;
716 	uint8_t intline, intpin;
717 
718 	error = 1;
719 	sc = pi->pi_arg;
720 
721 	bzero(&sc->psc_sel, sizeof(struct pcisel));
722 	sc->psc_sel.pc_bus = bus;
723 	sc->psc_sel.pc_dev = slot;
724 	sc->psc_sel.pc_func = func;
725 
726 	/*
727 	 * Copy physical PCI header to virtual config space.  COMMAND,
728 	 * INTLINE, and INTPIN shouldn't be aligned with their
729 	 * physical value and they are already set by pci_emul_init().
730 	 */
731 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
732 	intline = pci_get_cfgdata8(pi, PCIR_INTLINE);
733 	intpin = pci_get_cfgdata8(pi, PCIR_INTPIN);
734 	for (int i = 0; i <= PCIR_MAXLAT; i += 4) {
735 		pci_set_cfgdata32(pi, i,
736 		    passthru_read_config(&sc->psc_sel, i, 4));
737 	}
738 	pci_set_cfgdata16(pi, PCIR_COMMAND, cmd);
739 	pci_set_cfgdata8(pi, PCIR_INTLINE, intline);
740 	pci_set_cfgdata8(pi, PCIR_INTPIN, intpin);
741 
742 	if (cfginitcaps(sc) != 0) {
743 		warnx("failed to initialize PCI capabilities for %d/%d/%d",
744 		    bus, slot, func);
745 		goto done;
746 	}
747 
748 	if (cfginitbar(sc) != 0) {
749 		warnx("failed to initialize BARs for PCI %d/%d/%d",
750 		    bus, slot, func);
751 		goto done;
752 	}
753 
754 	if (pci_msix_table_bar(pi) >= 0) {
755 		error = init_msix_table(sc);
756 		if (error != 0) {
757 			warnx(
758 			    "failed to initialize MSI-X table for PCI %d/%d/%d: %d",
759 			    bus, slot, func, error);
760 			goto done;
761 		}
762 	}
763 
764 	error = 0;				/* success */
765 done:
766 	return (error);
767 }
768 
769 struct passthru_mmio_mapping *
passthru_get_mmio(struct passthru_softc * sc,int num)770 passthru_get_mmio(struct passthru_softc *sc, int num)
771 {
772 	assert(sc != NULL);
773 	assert(num < PASSTHRU_MMIO_MAX);
774 
775 	return (&sc->psc_mmio_map[num]);
776 }
777 
778 struct pcisel *
passthru_get_sel(struct passthru_softc * sc)779 passthru_get_sel(struct passthru_softc *sc)
780 {
781 	assert(sc != NULL);
782 
783 	return (&sc->psc_sel);
784 }
785 
786 int
set_pcir_handler(struct passthru_softc * sc,int reg,int len,cfgread_handler rhandler,cfgwrite_handler whandler)787 set_pcir_handler(struct passthru_softc *sc, int reg, int len,
788     cfgread_handler rhandler, cfgwrite_handler whandler)
789 {
790 	if (reg > PCI_REGMAX || reg + len > PCI_REGMAX + 1)
791 		return (-1);
792 
793 	for (int i = reg; i < reg + len; ++i) {
794 		assert(sc->psc_pcir_rhandler[i] == NULL || rhandler == NULL);
795 		assert(sc->psc_pcir_whandler[i] == NULL || whandler == NULL);
796 		sc->psc_pcir_rhandler[i] = rhandler;
797 		sc->psc_pcir_whandler[i] = whandler;
798 	}
799 
800 	return (0);
801 }
802 
803 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)804 passthru_set_bar_handler(struct passthru_softc *sc, int baridx, uint64_t off,
805     uint64_t size, passthru_read_handler rhandler,
806     passthru_write_handler whandler)
807 {
808 	struct passthru_bar_handler *handler_new;
809 	struct passthru_bar_handler *handler;
810 
811 	assert(sc->psc_bar[baridx].type == PCIBAR_IO ||
812 	    sc->psc_bar[baridx].type == PCIBAR_MEM32 ||
813 	    sc->psc_bar[baridx].type == PCIBAR_MEM64);
814 	assert(sc->psc_bar[baridx].size >= off + size);
815 	assert(off < off + size);
816 
817 	handler_new = malloc(sizeof(struct passthru_bar_handler));
818 	if (handler_new == NULL) {
819 		return (ENOMEM);
820 	}
821 
822 	handler_new->off = off;
823 	handler_new->size = size;
824 	handler_new->read = rhandler;
825 	handler_new->write = whandler;
826 
827 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
828 		if (handler->off < handler_new->off) {
829 			assert(handler->off + handler->size < handler_new->off);
830 			continue;
831 		}
832 		assert(handler->off > handler_new->off + handler_new->size);
833 		TAILQ_INSERT_BEFORE(handler, handler_new, chain);
834 		return (0);
835 	}
836 
837 	TAILQ_INSERT_TAIL(&sc->psc_bar_handler[baridx], handler_new, chain);
838 
839 	return (0);
840 }
841 
842 static int
passthru_legacy_config(nvlist_t * nvl,const char * opts)843 passthru_legacy_config(nvlist_t *nvl, const char *opts)
844 {
845 	const char *cp;
846 	char *tofree;
847 	char value[16];
848 	int bus, slot, func;
849 
850 	if (opts == NULL)
851 		return (0);
852 
853 	cp = strchr(opts, ',');
854 
855 	if (strncmp(opts, "ppt", strlen("ppt")) == 0) {
856 		tofree = strndup(opts, cp - opts);
857 		set_config_value_node(nvl, "pptdev", tofree);
858 		free(tofree);
859 	} else if (sscanf(opts, "pci0:%d:%d:%d", &bus, &slot, &func) == 3 ||
860 	    sscanf(opts, "pci%d:%d:%d", &bus, &slot, &func) == 3 ||
861 	    sscanf(opts, "%d/%d/%d", &bus, &slot, &func) == 3) {
862 		snprintf(value, sizeof(value), "%d", bus);
863 		set_config_value_node(nvl, "bus", value);
864 		snprintf(value, sizeof(value), "%d", slot);
865 		set_config_value_node(nvl, "slot", value);
866 		snprintf(value, sizeof(value), "%d", func);
867 		set_config_value_node(nvl, "func", value);
868 	} else {
869 		EPRINTLN("passthru: invalid options \"%s\"", opts);
870 		return (-1);
871 	}
872 
873 	if (cp == NULL) {
874 		return (0);
875 	}
876 
877 	return (pci_parse_legacy_config(nvl, cp + 1));
878 }
879 
880 static int
passthru_init_rom(struct passthru_softc * const sc,const char * const romfile)881 passthru_init_rom(struct passthru_softc *const sc, const char *const romfile)
882 {
883 	if (romfile == NULL) {
884 		return (0);
885 	}
886 
887 	const int fd = open(romfile, O_RDONLY);
888 	if (fd < 0) {
889 		warnx("%s: can't open romfile \"%s\"", __func__, romfile);
890 		return (-1);
891 	}
892 
893 	struct stat sbuf;
894 	if (fstat(fd, &sbuf) < 0) {
895 		warnx("%s: can't fstat romfile \"%s\"", __func__, romfile);
896 		close(fd);
897 		return (-1);
898 	}
899 	const uint64_t rom_size = sbuf.st_size;
900 
901 	void *const rom_data = mmap(NULL, rom_size, PROT_READ, MAP_SHARED, fd,
902 	    0);
903 	if (rom_data == MAP_FAILED) {
904 		warnx("%s: unable to mmap romfile \"%s\" (%d)", __func__,
905 		    romfile, errno);
906 		close(fd);
907 		return (-1);
908 	}
909 
910 	void *rom_addr;
911 	int error = pci_emul_alloc_rom(sc->psc_pi, rom_size, &rom_addr);
912 	if (error) {
913 		warnx("%s: failed to alloc rom segment", __func__);
914 		munmap(rom_data, rom_size);
915 		close(fd);
916 		return (error);
917 	}
918 	memcpy(rom_addr, rom_data, rom_size);
919 
920 	sc->psc_bar[PCI_ROM_IDX].type = PCIBAR_ROM;
921 	sc->psc_bar[PCI_ROM_IDX].addr = (uint64_t)rom_addr;
922 	sc->psc_bar[PCI_ROM_IDX].size = rom_size;
923 
924 	munmap(rom_data, rom_size);
925 	close(fd);
926 
927 	return (0);
928 }
929 
930 static bool
passthru_lookup_pptdev(const char * name,int * bus,int * slot,int * func)931 passthru_lookup_pptdev(const char *name, int *bus, int *slot, int *func)
932 {
933 	struct pci_conf_io pc;
934 	struct pci_conf conf[1];
935 	struct pci_match_conf patterns[1];
936 	char *cp;
937 
938 	bzero(&pc, sizeof(struct pci_conf_io));
939 	pc.match_buf_len = sizeof(conf);
940 	pc.matches = conf;
941 
942 	bzero(&patterns, sizeof(patterns));
943 
944 	/*
945 	 * The pattern structure requires the unit to be split out from
946 	 * the driver name.  Walk backwards from the end of the name to
947 	 * find the start of the unit.
948 	 */
949 	cp = strchr(name, '\0');
950 	assert(cp != NULL);
951 	while (cp != name && isdigit(cp[-1]))
952 		cp--;
953 	if (cp == name || !isdigit(*cp)) {
954 		EPRINTLN("Invalid passthru device name %s", name);
955 		return (false);
956 	}
957 	if ((size_t)(cp - name) + 1 > sizeof(patterns[0].pd_name)) {
958 		EPRINTLN("Passthru device name %s is too long", name);
959 		return (false);
960 	}
961 	memcpy(patterns[0].pd_name, name, cp - name);
962 	patterns[0].pd_unit = strtol(cp, &cp, 10);
963 	if (*cp != '\0') {
964 		EPRINTLN("Invalid passthru device name %s", name);
965 		return (false);
966 	}
967 	patterns[0].flags = PCI_GETCONF_MATCH_NAME | PCI_GETCONF_MATCH_UNIT;
968 	pc.num_patterns = 1;
969 	pc.pat_buf_len = sizeof(patterns);
970 	pc.patterns = patterns;
971 
972 	if (ioctl(pcifd, PCIOCGETCONF, &pc) == -1) {
973 		EPRINTLN("ioctl(PCIOCGETCONF): %s", strerror(errno));
974 		return (false);
975 	}
976 	if (pc.status != PCI_GETCONF_LAST_DEVICE &&
977 	    pc.status != PCI_GETCONF_MORE_DEVS) {
978 		EPRINTLN("error returned from PCIOCGETCONF ioctl");
979 		return (false);
980 	}
981 	if (pc.num_matches == 0) {
982 		EPRINTLN("Passthru device %s not found", name);
983 		return (false);
984 	}
985 
986 	if (conf[0].pc_sel.pc_domain != 0) {
987 		EPRINTLN("Passthru device %s on unsupported domain", name);
988 		return (false);
989 	}
990 	*bus = conf[0].pc_sel.pc_bus;
991 	*slot = conf[0].pc_sel.pc_dev;
992 	*func = conf[0].pc_sel.pc_func;
993 	return (true);
994 }
995 
996 static int
passthru_init(struct pci_devinst * pi,nvlist_t * nvl)997 passthru_init(struct pci_devinst *pi, nvlist_t *nvl)
998 {
999 	int bus, slot, func, error, memflags;
1000 	struct passthru_softc *sc;
1001 	struct passthru_dev **devpp;
1002 	struct passthru_dev *devp, *dev = NULL;
1003 	const char *value;
1004 
1005 	sc = NULL;
1006 	error = 1;
1007 
1008 	memflags = vm_get_memflags(pi->pi_vmctx);
1009 	if (!(memflags & VM_MEM_F_WIRED)) {
1010 		warnx("passthru requires guest memory to be wired");
1011 		return (error);
1012 	}
1013 
1014 	if (pcifd < 0 && pcifd_init()) {
1015 		return (error);
1016 	}
1017 
1018 #define GET_INT_CONFIG(var, name) do {					\
1019 	value = get_config_value_node(nvl, name);			\
1020 	if (value == NULL) {						\
1021 		EPRINTLN("passthru: missing required %s setting", name); \
1022 		return (error);						\
1023 	}								\
1024 	var = atoi(value);						\
1025 } while (0)
1026 
1027 	value = get_config_value_node(nvl, "pptdev");
1028 	if (value != NULL) {
1029 		if (!passthru_lookup_pptdev(value, &bus, &slot, &func))
1030 			return (error);
1031 	} else {
1032 		GET_INT_CONFIG(bus, "bus");
1033 		GET_INT_CONFIG(slot, "slot");
1034 		GET_INT_CONFIG(func, "func");
1035 	}
1036 
1037 	if (vm_assign_pptdev(pi->pi_vmctx, bus, slot, func) != 0) {
1038 		if (errno == ENOENT) {
1039 			EPRINTLN(
1040 		    "PCI device at %d/%d/%d is not using the ppt driver",
1041 			    bus, slot, func);
1042 		} else {
1043 			EPRINTLN("vm_assign_pptdev: %s", strerror(errno));
1044 		}
1045 		goto done;
1046 	}
1047 
1048 	sc = calloc(1, sizeof(struct passthru_softc));
1049 	if (sc == NULL)
1050 		goto done;
1051 	pthread_mutex_init(&sc->psc_io_mtx, NULL);
1052 
1053 	pi->pi_arg = sc;
1054 	sc->psc_pi = pi;
1055 
1056 	for (uint8_t i = 0; i < PCI_BARMAX_WITH_ROM + 1; ++i)
1057 		TAILQ_INIT(&sc->psc_bar_handler[i]);
1058 
1059 	/* initialize config space */
1060 	if ((error = cfginit(pi, bus, slot, func)) != 0)
1061 		goto done;
1062 
1063 	/* initialize ROM */
1064 	if ((error = passthru_init_rom(sc,
1065             get_config_value_node(nvl, "rom"))) != 0)
1066 		goto done;
1067 
1068 	/* Emulate most PCI header register. */
1069 	if ((error = set_pcir_handler(sc, 0, PCIR_MAXLAT + 1,
1070 	    passthru_cfgread_emulate, passthru_cfgwrite_emulate)) != 0)
1071 		goto done;
1072 
1073 	/* Allow access to the physical status register. */
1074 	if ((error = set_pcir_handler(sc, PCIR_COMMAND, 0x04, NULL, NULL)) != 0)
1075 		goto done;
1076 
1077 	SET_FOREACH(devpp, passthru_dev_set) {
1078 		devp = *devpp;
1079 		assert(devp->probe != NULL);
1080 		if (devp->probe(pi) == 0) {
1081 			dev = devp;
1082 			break;
1083 		}
1084 	}
1085 
1086 	if (dev != NULL) {
1087 		error = dev->init(pi, nvl);
1088 		if (error != 0)
1089 			goto done;
1090 	}
1091 
1092 	error = 0;		/* success */
1093 done:
1094 	if (error) {
1095 		if (dev != NULL)
1096 			dev->deinit(pi);
1097 		if (sc != NULL)
1098 			pthread_mutex_destroy(&sc->psc_io_mtx);
1099 		free(sc);
1100 		vm_unassign_pptdev(pi->pi_vmctx, bus, slot, func);
1101 	}
1102 	return (error);
1103 }
1104 
1105 static int
msicap_access(struct passthru_softc * sc,int coff)1106 msicap_access(struct passthru_softc *sc, int coff)
1107 {
1108 	int caplen;
1109 
1110 	if (sc->psc_msi.capoff == 0)
1111 		return (0);
1112 
1113 	caplen = msi_caplen(sc->psc_msi.msgctrl);
1114 
1115 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
1116 		return (1);
1117 	else
1118 		return (0);
1119 }
1120 
1121 static int
msixcap_access(struct passthru_softc * sc,int coff)1122 msixcap_access(struct passthru_softc *sc, int coff)
1123 {
1124 	if (sc->psc_msix.capoff == 0)
1125 		return (0);
1126 
1127 	return (coff >= sc->psc_msix.capoff &&
1128 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
1129 }
1130 
1131 #define	PASSTHRU_DEVCTL_VIRT	(PCIEM_CTL_MAX_PAYLOAD | \
1132 				 PCIEM_CTL_MAX_READ_REQUEST)
1133 #define	PASSTHRU_DEVCTL_NO_WRITE	PCIEM_CTL_PHANTHOM_FUNCS
1134 #define	PASSTHRU_DEVCTL2_VIRT	(PCIEM_CTL2_COMP_TIMO_VAL | \
1135 				 PCIEM_CTL2_COMP_TIMO_DISABLE)
1136 #define	PASSTHRU_PMCSR_VIRT	(PCIM_PSTAT_DMASK | \
1137 				 PCIM_PSTAT_NOSOFTRESET)
1138 
1139 static uint32_t
passthru_cfg_field_mask(int coff,int bytes,int fieldoff,uint16_t mask)1140 passthru_cfg_field_mask(int coff, int bytes, int fieldoff, uint16_t mask)
1141 {
1142 	uint32_t access_mask;
1143 	int i, pos;
1144 
1145 	access_mask = 0;
1146 	for (i = 0; i < bytes; i++) {
1147 		pos = coff + i;
1148 		if (pos >= fieldoff && pos < fieldoff + 2)
1149 			access_mask |= ((mask >> ((pos - fieldoff) * NBBY)) &
1150 			    0xff) << (i * NBBY);
1151 	}
1152 	return (access_mask);
1153 }
1154 
1155 static uint32_t
passthru_cfg_field_value(int coff,int bytes,int fieldoff,uint16_t value)1156 passthru_cfg_field_value(int coff, int bytes, int fieldoff, uint16_t value)
1157 {
1158 	uint32_t access_value;
1159 	int i, pos;
1160 
1161 	access_value = 0;
1162 	for (i = 0; i < bytes; i++) {
1163 		pos = coff + i;
1164 		if (pos >= fieldoff && pos < fieldoff + 2)
1165 			access_value |= ((value >> ((pos - fieldoff) * NBBY)) &
1166 			    0xff) << (i * NBBY);
1167 	}
1168 	return (access_value);
1169 }
1170 
1171 /*
1172  * Replace selected bits of a 16-bit field within an arbitrarily aligned
1173  * configuration-space access.  Preserve every byte and field bit outside
1174  * the supplied mask.
1175  */
1176 static uint32_t
passthru_cfg_overlay_field(int coff,int bytes,uint32_t access,int fieldoff,uint16_t field,uint16_t field_mask)1177 passthru_cfg_overlay_field(int coff, int bytes, uint32_t access, int fieldoff,
1178     uint16_t field, uint16_t field_mask)
1179 {
1180 	uint32_t access_mask;
1181 
1182 	access_mask = passthru_cfg_field_mask(coff, bytes, fieldoff,
1183 	    field_mask);
1184 	return ((access & ~access_mask) |
1185 	    (passthru_cfg_field_value(coff, bytes, fieldoff, field) &
1186 	    access_mask));
1187 }
1188 
1189 static void
passthru_cfg_update_field(int coff,int bytes,uint32_t value,int fieldoff,uint16_t mask,uint16_t * field)1190 passthru_cfg_update_field(int coff, int bytes, uint32_t value, int fieldoff,
1191     uint16_t mask, uint16_t *field)
1192 {
1193 	uint16_t byte_mask, byte_value;
1194 	int i, pos, shift;
1195 
1196 	for (i = 0; i < bytes; i++) {
1197 		pos = coff + i;
1198 		if (pos < fieldoff || pos >= fieldoff + 2)
1199 			continue;
1200 		shift = (pos - fieldoff) * NBBY;
1201 		byte_mask = mask & (0xff << shift);
1202 		byte_value = ((value >> (i * NBBY)) & 0xff) << shift;
1203 		*field = (*field & ~byte_mask) | (byte_value & byte_mask);
1204 	}
1205 }
1206 
1207 static void
passthru_reset_interrupt_state(struct passthru_softc * sc)1208 passthru_reset_interrupt_state(struct passthru_softc *sc)
1209 {
1210 	struct pci_devinst *pi;
1211 	uint16_t msgctrl;
1212 	int caplen, i;
1213 
1214 	pi = sc->psc_pi;
1215 	if (sc->psc_msi.capoff != 0) {
1216 		caplen = msi_caplen(sc->psc_msi.msgctrl);
1217 		msgctrl = pci_get_cfgdata16(pi, sc->psc_msi.capoff + 2);
1218 		msgctrl &= ~(PCIM_MSICTRL_MME_MASK | PCIM_MSICTRL_MSI_ENABLE);
1219 		memset(pi->pi_cfgdata + sc->psc_msi.capoff + 4, 0, caplen - 4);
1220 		pci_set_cfgdata16(pi, sc->psc_msi.capoff + 2, msgctrl);
1221 		pi->pi_msi.enabled = 0;
1222 		pi->pi_msi.addr = 0;
1223 		pi->pi_msi.msg_data = 0;
1224 		pi->pi_msi.maxmsgnum = 0;
1225 	}
1226 	if (sc->psc_msix.capoff != 0) {
1227 		msgctrl = pci_get_cfgdata16(pi, sc->psc_msix.capoff + 2);
1228 		msgctrl &= ~(PCIM_MSIXCTRL_MSIX_ENABLE |
1229 		    PCIM_MSIXCTRL_FUNCTION_MASK);
1230 		pci_set_cfgdata16(pi, sc->psc_msix.capoff + 2, msgctrl);
1231 		pi->pi_msix.enabled = 0;
1232 		pi->pi_msix.function_mask = 0;
1233 		bzero(pi->pi_msix.table, pi->pi_msix.table_count *
1234 		    sizeof(pi->pi_msix.table[0]));
1235 		for (i = 0; i < pi->pi_msix.table_count; i++)
1236 			pi->pi_msix.table[i].vector_control =
1237 			    PCIM_MSIX_VCTRL_MASK;
1238 	}
1239 }
1240 
1241 static void
passthru_reset_capability_state(struct passthru_softc * sc)1242 passthru_reset_capability_state(struct passthru_softc *sc)
1243 {
1244 	uint16_t devctl, guest_mps;
1245 	int offset;
1246 
1247 	/* MPS is explicitly preserved across FLR by the PCIe specification. */
1248 	guest_mps = sc->psc_pcie.devctl & PCIEM_CTL_MAX_PAYLOAD;
1249 	offset = sc->psc_pcie.capoff + PCIER_DEVICE_CTL;
1250 	devctl = passthru_read_config(&sc->psc_sel, offset, 2);
1251 	if (devctl != 0xffff) {
1252 		devctl &= ~PCIEM_CTL_MAX_READ_REQUEST;
1253 		devctl |= sc->psc_pcie.reset_devctl &
1254 		    PCIEM_CTL_MAX_READ_REQUEST;
1255 		passthru_write_config(&sc->psc_sel, offset, 2, devctl);
1256 	}
1257 	sc->psc_pcie.devctl =
1258 	    (sc->psc_pcie.reset_devctl & ~PCIEM_CTL_MAX_PAYLOAD) | guest_mps;
1259 	if (sc->psc_pcie.has_devctl2)
1260 		sc->psc_pcie.devctl2 = sc->psc_pcie.reset_devctl2;
1261 	if (sc->psc_pm.capoff != 0)
1262 		sc->psc_pm.pmcsr = sc->psc_pm.reset_pmcsr;
1263 }
1264 
1265 static int
passthru_reset(struct passthru_softc * sc)1266 passthru_reset(struct passthru_softc *sc)
1267 {
1268 	struct pci_devinst *pi;
1269 	uint16_t command;
1270 	int error;
1271 
1272 	pi = sc->psc_pi;
1273 	command = pci_get_cfgdata16(pi, PCIR_COMMAND);
1274 
1275 	/*
1276 	 * Stop trapped BAR accesses and drain any handler already touching the
1277 	 * device.  pci_cfgrw() holds pi_cfg_lock for this entire transaction,
1278 	 * so another vCPU cannot re-enable or move a BAR around the reset.
1279 	 */
1280 	pthread_mutex_lock(&sc->psc_io_mtx);
1281 	sc->psc_resetting = true;
1282 	pthread_mutex_unlock(&sc->psc_io_mtx);
1283 
1284 	if (pi->pi_lintr.pin != 0)
1285 		pci_lintr_deassert(pi);
1286 	pci_set_cfgdata16(pi, PCIR_COMMAND, 0);
1287 	pci_emul_cmd_changed(pi, command);
1288 
1289 	if (vm_reset_pptdev(pi->pi_vmctx, sc->psc_sel.pc_bus,
1290 	    sc->psc_sel.pc_dev, sc->psc_sel.pc_func) == 0)
1291 		error = 0;
1292 	else
1293 		error = errno;
1294 
1295 	/*
1296 	 * EIO means PPT crossed the destructive preparation boundary.  The FLR
1297 	 * either ran or failed after host interrupt resources were torn down, so
1298 	 * the corresponding guest state must be discarded in either case.
1299 	 */
1300 	if (error != 0 && error != EIO) {
1301 		pci_set_cfgdata16(pi, PCIR_COMMAND, command);
1302 		pci_emul_cmd_changed(pi, 0);
1303 	} else {
1304 		passthru_reset_interrupt_state(sc);
1305 		passthru_reset_capability_state(sc);
1306 	}
1307 	pthread_mutex_lock(&sc->psc_io_mtx);
1308 	sc->psc_resetting = false;
1309 	pthread_mutex_unlock(&sc->psc_io_mtx);
1310 	return (error);
1311 }
1312 
1313 static int
passthru_cfgread_default(struct passthru_softc * sc,struct pci_devinst * pi __unused,int coff,int bytes,uint32_t * rv)1314 passthru_cfgread_default(struct passthru_softc *sc,
1315     struct pci_devinst *pi __unused, int coff, int bytes, uint32_t *rv)
1316 {
1317 	/*
1318 	 * MSI capability is emulated.
1319 	 */
1320 	if (msicap_access(sc, coff) || msixcap_access(sc, coff))
1321 		return (-1);
1322 
1323 	/*
1324 	 * Emulate the command register.  If a single read reads both the
1325 	 * command and status registers, read the status register from the
1326 	 * device's config space.
1327 	 */
1328 	if (coff == PCIR_COMMAND) {
1329 		uint32_t st;
1330 
1331 		if (bytes <= 2)
1332 			return (-1);
1333 		st = passthru_read_config(&sc->psc_sel, PCIR_STATUS, 2);
1334 		*rv = (st << 16) | pci_get_cfgdata16(pi, PCIR_COMMAND);
1335 		return (0);
1336 	}
1337 
1338 	/* Everything else just read from the device's config space. */
1339 	*rv = passthru_read_config(&sc->psc_sel, coff, bytes);
1340 	if (sc->psc_pm.capoff != 0) {
1341 		int pmcsr;
1342 
1343 		pmcsr = sc->psc_pm.capoff + PCIR_POWER_STATUS;
1344 		*rv = passthru_cfg_overlay_field(coff, bytes, *rv, pmcsr,
1345 		    sc->psc_pm.pmcsr, PASSTHRU_PMCSR_VIRT);
1346 	}
1347 	if (sc->psc_pcie.capoff != 0) {
1348 		int devctl;
1349 
1350 		devctl = sc->psc_pcie.capoff + PCIER_DEVICE_CTL;
1351 		*rv = passthru_cfg_overlay_field(coff, bytes, *rv, devctl,
1352 		    sc->psc_pcie.devctl, PASSTHRU_DEVCTL_VIRT);
1353 		if (sc->psc_pcie.has_devctl2) {
1354 			devctl = sc->psc_pcie.capoff + PCIER_DEVICE_CTL2;
1355 			*rv = passthru_cfg_overlay_field(coff, bytes, *rv, devctl,
1356 			    sc->psc_pcie.devctl2, PASSTHRU_DEVCTL2_VIRT);
1357 		}
1358 	}
1359 
1360 	return (0);
1361 }
1362 
1363 int
passthru_cfgread_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t * rv __unused)1364 passthru_cfgread_emulate(struct passthru_softc *sc __unused,
1365     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1366     uint32_t *rv __unused)
1367 {
1368 	return (-1);
1369 }
1370 
1371 static int
passthru_cfgread(struct pci_devinst * pi,int coff,int bytes,uint32_t * rv)1372 passthru_cfgread(struct pci_devinst *pi, int coff, int bytes, uint32_t *rv)
1373 {
1374 	struct passthru_softc *sc;
1375 
1376 	sc = pi->pi_arg;
1377 
1378 	if (sc->psc_pcir_rhandler[coff] != NULL)
1379 		return (sc->psc_pcir_rhandler[coff](sc, pi, coff, bytes, rv));
1380 
1381 	return (passthru_cfgread_default(sc, pi, coff, bytes, rv));
1382 }
1383 
1384 static int
passthru_cfgwrite_default(struct passthru_softc * sc,struct pci_devinst * pi,int coff,int bytes,uint32_t val)1385 passthru_cfgwrite_default(struct passthru_softc *sc, struct pci_devinst *pi,
1386     int coff, int bytes, uint32_t val)
1387 {
1388 	uint32_t flr_mask, transport_mask;
1389 	uint16_t physical_devctl, physical_pmcsr;
1390 	int devctl, devctl2, host_mps, guest_mrrs, pmcsr;
1391 	int error, msix_table_entries, i;
1392 	uint16_t cmd_old;
1393 
1394 	/*
1395 	 * MSI capability is emulated
1396 	 */
1397 	if (msicap_access(sc, coff)) {
1398 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
1399 		    PCIY_MSI);
1400 		error = vm_setup_pptdev_msi(pi->pi_vmctx, sc->psc_sel.pc_bus,
1401 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
1402 			pi->pi_msi.addr, pi->pi_msi.msg_data,
1403 			pi->pi_msi.maxmsgnum);
1404 		if (error != 0)
1405 			err(1, "vm_setup_pptdev_msi");
1406 		return (0);
1407 	}
1408 
1409 	if (msixcap_access(sc, coff)) {
1410 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
1411 		    PCIY_MSIX);
1412 		if (pi->pi_msix.enabled) {
1413 			msix_table_entries = pi->pi_msix.table_count;
1414 			for (i = 0; i < msix_table_entries; i++) {
1415 				error = vm_setup_pptdev_msix(pi->pi_vmctx,
1416 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1417 				    sc->psc_sel.pc_func, i,
1418 				    pi->pi_msix.table[i].addr,
1419 				    pi->pi_msix.table[i].msg_data,
1420 				    pi->pi_msix.table[i].vector_control);
1421 
1422 				if (error)
1423 					err(1, "vm_setup_pptdev_msix");
1424 			}
1425 		} else {
1426 			error = vm_disable_pptdev_msix(pi->pi_vmctx,
1427 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1428 			    sc->psc_sel.pc_func);
1429 			if (error)
1430 				err(1, "vm_disable_pptdev_msix");
1431 		}
1432 		return (0);
1433 	}
1434 
1435 	/*
1436 	 * A physical D3hot-to-D0 transition may reset the function and clear
1437 	 * Command behind bhyve's emulated copy.  Keep the physical D-state
1438 	 * host-owned, emulate the guest D-state, and advertise No_Soft_Reset so
1439 	 * the guest does not rely on this cycle as a function reset.
1440 	 */
1441 	pmcsr = sc->psc_pm.capoff + PCIR_POWER_STATUS;
1442 	if (sc->psc_pm.capoff != 0 && coff < pmcsr + 2 &&
1443 	    coff + bytes > pmcsr) {
1444 		physical_pmcsr = passthru_read_config(&sc->psc_sel, pmcsr, 2);
1445 		if (physical_pmcsr == 0xffff) {
1446 			warnx("configuration space unavailable for passthru "
1447 			    "device %d/%d/%d", sc->psc_sel.pc_bus,
1448 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
1449 			return (0);
1450 		}
1451 		passthru_cfg_update_field(coff, bytes, val, pmcsr,
1452 		    PCIM_PSTAT_DMASK, &sc->psc_pm.pmcsr);
1453 		val = passthru_cfg_overlay_field(coff, bytes, val, pmcsr,
1454 		    physical_pmcsr, PASSTHRU_PMCSR_VIRT);
1455 		passthru_write_config(&sc->psc_sel, coff, bytes, val);
1456 		return (0);
1457 	}
1458 
1459 	/*
1460 	 * A direct FLR would clear physical Command while the guest sees its
1461 	 * emulated copy remain enabled.  Route FLR through ppt so it restores
1462 	 * host-owned state.  MPS is shared-path policy, and Phantom Functions
1463 	 * Enable changes IOMMU-visible requester IDs, so keep both host-owned.
1464 	 * Floor physical MRRS at physical MPS because the guest lacks the
1465 	 * hierarchy view.  ppt also applies FLR quirks for VFs such as 82599.
1466 	 */
1467 	devctl = sc->psc_pcie.capoff + PCIER_DEVICE_CTL;
1468 	if (sc->psc_pcie.capoff != 0 && coff < devctl + 2 &&
1469 	    coff + bytes > devctl) {
1470 		transport_mask = passthru_cfg_field_mask(coff, bytes, devctl,
1471 		    PASSTHRU_DEVCTL_VIRT);
1472 		physical_devctl = passthru_read_config(&sc->psc_sel, devctl, 2);
1473 		if (physical_devctl == 0xffff) {
1474 			warnx("configuration space unavailable for passthru "
1475 			    "device %d/%d/%d", sc->psc_sel.pc_bus,
1476 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
1477 			return (0);
1478 		}
1479 		passthru_cfg_update_field(coff, bytes, val, devctl,
1480 		    PASSTHRU_DEVCTL_VIRT, &sc->psc_pcie.devctl);
1481 		if ((transport_mask & passthru_cfg_field_mask(coff, bytes,
1482 		    devctl, PCIEM_CTL_MAX_READ_REQUEST)) != 0) {
1483 			host_mps = (physical_devctl & PCIEM_CTL_MAX_PAYLOAD) >> 5;
1484 			guest_mrrs = (sc->psc_pcie.devctl &
1485 			    PCIEM_CTL_MAX_READ_REQUEST) >> 12;
1486 			if (guest_mrrs <= 5) {
1487 				if (guest_mrrs < host_mps)
1488 					guest_mrrs = host_mps;
1489 				physical_devctl &= ~PCIEM_CTL_MAX_READ_REQUEST;
1490 				physical_devctl |= guest_mrrs << 12;
1491 			}
1492 		}
1493 		val = passthru_cfg_overlay_field(coff, bytes, val, devctl,
1494 		    physical_devctl,
1495 		    PASSTHRU_DEVCTL_VIRT | PASSTHRU_DEVCTL_NO_WRITE);
1496 
1497 		flr_mask = passthru_cfg_field_mask(coff, bytes, devctl,
1498 		    PCIEM_CTL_INITIATE_FLR);
1499 		passthru_write_config(&sc->psc_sel, coff, bytes,
1500 		    val & ~flr_mask);
1501 		if ((val & flr_mask) != 0) {
1502 			error = passthru_reset(sc);
1503 			if (error != 0)
1504 				warnx("failed to reset passthru device "
1505 				    "%d/%d/%d: %s", sc->psc_sel.pc_bus,
1506 				    sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
1507 				    strerror(error));
1508 		}
1509 		return (0);
1510 	}
1511 
1512 	/*
1513 	 * Completion Timeout controls how long the host must protect against an
1514 	 * in-flight completion after a forced FLR.  Keep the physical policy
1515 	 * host-owned so a guest cannot extend the reset ioctl for tens of
1516 	 * seconds, but retain a guest-visible value for normal PCI semantics.
1517 	 */
1518 	devctl2 = sc->psc_pcie.capoff + PCIER_DEVICE_CTL2;
1519 	if (sc->psc_pcie.has_devctl2 && coff < devctl2 + 2 &&
1520 	    coff + bytes > devctl2) {
1521 		physical_devctl = passthru_read_config(&sc->psc_sel, devctl2, 2);
1522 		if (physical_devctl == 0xffff) {
1523 			warnx("configuration space unavailable for passthru "
1524 			    "device %d/%d/%d", sc->psc_sel.pc_bus,
1525 			    sc->psc_sel.pc_dev, sc->psc_sel.pc_func);
1526 			return (0);
1527 		}
1528 		passthru_cfg_update_field(coff, bytes, val, devctl2,
1529 		    PASSTHRU_DEVCTL2_VIRT, &sc->psc_pcie.devctl2);
1530 		val = passthru_cfg_overlay_field(coff, bytes, val, devctl2,
1531 		    physical_devctl, PASSTHRU_DEVCTL2_VIRT);
1532 		passthru_write_config(&sc->psc_sel, coff, bytes, val);
1533 		return (0);
1534 	}
1535 
1536 	/*
1537 	 * The command register is emulated, but the status register
1538 	 * is passed through.
1539 	 */
1540 	if (coff == PCIR_COMMAND) {
1541 		if (bytes <= 2)
1542 			return (-1);
1543 
1544 		/* Update the physical status register. */
1545 		passthru_write_config(&sc->psc_sel, PCIR_STATUS, val >> 16, 2);
1546 
1547 		/* Update the virtual command register. */
1548 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
1549 		pci_set_cfgdata16(pi, PCIR_COMMAND, val & 0xffff);
1550 		pci_emul_cmd_changed(pi, cmd_old);
1551 		return (0);
1552 	}
1553 
1554 	passthru_write_config(&sc->psc_sel, coff, bytes, val);
1555 
1556 	return (0);
1557 }
1558 
1559 int
passthru_cfgwrite_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t val __unused)1560 passthru_cfgwrite_emulate(struct passthru_softc *sc __unused,
1561     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1562     uint32_t val __unused)
1563 {
1564 	return (-1);
1565 }
1566 
1567 static int
passthru_cfgwrite(struct pci_devinst * pi,int coff,int bytes,uint32_t val)1568 passthru_cfgwrite(struct pci_devinst *pi, int coff, int bytes, uint32_t val)
1569 {
1570 	struct passthru_softc *sc;
1571 
1572 	sc = pi->pi_arg;
1573 
1574 	if (sc->psc_pcir_whandler[coff] != NULL)
1575 		return (sc->psc_pcir_whandler[coff](sc, pi, coff, bytes, val));
1576 
1577 	return (passthru_cfgwrite_default(sc, pi, coff, bytes, val));
1578 }
1579 
1580 static void
passthru_write_locked(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)1581 passthru_write_locked(struct pci_devinst *pi, int baridx, uint64_t offset,
1582     int size, uint64_t value)
1583 {
1584 	struct passthru_softc *sc;
1585 	struct passthru_bar_handler *handler;
1586 	struct pci_bar_ioreq pio;
1587 
1588 	sc = pi->pi_arg;
1589 
1590 	if (baridx == pci_msix_table_bar(pi)) {
1591 		msix_table_write(sc, offset, size, value);
1592 	} else {
1593 		assert(size == 1 || size == 2 || size == 4);
1594 
1595 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1596 			if (offset >= handler->off + handler->size) {
1597 				continue;
1598 			} else if (offset < handler->off) {
1599 				assert(offset + size < handler->off);
1600 				/*
1601 				 * The list is sorted in ascending order, so all
1602 				 * remaining handlers will have an even larger
1603 				 * offset.
1604 				 */
1605 				break;
1606 			}
1607 
1608 			assert(offset + size <= handler->off + handler->size);
1609 
1610 			handler->write(pi, baridx,
1611 			    offset - handler->off, size, value);
1612 			return;
1613 		}
1614 
1615 		bzero(&pio, sizeof(pio));
1616 		pio.pbi_sel = sc->psc_sel;
1617 		pio.pbi_op = PCIBARIO_WRITE;
1618 		pio.pbi_bar = baridx;
1619 		pio.pbi_offset = (uint32_t)offset;
1620 		pio.pbi_width = size;
1621 		pio.pbi_value = (uint32_t)value;
1622 
1623 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1624 	}
1625 }
1626 
1627 static uint64_t
passthru_read_locked(struct pci_devinst * pi,int baridx,uint64_t offset,int size)1628 passthru_read_locked(struct pci_devinst *pi, int baridx, uint64_t offset,
1629     int size)
1630 {
1631 	struct passthru_softc *sc;
1632 	struct passthru_bar_handler *handler;
1633 	struct pci_bar_ioreq pio;
1634 	uint64_t val;
1635 
1636 	sc = pi->pi_arg;
1637 
1638 	if (baridx == pci_msix_table_bar(pi)) {
1639 		val = msix_table_read(sc, offset, size);
1640 	} else {
1641 		assert(size == 1 || size == 2 || size == 4);
1642 
1643 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1644 			if (offset >= handler->off + handler->size) {
1645 				continue;
1646 			} else if (offset < handler->off) {
1647 				assert(offset + size < handler->off);
1648 				/*
1649 				 * The list is sorted in ascending order, so all
1650 				 * remaining handlers will have an even larger
1651 				 * offset.
1652 				 */
1653 				break;
1654 			}
1655 
1656 			assert(offset + size <= handler->off + handler->size);
1657 
1658 			return (handler->read(pi, baridx,
1659 			    offset - handler->off, size));
1660 		}
1661 
1662 		bzero(&pio, sizeof(pio));
1663 		pio.pbi_sel = sc->psc_sel;
1664 		pio.pbi_op = PCIBARIO_READ;
1665 		pio.pbi_bar = baridx;
1666 		pio.pbi_offset = (uint32_t)offset;
1667 		pio.pbi_width = size;
1668 
1669 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1670 
1671 		val = pio.pbi_value;
1672 	}
1673 
1674 	return (val);
1675 }
1676 
1677 static void
passthru_write(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)1678 passthru_write(struct pci_devinst *pi, int baridx, uint64_t offset, int size,
1679     uint64_t value)
1680 {
1681 	struct passthru_softc *sc;
1682 
1683 	sc = pi->pi_arg;
1684 	pthread_mutex_lock(&sc->psc_io_mtx);
1685 	if (!sc->psc_resetting)
1686 		passthru_write_locked(pi, baridx, offset, size, value);
1687 	pthread_mutex_unlock(&sc->psc_io_mtx);
1688 }
1689 
1690 static uint64_t
passthru_read(struct pci_devinst * pi,int baridx,uint64_t offset,int size)1691 passthru_read(struct pci_devinst *pi, int baridx, uint64_t offset, int size)
1692 {
1693 	struct passthru_softc *sc;
1694 	uint64_t value;
1695 
1696 	sc = pi->pi_arg;
1697 	pthread_mutex_lock(&sc->psc_io_mtx);
1698 	if (sc->psc_resetting)
1699 		value = UINT64_MAX;
1700 	else
1701 		value = passthru_read_locked(pi, baridx, offset, size);
1702 	pthread_mutex_unlock(&sc->psc_io_mtx);
1703 	return (value);
1704 }
1705 
1706 static int
passthru_mmio_map(struct pci_devinst * pi,int baridx,int enabled,uint64_t address,uint64_t off,uint64_t size)1707 passthru_mmio_map(struct pci_devinst *pi, int baridx, int enabled,
1708     uint64_t address, uint64_t off, uint64_t size)
1709 {
1710 	struct passthru_softc *sc;
1711 
1712 	sc = pi->pi_arg;
1713 	if (!enabled) {
1714 		if (vm_unmap_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1715 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1716 		    size) != 0) {
1717 			EPRINTLN("pci_passthru: unmap_pptdev_mmio failed: %s",
1718 			    strerror(errno));
1719 			return (-1);
1720 		}
1721 	} else {
1722 		if (vm_map_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1723 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1724 		    size, sc->psc_bar[baridx].addr + off) != 0) {
1725 			EPRINTLN("pci_passthru: map_pptdev_mmio failed: %s",
1726 			    strerror(errno));
1727 			return (-1);
1728 		}
1729 	}
1730 
1731 	return (0);
1732 }
1733 
1734 static void
passthru_msix_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1735 passthru_msix_addr(struct pci_devinst *pi, int baridx, int enabled,
1736     uint64_t address)
1737 {
1738 	size_t remaining;
1739 	uint32_t table_size, table_offset;
1740 
1741 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
1742 	if (table_offset > 0) {
1743 		(void)passthru_mmio_map(pi, baridx, enabled, address, 0,
1744 		    table_offset);
1745 	}
1746 	table_size = pi->pi_msix.table_offset - table_offset;
1747 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
1748 	table_size = roundup2(table_size, 4096);
1749 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
1750 	if (remaining > 0) {
1751 		(void)passthru_mmio_map(pi, baridx, enabled, address,
1752 		    table_offset + table_size, remaining);
1753 	}
1754 }
1755 
1756 static void
passthru_mmio_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1757 passthru_mmio_addr(struct pci_devinst *pi, int baridx, int enabled,
1758     uint64_t address)
1759 {
1760 	struct passthru_softc *sc;
1761 	struct passthru_bar_handler *handler;
1762 	uint64_t off;
1763 
1764 	sc = pi->pi_arg;
1765 
1766 	off = 0;
1767 
1768 	/* The queue is sorted by offset in ascending order. */
1769 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1770 		uint64_t handler_off = trunc_page(handler->off);
1771 		uint64_t handler_end = round_page(handler->off + handler->size);
1772 
1773 		/*
1774 		 * When two handlers point to the same page, handler_off can be
1775 		 * lower than off. That's fine because we have nothing to do in
1776 		 * that case.
1777 		 */
1778 		if (handler_off > off) {
1779 			passthru_mmio_map(pi, baridx, enabled, address, off,
1780 			    handler_off - off);
1781 		}
1782 
1783 		off = handler_end;
1784 	}
1785 
1786 	passthru_mmio_map(pi, baridx, enabled, address, off,
1787 	    sc->psc_bar[baridx].size - off);
1788 }
1789 
1790 static void
passthru_addr_rom(struct pci_devinst * const pi,const int idx,const int enabled)1791 passthru_addr_rom(struct pci_devinst *const pi, const int idx,
1792     const int enabled)
1793 {
1794 	const uint64_t addr = pi->pi_bar[idx].addr;
1795 	const uint64_t size = pi->pi_bar[idx].size;
1796 
1797 	if (!enabled) {
1798 		if (vm_munmap_memseg(pi->pi_vmctx, addr, size) != 0) {
1799 			errx(4, "%s: munmap_memseg @ [%016lx - %016lx] failed",
1800 			    __func__, addr, addr + size);
1801 		}
1802 
1803 	} else {
1804 		if (vm_mmap_memseg(pi->pi_vmctx, addr, VM_PCIROM,
1805 			pi->pi_romoffset, size, PROT_READ | PROT_EXEC) != 0) {
1806 			errx(4, "%s: mmap_memseg @ [%016lx - %016lx]  failed",
1807 			    __func__, addr, addr + size);
1808 		}
1809 	}
1810 }
1811 
1812 static void
passthru_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1813 passthru_addr(struct pci_devinst *pi, int baridx, int enabled, uint64_t address)
1814 {
1815 	switch (pi->pi_bar[baridx].type) {
1816 	case PCIBAR_IO:
1817 		/* IO BARs are emulated */
1818 		break;
1819 	case PCIBAR_ROM:
1820 		passthru_addr_rom(pi, baridx, enabled);
1821 		break;
1822 	case PCIBAR_MEM32:
1823 	case PCIBAR_MEM64:
1824 		if (baridx == pci_msix_table_bar(pi))
1825 			passthru_msix_addr(pi, baridx, enabled, address);
1826 		else
1827 			passthru_mmio_addr(pi, baridx, enabled, address);
1828 		break;
1829 	default:
1830 		errx(4, "%s: invalid BAR type %d", __func__,
1831 		    pi->pi_bar[baridx].type);
1832 	}
1833 }
1834 
1835 static const struct pci_devemu passthru = {
1836 	.pe_emu		= "passthru",
1837 	.pe_init	= passthru_init,
1838 	.pe_legacy_config = passthru_legacy_config,
1839 	.pe_cfgwrite	= passthru_cfgwrite,
1840 	.pe_cfgread	= passthru_cfgread,
1841 	.pe_barwrite 	= passthru_write,
1842 	.pe_barread    	= passthru_read,
1843 	.pe_baraddr	= passthru_addr,
1844 };
1845 PCI_EMUL_SET(passthru);
1846