xref: /freebsd/usr.sbin/bhyve/pci_passthru.c (revision 6dda2653bd0ee297b114682972b11d6d3c74a6a6)
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 <sysexits.h>
59 #include <unistd.h>
60 
61 #include <machine/vmm.h>
62 
63 #include "debug.h"
64 #include "mem.h"
65 #include "pci_passthru.h"
66 
67 #ifndef _PATH_DEVPCI
68 #define	_PATH_DEVPCI	"/dev/pci"
69 #endif
70 
71 #define	LEGACY_SUPPORT	1
72 
73 #define MSIX_TABLE_COUNT(ctrl) (((ctrl) & PCIM_MSIXCTRL_TABLE_SIZE) + 1)
74 #define MSIX_CAPLEN 12
75 
76 #define PASSTHRU_MMIO_MAX 3
77 
78 static int pcifd = -1;
79 
80 SET_DECLARE(passthru_dev_set, struct passthru_dev);
81 
82 struct passthru_bar_handler {
83 	TAILQ_ENTRY(passthru_bar_handler) chain;
84 	uint64_t off;
85 	uint64_t size;
86 	passthru_read_handler read;
87 	passthru_write_handler write;
88 };
89 
90 struct passthru_softc {
91 	struct pci_devinst *psc_pi;
92 	/* ROM is handled like a BAR */
93 	struct pcibar psc_bar[PCI_BARMAX_WITH_ROM + 1];
94 	struct {
95 		int		capoff;
96 		int		msgctrl;
97 		int		emulated;
98 	} psc_msi;
99 	struct {
100 		int		capoff;
101 	} psc_msix;
102 	struct pcisel psc_sel;
103 
104 	struct passthru_mmio_mapping psc_mmio_map[PASSTHRU_MMIO_MAX];
105 	cfgread_handler psc_pcir_rhandler[PCI_REGMAX + 1];
106 	cfgwrite_handler psc_pcir_whandler[PCI_REGMAX + 1];
107 
108 	TAILQ_HEAD(,
109 	    passthru_bar_handler) psc_bar_handler[PCI_BARMAX_WITH_ROM + 1];
110 };
111 
112 static int
msi_caplen(int msgctrl)113 msi_caplen(int msgctrl)
114 {
115 	int len;
116 
117 	len = 10;		/* minimum length of msi capability */
118 
119 	if (msgctrl & PCIM_MSICTRL_64BIT)
120 		len += 4;
121 
122 #if 0
123 	/*
124 	 * Ignore the 'mask' and 'pending' bits in the MSI capability.
125 	 * We'll let the guest manipulate them directly.
126 	 */
127 	if (msgctrl & PCIM_MSICTRL_VECTOR)
128 		len += 10;
129 #endif
130 
131 	return (len);
132 }
133 
134 static int
pcifd_open(void)135 pcifd_open(void)
136 {
137 	int fd;
138 
139 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
140 	if (fd < 0) {
141 		warn("failed to open %s", _PATH_DEVPCI);
142 		return (-1);
143 	}
144 	return (fd);
145 }
146 
147 static int
pcifd_init(void)148 pcifd_init(void)
149 {
150 	pcifd = pcifd_open();
151 	if (pcifd < 0)
152 		return (1);
153 
154 #ifndef WITHOUT_CAPSICUM
155 	cap_rights_t pcifd_rights;
156 	cap_rights_init(&pcifd_rights, CAP_IOCTL, CAP_READ, CAP_WRITE);
157 	if (caph_rights_limit(pcifd, &pcifd_rights) == -1)
158 		errx(EX_OSERR, "Unable to apply rights for sandbox");
159 
160 	const cap_ioctl_t pcifd_ioctls[] = { PCIOCREAD, PCIOCWRITE, PCIOCGETBAR,
161 		PCIOCBARIO, PCIOCBARMMAP, PCIOCGETCONF };
162 	if (caph_ioctls_limit(pcifd, pcifd_ioctls, nitems(pcifd_ioctls)) == -1)
163 		errx(EX_OSERR, "Unable to apply rights for sandbox");
164 #endif
165 
166 	return (0);
167 }
168 
169 static uint32_t
host_read_config(int fd,const struct pcisel * sel,long reg,int width)170 host_read_config(int fd, const struct pcisel *sel, long reg, int width)
171 {
172 	struct pci_io pi;
173 
174 	bzero(&pi, sizeof(pi));
175 	pi.pi_sel = *sel;
176 	pi.pi_reg = reg;
177 	pi.pi_width = width;
178 
179 	if (ioctl(fd, PCIOCREAD, &pi) < 0)
180 		return (0);			/* XXX */
181 	else
182 		return (pi.pi_data);
183 }
184 
185 static uint32_t
passthru_read_config(const struct pcisel * sel,long reg,int width)186 passthru_read_config(const struct pcisel *sel, long reg, int width)
187 {
188 	return (host_read_config(pcifd, sel, reg, width));
189 }
190 
191 uint32_t
pci_host_read_config(const struct pcisel * sel,long reg,int width)192 pci_host_read_config(const struct pcisel *sel, long reg, int width)
193 {
194 	uint32_t ret;
195 	int fd;
196 
197 	fd = pcifd_open();
198 	if (fd < 0)
199 		return (0);
200 	ret = host_read_config(fd, sel, reg, width);
201 	(void)close(fd);
202 	return (ret);
203 }
204 
205 static void
host_write_config(int fd,const struct pcisel * sel,long reg,int width,uint32_t data)206 host_write_config(int fd, const struct pcisel *sel, long reg, int width,
207     uint32_t data)
208 {
209 	struct pci_io pi;
210 
211 	bzero(&pi, sizeof(pi));
212 	pi.pi_sel = *sel;
213 	pi.pi_reg = reg;
214 	pi.pi_width = width;
215 	pi.pi_data = data;
216 
217 	(void)ioctl(fd, PCIOCWRITE, &pi);		/* XXX */
218 }
219 
220 static void
passthru_write_config(const struct pcisel * sel,long reg,int width,uint32_t data)221 passthru_write_config(const struct pcisel *sel, long reg, int width,
222     uint32_t data)
223 {
224 	host_write_config(pcifd, sel, reg, width, data);
225 }
226 
227 void
pci_host_write_config(const struct pcisel * sel,long reg,int width,uint32_t data)228 pci_host_write_config(const struct pcisel *sel, long reg, int width,
229     uint32_t data)
230 {
231 	int fd;
232 
233 	fd = pcifd_open();
234 	if (fd < 0)
235 		return;
236 	host_write_config(fd, sel, reg, width, data);
237 	(void)close(fd);
238 }
239 
240 #ifdef LEGACY_SUPPORT
241 static int
passthru_add_msicap(struct pci_devinst * pi,int msgnum,int nextptr)242 passthru_add_msicap(struct pci_devinst *pi, int msgnum, int nextptr)
243 {
244 	int capoff;
245 	struct msicap msicap;
246 	u_char *capdata;
247 
248 	pci_populate_msicap(&msicap, msgnum, nextptr);
249 
250 	/*
251 	 * XXX
252 	 * Copy the msi capability structure in the last 16 bytes of the
253 	 * config space. This is wrong because it could shadow something
254 	 * useful to the device.
255 	 */
256 	capoff = 256 - roundup(sizeof(msicap), 4);
257 	capdata = (u_char *)&msicap;
258 	for (size_t i = 0; i < sizeof(msicap); i++)
259 		pci_set_cfgdata8(pi, capoff + i, capdata[i]);
260 
261 	return (capoff);
262 }
263 #endif	/* LEGACY_SUPPORT */
264 
265 static int
cfginitmsi(struct passthru_softc * sc)266 cfginitmsi(struct passthru_softc *sc)
267 {
268 	int i, ptr, capptr, cap, sts, caplen, table_size;
269 	uint32_t u32;
270 	struct pcisel sel;
271 	struct pci_devinst *pi;
272 	struct msixcap msixcap;
273 	char *msixcap_ptr;
274 
275 	pi = sc->psc_pi;
276 	sel = sc->psc_sel;
277 
278 	/*
279 	 * Parse the capabilities and cache the location of the MSI
280 	 * and MSI-X capabilities.
281 	 */
282 	sts = passthru_read_config(&sel, PCIR_STATUS, 2);
283 	if (sts & PCIM_STATUS_CAPPRESENT) {
284 		ptr = passthru_read_config(&sel, PCIR_CAP_PTR, 1);
285 		while (ptr != 0 && ptr != 0xff) {
286 			cap = passthru_read_config(&sel, ptr + PCICAP_ID, 1);
287 			if (cap == PCIY_MSI) {
288 				/*
289 				 * Copy the MSI capability into the config
290 				 * space of the emulated pci device
291 				 */
292 				sc->psc_msi.capoff = ptr;
293 				sc->psc_msi.msgctrl =
294 				    passthru_read_config(&sel, ptr + 2, 2);
295 				sc->psc_msi.emulated = 0;
296 				caplen = msi_caplen(sc->psc_msi.msgctrl);
297 				capptr = ptr;
298 				while (caplen > 0) {
299 					u32 = passthru_read_config(&sel, capptr,
300 					    4);
301 					pci_set_cfgdata32(pi, capptr, u32);
302 					caplen -= 4;
303 					capptr += 4;
304 				}
305 			} else if (cap == PCIY_MSIX) {
306 				/*
307 				 * Copy the MSI-X capability
308 				 */
309 				sc->psc_msix.capoff = ptr;
310 				caplen = 12;
311 				msixcap_ptr = (char *)&msixcap;
312 				capptr = ptr;
313 				while (caplen > 0) {
314 					u32 = passthru_read_config(&sel, capptr,
315 					    4);
316 					memcpy(msixcap_ptr, &u32, 4);
317 					pci_set_cfgdata32(pi, capptr, u32);
318 					caplen -= 4;
319 					capptr += 4;
320 					msixcap_ptr += 4;
321 				}
322 			}
323 			ptr = passthru_read_config(&sel, ptr + PCICAP_NEXTPTR,
324 			    1);
325 		}
326 	}
327 
328 	if (sc->psc_msix.capoff != 0) {
329 		pi->pi_msix.pba_bar =
330 		    msixcap.pba_info & PCIM_MSIX_BIR_MASK;
331 		pi->pi_msix.pba_offset =
332 		    msixcap.pba_info & ~PCIM_MSIX_BIR_MASK;
333 		pi->pi_msix.table_bar =
334 		    msixcap.table_info & PCIM_MSIX_BIR_MASK;
335 		pi->pi_msix.table_offset =
336 		    msixcap.table_info & ~PCIM_MSIX_BIR_MASK;
337 		pi->pi_msix.table_count = MSIX_TABLE_COUNT(msixcap.msgctrl);
338 		pi->pi_msix.pba_size = PBA_SIZE(pi->pi_msix.table_count);
339 
340 		/* Allocate the emulated MSI-X table array */
341 		table_size = pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
342 		pi->pi_msix.table = calloc(1, table_size);
343 
344 		/* Mask all table entries */
345 		for (i = 0; i < pi->pi_msix.table_count; i++) {
346 			pi->pi_msix.table[i].vector_control |=
347 						PCIM_MSIX_VCTRL_MASK;
348 		}
349 	}
350 
351 #ifdef LEGACY_SUPPORT
352 	/*
353 	 * If the passthrough device does not support MSI then craft a
354 	 * MSI capability for it. We link the new MSI capability at the
355 	 * head of the list of capabilities.
356 	 */
357 	if ((sts & PCIM_STATUS_CAPPRESENT) != 0 && sc->psc_msi.capoff == 0) {
358 		int origptr, msiptr;
359 		origptr = passthru_read_config(&sel, PCIR_CAP_PTR, 1);
360 		msiptr = passthru_add_msicap(pi, 1, origptr);
361 		sc->psc_msi.capoff = msiptr;
362 		sc->psc_msi.msgctrl = pci_get_cfgdata16(pi, msiptr + 2);
363 		sc->psc_msi.emulated = 1;
364 		pci_set_cfgdata8(pi, PCIR_CAP_PTR, msiptr);
365 	}
366 #endif
367 
368 	/* Make sure one of the capabilities is present */
369 	if (sc->psc_msi.capoff == 0 && sc->psc_msix.capoff == 0)
370 		return (-1);
371 	else
372 		return (0);
373 }
374 
375 static uint64_t
msix_table_read(struct passthru_softc * sc,uint64_t offset,int size)376 msix_table_read(struct passthru_softc *sc, uint64_t offset, int size)
377 {
378 	struct pci_devinst *pi;
379 	struct msix_table_entry *entry;
380 	uint8_t *src8;
381 	uint16_t *src16;
382 	uint32_t *src32;
383 	uint64_t *src64;
384 	uint64_t data;
385 	size_t entry_offset;
386 	uint32_t table_offset;
387 	int index, table_count;
388 
389 	pi = sc->psc_pi;
390 
391 	table_offset = pi->pi_msix.table_offset;
392 	table_count = pi->pi_msix.table_count;
393 	if (offset < table_offset ||
394 	    offset >= table_offset + table_count * MSIX_TABLE_ENTRY_SIZE) {
395 		switch (size) {
396 		case 1:
397 			src8 = (uint8_t *)(pi->pi_msix.mapped_addr + offset);
398 			data = *src8;
399 			break;
400 		case 2:
401 			src16 = (uint16_t *)(pi->pi_msix.mapped_addr + offset);
402 			data = *src16;
403 			break;
404 		case 4:
405 			src32 = (uint32_t *)(pi->pi_msix.mapped_addr + offset);
406 			data = *src32;
407 			break;
408 		case 8:
409 			src64 = (uint64_t *)(pi->pi_msix.mapped_addr + offset);
410 			data = *src64;
411 			break;
412 		default:
413 			return (-1);
414 		}
415 		return (data);
416 	}
417 
418 	offset -= table_offset;
419 	index = offset / MSIX_TABLE_ENTRY_SIZE;
420 	assert(index < table_count);
421 
422 	entry = &pi->pi_msix.table[index];
423 	entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
424 
425 	switch (size) {
426 	case 1:
427 		src8 = (uint8_t *)((uint8_t *)entry + entry_offset);
428 		data = *src8;
429 		break;
430 	case 2:
431 		src16 = (uint16_t *)((uint8_t *)entry + entry_offset);
432 		data = *src16;
433 		break;
434 	case 4:
435 		src32 = (uint32_t *)((uint8_t *)entry + entry_offset);
436 		data = *src32;
437 		break;
438 	case 8:
439 		src64 = (uint64_t *)((uint8_t *)entry + entry_offset);
440 		data = *src64;
441 		break;
442 	default:
443 		return (-1);
444 	}
445 
446 	return (data);
447 }
448 
449 static void
msix_table_write(struct passthru_softc * sc,uint64_t offset,int size,uint64_t data)450 msix_table_write(struct passthru_softc *sc, uint64_t offset, int size,
451     uint64_t data)
452 {
453 	struct pci_devinst *pi;
454 	struct msix_table_entry *entry;
455 	uint8_t *dest8;
456 	uint16_t *dest16;
457 	uint32_t *dest32;
458 	uint64_t *dest64;
459 	size_t entry_offset;
460 	uint32_t table_offset, vector_control;
461 	int index, table_count;
462 
463 	pi = sc->psc_pi;
464 
465 	table_offset = pi->pi_msix.table_offset;
466 	table_count = pi->pi_msix.table_count;
467 	if (offset < table_offset ||
468 	    offset >= table_offset + table_count * MSIX_TABLE_ENTRY_SIZE) {
469 		switch (size) {
470 		case 1:
471 			dest8 = (uint8_t *)(pi->pi_msix.mapped_addr + offset);
472 			*dest8 = data;
473 			break;
474 		case 2:
475 			dest16 = (uint16_t *)(pi->pi_msix.mapped_addr + offset);
476 			*dest16 = data;
477 			break;
478 		case 4:
479 			dest32 = (uint32_t *)(pi->pi_msix.mapped_addr + offset);
480 			*dest32 = data;
481 			break;
482 		case 8:
483 			dest64 = (uint64_t *)(pi->pi_msix.mapped_addr + offset);
484 			*dest64 = data;
485 			break;
486 		}
487 		return;
488 	}
489 
490 	offset -= table_offset;
491 	index = offset / MSIX_TABLE_ENTRY_SIZE;
492 	assert(index < table_count);
493 
494 	entry = &pi->pi_msix.table[index];
495 	entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
496 
497 	/* Only 4 byte naturally-aligned writes are supported */
498 	assert(size == 4);
499 	assert(entry_offset % 4 == 0);
500 
501 	vector_control = entry->vector_control;
502 	dest32 = (uint32_t *)((uint8_t *)entry + entry_offset);
503 	*dest32 = data;
504 	/* If MSI-X hasn't been enabled, do nothing */
505 	if (pi->pi_msix.enabled) {
506 		/* If the entry is masked, don't set it up */
507 		if ((entry->vector_control & PCIM_MSIX_VCTRL_MASK) == 0 ||
508 		    (vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
509 			(void)vm_setup_pptdev_msix(sc->psc_pi->pi_vmctx,
510 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
511 			    sc->psc_sel.pc_func, index, entry->addr,
512 			    entry->msg_data, entry->vector_control);
513 		}
514 	}
515 }
516 
517 static int
init_msix_table(struct passthru_softc * sc)518 init_msix_table(struct passthru_softc *sc)
519 {
520 	struct pci_devinst *pi = sc->psc_pi;
521 	struct pci_bar_mmap pbm;
522 	int b, s, f;
523 	uint32_t table_size, table_offset;
524 
525 	assert(pci_msix_table_bar(pi) >= 0 && pci_msix_pba_bar(pi) >= 0);
526 
527 	b = sc->psc_sel.pc_bus;
528 	s = sc->psc_sel.pc_dev;
529 	f = sc->psc_sel.pc_func;
530 
531 	/*
532 	 * Map the region of the BAR containing the MSI-X table.  This is
533 	 * necessary for two reasons:
534 	 * 1. The PBA may reside in the first or last page containing the MSI-X
535 	 *    table.
536 	 * 2. While PCI devices are not supposed to use the page(s) containing
537 	 *    the MSI-X table for other purposes, some do in practice.
538 	 */
539 	memset(&pbm, 0, sizeof(pbm));
540 	pbm.pbm_sel = sc->psc_sel;
541 	pbm.pbm_flags = PCIIO_BAR_MMAP_RW;
542 	pbm.pbm_reg = PCIR_BAR(pi->pi_msix.table_bar);
543 	pbm.pbm_memattr = VM_MEMATTR_DEVICE;
544 
545 	if (ioctl(pcifd, PCIOCBARMMAP, &pbm) != 0) {
546 		warn("Failed to map MSI-X table BAR on %d/%d/%d", b, s, f);
547 		return (-1);
548 	}
549 	assert(pbm.pbm_bar_off == 0);
550 	pi->pi_msix.mapped_addr = (uint8_t *)(uintptr_t)pbm.pbm_map_base;
551 	pi->pi_msix.mapped_size = pbm.pbm_map_length;
552 
553 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
554 
555 	table_size = pi->pi_msix.table_offset - table_offset;
556 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
557 	table_size = roundup2(table_size, 4096);
558 
559 	/*
560 	 * Unmap any pages not containing the table, we do not need to emulate
561 	 * accesses to them.  Avoid releasing address space to help ensure that
562 	 * a buggy out-of-bounds access causes a crash.
563 	 */
564 	if (table_offset != 0)
565 		if (mprotect(pi->pi_msix.mapped_addr, table_offset,
566 		    PROT_NONE) != 0)
567 			warn("Failed to unmap MSI-X table BAR region");
568 	if (table_offset + table_size != pi->pi_msix.mapped_size)
569 		if (mprotect(
570 		    pi->pi_msix.mapped_addr + table_offset + table_size,
571 		    pi->pi_msix.mapped_size - (table_offset + table_size),
572 		    PROT_NONE) != 0)
573 			warn("Failed to unmap MSI-X table BAR region");
574 
575 	return (0);
576 }
577 
578 static int
cfginitbar(struct passthru_softc * sc)579 cfginitbar(struct passthru_softc *sc)
580 {
581 	int i, error;
582 	struct pci_devinst *pi;
583 	struct pci_bar_io bar;
584 	enum pcibar_type bartype;
585 	uint64_t base, size;
586 
587 	pi = sc->psc_pi;
588 
589 	/*
590 	 * Initialize BAR registers
591 	 */
592 	for (i = 0; i <= PCI_BARMAX; i++) {
593 		uint8_t lobits;
594 
595 		bzero(&bar, sizeof(bar));
596 		bar.pbi_sel = sc->psc_sel;
597 		bar.pbi_reg = PCIR_BAR(i);
598 
599 		if (ioctl(pcifd, PCIOCGETBAR, &bar) < 0)
600 			continue;
601 
602 		if (PCI_BAR_IO(bar.pbi_base)) {
603 			bartype = PCIBAR_IO;
604 			base = bar.pbi_base & PCIM_BAR_IO_BASE;
605 		} else {
606 			switch (bar.pbi_base & PCIM_BAR_MEM_TYPE) {
607 			case PCIM_BAR_MEM_64:
608 				bartype = PCIBAR_MEM64;
609 				break;
610 			default:
611 				bartype = PCIBAR_MEM32;
612 				break;
613 			}
614 			base = bar.pbi_base & PCIM_BAR_MEM_BASE;
615 		}
616 		size = bar.pbi_length;
617 
618 		if (bartype != PCIBAR_IO) {
619 			if (((base | size) & PAGE_MASK) != 0) {
620 				warnx("passthru device %d/%d/%d BAR %d: "
621 				    "base %#lx or size %#lx not page aligned\n",
622 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
623 				    sc->psc_sel.pc_func, i, base, size);
624 				return (-1);
625 			}
626 		}
627 
628 		/* Cache information about the "real" BAR */
629 		sc->psc_bar[i].type = bartype;
630 		sc->psc_bar[i].size = size;
631 		sc->psc_bar[i].addr = base;
632 		sc->psc_bar[i].lobits = 0;
633 
634 		/* Allocate the BAR in the guest I/O or MMIO space */
635 		error = pci_emul_alloc_bar(pi, i, bartype, size);
636 		if (error)
637 			return (-1);
638 
639 		/* Use same lobits as physical bar */
640 		lobits = (uint8_t)passthru_read_config(&sc->psc_sel,
641 		    PCIR_BAR(i), 0x01);
642 		if (bartype == PCIBAR_MEM32 || bartype == PCIBAR_MEM64) {
643 			lobits &= ~PCIM_BAR_MEM_BASE;
644 		} else {
645 			lobits &= ~PCIM_BAR_IO_BASE;
646 		}
647 		sc->psc_bar[i].lobits = lobits;
648 		pi->pi_bar[i].lobits = lobits;
649 
650 		/*
651 		 * 64-bit BAR takes up two slots so skip the next one.
652 		 */
653 		if (bartype == PCIBAR_MEM64) {
654 			i++;
655 			assert(i <= PCI_BARMAX);
656 			sc->psc_bar[i].type = PCIBAR_MEMHI64;
657 		}
658 	}
659 	return (0);
660 }
661 
662 static int
cfginit(struct pci_devinst * pi,int bus,int slot,int func)663 cfginit(struct pci_devinst *pi, int bus, int slot, int func)
664 {
665 	int error;
666 	struct passthru_softc *sc;
667 	uint16_t cmd;
668 	uint8_t intline, intpin;
669 
670 	error = 1;
671 	sc = pi->pi_arg;
672 
673 	bzero(&sc->psc_sel, sizeof(struct pcisel));
674 	sc->psc_sel.pc_bus = bus;
675 	sc->psc_sel.pc_dev = slot;
676 	sc->psc_sel.pc_func = func;
677 
678 	/*
679 	 * Copy physical PCI header to virtual config space.  COMMAND,
680 	 * INTLINE, and INTPIN shouldn't be aligned with their
681 	 * physical value and they are already set by pci_emul_init().
682 	 */
683 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
684 	intline = pci_get_cfgdata8(pi, PCIR_INTLINE);
685 	intpin = pci_get_cfgdata8(pi, PCIR_INTPIN);
686 	for (int i = 0; i <= PCIR_MAXLAT; i += 4) {
687 		pci_set_cfgdata32(pi, i,
688 		    passthru_read_config(&sc->psc_sel, i, 4));
689 	}
690 	pci_set_cfgdata16(pi, PCIR_COMMAND, cmd);
691 	pci_set_cfgdata8(pi, PCIR_INTLINE, intline);
692 	pci_set_cfgdata8(pi, PCIR_INTPIN, intpin);
693 
694 	if (cfginitmsi(sc) != 0) {
695 		warnx("failed to initialize MSI for PCI %d/%d/%d",
696 		    bus, slot, func);
697 		goto done;
698 	}
699 
700 	if (cfginitbar(sc) != 0) {
701 		warnx("failed to initialize BARs for PCI %d/%d/%d",
702 		    bus, slot, func);
703 		goto done;
704 	}
705 
706 	if (pci_msix_table_bar(pi) >= 0) {
707 		error = init_msix_table(sc);
708 		if (error != 0) {
709 			warnx(
710 			    "failed to initialize MSI-X table for PCI %d/%d/%d: %d",
711 			    bus, slot, func, error);
712 			goto done;
713 		}
714 	}
715 
716 	error = 0;				/* success */
717 done:
718 	return (error);
719 }
720 
721 struct passthru_mmio_mapping *
passthru_get_mmio(struct passthru_softc * sc,int num)722 passthru_get_mmio(struct passthru_softc *sc, int num)
723 {
724 	assert(sc != NULL);
725 	assert(num < PASSTHRU_MMIO_MAX);
726 
727 	return (&sc->psc_mmio_map[num]);
728 }
729 
730 struct pcisel *
passthru_get_sel(struct passthru_softc * sc)731 passthru_get_sel(struct passthru_softc *sc)
732 {
733 	assert(sc != NULL);
734 
735 	return (&sc->psc_sel);
736 }
737 
738 int
set_pcir_handler(struct passthru_softc * sc,int reg,int len,cfgread_handler rhandler,cfgwrite_handler whandler)739 set_pcir_handler(struct passthru_softc *sc, int reg, int len,
740     cfgread_handler rhandler, cfgwrite_handler whandler)
741 {
742 	if (reg > PCI_REGMAX || reg + len > PCI_REGMAX + 1)
743 		return (-1);
744 
745 	for (int i = reg; i < reg + len; ++i) {
746 		assert(sc->psc_pcir_rhandler[i] == NULL || rhandler == NULL);
747 		assert(sc->psc_pcir_whandler[i] == NULL || whandler == NULL);
748 		sc->psc_pcir_rhandler[i] = rhandler;
749 		sc->psc_pcir_whandler[i] = whandler;
750 	}
751 
752 	return (0);
753 }
754 
755 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)756 passthru_set_bar_handler(struct passthru_softc *sc, int baridx, uint64_t off,
757     uint64_t size, passthru_read_handler rhandler,
758     passthru_write_handler whandler)
759 {
760 	struct passthru_bar_handler *handler_new;
761 	struct passthru_bar_handler *handler;
762 
763 	assert(sc->psc_bar[baridx].type == PCIBAR_IO ||
764 	    sc->psc_bar[baridx].type == PCIBAR_MEM32 ||
765 	    sc->psc_bar[baridx].type == PCIBAR_MEM64);
766 	assert(sc->psc_bar[baridx].size >= off + size);
767 	assert(off < off + size);
768 
769 	handler_new = malloc(sizeof(struct passthru_bar_handler));
770 	if (handler_new == NULL) {
771 		return (ENOMEM);
772 	}
773 
774 	handler_new->off = off;
775 	handler_new->size = size;
776 	handler_new->read = rhandler;
777 	handler_new->write = whandler;
778 
779 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
780 		if (handler->off < handler_new->off) {
781 			assert(handler->off + handler->size < handler_new->off);
782 			continue;
783 		}
784 		assert(handler->off > handler_new->off + handler_new->size);
785 		TAILQ_INSERT_BEFORE(handler, handler_new, chain);
786 		return (0);
787 	}
788 
789 	TAILQ_INSERT_TAIL(&sc->psc_bar_handler[baridx], handler_new, chain);
790 
791 	return (0);
792 }
793 
794 static int
passthru_legacy_config(nvlist_t * nvl,const char * opts)795 passthru_legacy_config(nvlist_t *nvl, const char *opts)
796 {
797 	const char *cp;
798 	char *tofree;
799 	char value[16];
800 	int bus, slot, func;
801 
802 	if (opts == NULL)
803 		return (0);
804 
805 	cp = strchr(opts, ',');
806 
807 	if (strncmp(opts, "ppt", strlen("ppt")) == 0) {
808 		tofree = strndup(opts, cp - opts);
809 		set_config_value_node(nvl, "pptdev", tofree);
810 		free(tofree);
811 	} else if (sscanf(opts, "pci0:%d:%d:%d", &bus, &slot, &func) == 3 ||
812 	    sscanf(opts, "pci%d:%d:%d", &bus, &slot, &func) == 3 ||
813 	    sscanf(opts, "%d/%d/%d", &bus, &slot, &func) == 3) {
814 		snprintf(value, sizeof(value), "%d", bus);
815 		set_config_value_node(nvl, "bus", value);
816 		snprintf(value, sizeof(value), "%d", slot);
817 		set_config_value_node(nvl, "slot", value);
818 		snprintf(value, sizeof(value), "%d", func);
819 		set_config_value_node(nvl, "func", value);
820 	} else {
821 		EPRINTLN("passthru: invalid options \"%s\"", opts);
822 		return (-1);
823 	}
824 
825 	if (cp == NULL) {
826 		return (0);
827 	}
828 
829 	return (pci_parse_legacy_config(nvl, cp + 1));
830 }
831 
832 static int
passthru_init_rom(struct passthru_softc * const sc,const char * const romfile)833 passthru_init_rom(struct passthru_softc *const sc, const char *const romfile)
834 {
835 	if (romfile == NULL) {
836 		return (0);
837 	}
838 
839 	const int fd = open(romfile, O_RDONLY);
840 	if (fd < 0) {
841 		warnx("%s: can't open romfile \"%s\"", __func__, romfile);
842 		return (-1);
843 	}
844 
845 	struct stat sbuf;
846 	if (fstat(fd, &sbuf) < 0) {
847 		warnx("%s: can't fstat romfile \"%s\"", __func__, romfile);
848 		close(fd);
849 		return (-1);
850 	}
851 	const uint64_t rom_size = sbuf.st_size;
852 
853 	void *const rom_data = mmap(NULL, rom_size, PROT_READ, MAP_SHARED, fd,
854 	    0);
855 	if (rom_data == MAP_FAILED) {
856 		warnx("%s: unable to mmap romfile \"%s\" (%d)", __func__,
857 		    romfile, errno);
858 		close(fd);
859 		return (-1);
860 	}
861 
862 	void *rom_addr;
863 	int error = pci_emul_alloc_rom(sc->psc_pi, rom_size, &rom_addr);
864 	if (error) {
865 		warnx("%s: failed to alloc rom segment", __func__);
866 		munmap(rom_data, rom_size);
867 		close(fd);
868 		return (error);
869 	}
870 	memcpy(rom_addr, rom_data, rom_size);
871 
872 	sc->psc_bar[PCI_ROM_IDX].type = PCIBAR_ROM;
873 	sc->psc_bar[PCI_ROM_IDX].addr = (uint64_t)rom_addr;
874 	sc->psc_bar[PCI_ROM_IDX].size = rom_size;
875 
876 	munmap(rom_data, rom_size);
877 	close(fd);
878 
879 	return (0);
880 }
881 
882 static bool
passthru_lookup_pptdev(const char * name,int * bus,int * slot,int * func)883 passthru_lookup_pptdev(const char *name, int *bus, int *slot, int *func)
884 {
885 	struct pci_conf_io pc;
886 	struct pci_conf conf[1];
887 	struct pci_match_conf patterns[1];
888 	char *cp;
889 
890 	bzero(&pc, sizeof(struct pci_conf_io));
891 	pc.match_buf_len = sizeof(conf);
892 	pc.matches = conf;
893 
894 	bzero(&patterns, sizeof(patterns));
895 
896 	/*
897 	 * The pattern structure requires the unit to be split out from
898 	 * the driver name.  Walk backwards from the end of the name to
899 	 * find the start of the unit.
900 	 */
901 	cp = strchr(name, '\0');
902 	assert(cp != NULL);
903 	while (cp != name && isdigit(cp[-1]))
904 		cp--;
905 	if (cp == name || !isdigit(*cp)) {
906 		EPRINTLN("Invalid passthru device name %s", name);
907 		return (false);
908 	}
909 	if ((size_t)(cp - name) + 1 > sizeof(patterns[0].pd_name)) {
910 		EPRINTLN("Passthru device name %s is too long", name);
911 		return (false);
912 	}
913 	memcpy(patterns[0].pd_name, name, cp - name);
914 	patterns[0].pd_unit = strtol(cp, &cp, 10);
915 	if (*cp != '\0') {
916 		EPRINTLN("Invalid passthru device name %s", name);
917 		return (false);
918 	}
919 	patterns[0].flags = PCI_GETCONF_MATCH_NAME | PCI_GETCONF_MATCH_UNIT;
920 	pc.num_patterns = 1;
921 	pc.pat_buf_len = sizeof(patterns);
922 	pc.patterns = patterns;
923 
924 	if (ioctl(pcifd, PCIOCGETCONF, &pc) == -1) {
925 		EPRINTLN("ioctl(PCIOCGETCONF): %s", strerror(errno));
926 		return (false);
927 	}
928 	if (pc.status != PCI_GETCONF_LAST_DEVICE &&
929 	    pc.status != PCI_GETCONF_MORE_DEVS) {
930 		EPRINTLN("error returned from PCIOCGETCONF ioctl");
931 		return (false);
932 	}
933 	if (pc.num_matches == 0) {
934 		EPRINTLN("Passthru device %s not found", name);
935 		return (false);
936 	}
937 
938 	if (conf[0].pc_sel.pc_domain != 0) {
939 		EPRINTLN("Passthru device %s on unsupported domain", name);
940 		return (false);
941 	}
942 	*bus = conf[0].pc_sel.pc_bus;
943 	*slot = conf[0].pc_sel.pc_dev;
944 	*func = conf[0].pc_sel.pc_func;
945 	return (true);
946 }
947 
948 static int
passthru_init(struct pci_devinst * pi,nvlist_t * nvl)949 passthru_init(struct pci_devinst *pi, nvlist_t *nvl)
950 {
951 	int bus, slot, func, error, memflags;
952 	struct passthru_softc *sc;
953 	struct passthru_dev **devpp;
954 	struct passthru_dev *devp, *dev = NULL;
955 	const char *value;
956 
957 	sc = NULL;
958 	error = 1;
959 
960 	memflags = vm_get_memflags(pi->pi_vmctx);
961 	if (!(memflags & VM_MEM_F_WIRED)) {
962 		warnx("passthru requires guest memory to be wired");
963 		return (error);
964 	}
965 
966 	if (pcifd < 0 && pcifd_init()) {
967 		return (error);
968 	}
969 
970 #define GET_INT_CONFIG(var, name) do {					\
971 	value = get_config_value_node(nvl, name);			\
972 	if (value == NULL) {						\
973 		EPRINTLN("passthru: missing required %s setting", name); \
974 		return (error);						\
975 	}								\
976 	var = atoi(value);						\
977 } while (0)
978 
979 	value = get_config_value_node(nvl, "pptdev");
980 	if (value != NULL) {
981 		if (!passthru_lookup_pptdev(value, &bus, &slot, &func))
982 			return (error);
983 	} else {
984 		GET_INT_CONFIG(bus, "bus");
985 		GET_INT_CONFIG(slot, "slot");
986 		GET_INT_CONFIG(func, "func");
987 	}
988 
989 	if (vm_assign_pptdev(pi->pi_vmctx, bus, slot, func) != 0) {
990 		warnx("PCI device at %d/%d/%d is not using the ppt(4) driver",
991 		    bus, slot, func);
992 		goto done;
993 	}
994 
995 	sc = calloc(1, sizeof(struct passthru_softc));
996 
997 	pi->pi_arg = sc;
998 	sc->psc_pi = pi;
999 
1000 	for (uint8_t i = 0; i < PCI_BARMAX_WITH_ROM + 1; ++i)
1001 		TAILQ_INIT(&sc->psc_bar_handler[i]);
1002 
1003 	/* initialize config space */
1004 	if ((error = cfginit(pi, bus, slot, func)) != 0)
1005 		goto done;
1006 
1007 	/* initialize ROM */
1008 	if ((error = passthru_init_rom(sc,
1009             get_config_value_node(nvl, "rom"))) != 0)
1010 		goto done;
1011 
1012 	/* Emulate most PCI header register. */
1013 	if ((error = set_pcir_handler(sc, 0, PCIR_MAXLAT + 1,
1014 	    passthru_cfgread_emulate, passthru_cfgwrite_emulate)) != 0)
1015 		goto done;
1016 
1017 	/* Allow access to the physical status register. */
1018 	if ((error = set_pcir_handler(sc, PCIR_COMMAND, 0x04, NULL, NULL)) != 0)
1019 		goto done;
1020 
1021 	SET_FOREACH(devpp, passthru_dev_set) {
1022 		devp = *devpp;
1023 		assert(devp->probe != NULL);
1024 		if (devp->probe(pi) == 0) {
1025 			dev = devp;
1026 			break;
1027 		}
1028 	}
1029 
1030 	if (dev != NULL) {
1031 		error = dev->init(pi, nvl);
1032 		if (error != 0)
1033 			goto done;
1034 	}
1035 
1036 	error = 0;		/* success */
1037 done:
1038 	if (error) {
1039 		if (dev != NULL)
1040 			dev->deinit(pi);
1041 		free(sc);
1042 		vm_unassign_pptdev(pi->pi_vmctx, bus, slot, func);
1043 	}
1044 	return (error);
1045 }
1046 
1047 static int
msicap_access(struct passthru_softc * sc,int coff)1048 msicap_access(struct passthru_softc *sc, int coff)
1049 {
1050 	int caplen;
1051 
1052 	if (sc->psc_msi.capoff == 0)
1053 		return (0);
1054 
1055 	caplen = msi_caplen(sc->psc_msi.msgctrl);
1056 
1057 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
1058 		return (1);
1059 	else
1060 		return (0);
1061 }
1062 
1063 static int
msixcap_access(struct passthru_softc * sc,int coff)1064 msixcap_access(struct passthru_softc *sc, int coff)
1065 {
1066 	if (sc->psc_msix.capoff == 0)
1067 		return (0);
1068 
1069 	return (coff >= sc->psc_msix.capoff &&
1070 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
1071 }
1072 
1073 static int
passthru_cfgread_default(struct passthru_softc * sc,struct pci_devinst * pi __unused,int coff,int bytes,uint32_t * rv)1074 passthru_cfgread_default(struct passthru_softc *sc,
1075     struct pci_devinst *pi __unused, int coff, int bytes, uint32_t *rv)
1076 {
1077 	/*
1078 	 * MSI capability is emulated.
1079 	 */
1080 	if (msicap_access(sc, coff) || msixcap_access(sc, coff))
1081 		return (-1);
1082 
1083 	/*
1084 	 * Emulate the command register.  If a single read reads both the
1085 	 * command and status registers, read the status register from the
1086 	 * device's config space.
1087 	 */
1088 	if (coff == PCIR_COMMAND) {
1089 		uint32_t st;
1090 
1091 		if (bytes <= 2)
1092 			return (-1);
1093 		st = passthru_read_config(&sc->psc_sel, PCIR_STATUS, 2);
1094 		*rv = (st << 16) | pci_get_cfgdata16(pi, PCIR_COMMAND);
1095 		return (0);
1096 	}
1097 
1098 	/* Everything else just read from the device's config space */
1099 	*rv = passthru_read_config(&sc->psc_sel, coff, bytes);
1100 
1101 	return (0);
1102 }
1103 
1104 int
passthru_cfgread_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t * rv __unused)1105 passthru_cfgread_emulate(struct passthru_softc *sc __unused,
1106     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1107     uint32_t *rv __unused)
1108 {
1109 	return (-1);
1110 }
1111 
1112 static int
passthru_cfgread(struct pci_devinst * pi,int coff,int bytes,uint32_t * rv)1113 passthru_cfgread(struct pci_devinst *pi, int coff, int bytes, uint32_t *rv)
1114 {
1115 	struct passthru_softc *sc;
1116 
1117 	sc = pi->pi_arg;
1118 
1119 	if (sc->psc_pcir_rhandler[coff] != NULL)
1120 		return (sc->psc_pcir_rhandler[coff](sc, pi, coff, bytes, rv));
1121 
1122 	return (passthru_cfgread_default(sc, pi, coff, bytes, rv));
1123 }
1124 
1125 static int
passthru_cfgwrite_default(struct passthru_softc * sc,struct pci_devinst * pi,int coff,int bytes,uint32_t val)1126 passthru_cfgwrite_default(struct passthru_softc *sc, struct pci_devinst *pi,
1127     int coff, int bytes, uint32_t val)
1128 {
1129 	int error, msix_table_entries, i;
1130 	uint16_t cmd_old;
1131 
1132 	/*
1133 	 * MSI capability is emulated
1134 	 */
1135 	if (msicap_access(sc, coff)) {
1136 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
1137 		    PCIY_MSI);
1138 		error = vm_setup_pptdev_msi(pi->pi_vmctx, sc->psc_sel.pc_bus,
1139 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
1140 			pi->pi_msi.addr, pi->pi_msi.msg_data,
1141 			pi->pi_msi.maxmsgnum);
1142 		if (error != 0)
1143 			err(1, "vm_setup_pptdev_msi");
1144 		return (0);
1145 	}
1146 
1147 	if (msixcap_access(sc, coff)) {
1148 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
1149 		    PCIY_MSIX);
1150 		if (pi->pi_msix.enabled) {
1151 			msix_table_entries = pi->pi_msix.table_count;
1152 			for (i = 0; i < msix_table_entries; i++) {
1153 				error = vm_setup_pptdev_msix(pi->pi_vmctx,
1154 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1155 				    sc->psc_sel.pc_func, i,
1156 				    pi->pi_msix.table[i].addr,
1157 				    pi->pi_msix.table[i].msg_data,
1158 				    pi->pi_msix.table[i].vector_control);
1159 
1160 				if (error)
1161 					err(1, "vm_setup_pptdev_msix");
1162 			}
1163 		} else {
1164 			error = vm_disable_pptdev_msix(pi->pi_vmctx,
1165 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1166 			    sc->psc_sel.pc_func);
1167 			if (error)
1168 				err(1, "vm_disable_pptdev_msix");
1169 		}
1170 		return (0);
1171 	}
1172 
1173 	/*
1174 	 * The command register is emulated, but the status register
1175 	 * is passed through.
1176 	 */
1177 	if (coff == PCIR_COMMAND) {
1178 		if (bytes <= 2)
1179 			return (-1);
1180 
1181 		/* Update the physical status register. */
1182 		passthru_write_config(&sc->psc_sel, PCIR_STATUS, val >> 16, 2);
1183 
1184 		/* Update the virtual command register. */
1185 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
1186 		pci_set_cfgdata16(pi, PCIR_COMMAND, val & 0xffff);
1187 		pci_emul_cmd_changed(pi, cmd_old);
1188 		return (0);
1189 	}
1190 
1191 	passthru_write_config(&sc->psc_sel, coff, bytes, val);
1192 
1193 	return (0);
1194 }
1195 
1196 int
passthru_cfgwrite_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t val __unused)1197 passthru_cfgwrite_emulate(struct passthru_softc *sc __unused,
1198     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1199     uint32_t val __unused)
1200 {
1201 	return (-1);
1202 }
1203 
1204 static int
passthru_cfgwrite(struct pci_devinst * pi,int coff,int bytes,uint32_t val)1205 passthru_cfgwrite(struct pci_devinst *pi, int coff, int bytes, uint32_t val)
1206 {
1207 	struct passthru_softc *sc;
1208 
1209 	sc = pi->pi_arg;
1210 
1211 	if (sc->psc_pcir_whandler[coff] != NULL)
1212 		return (sc->psc_pcir_whandler[coff](sc, pi, coff, bytes, val));
1213 
1214 	return (passthru_cfgwrite_default(sc, pi, coff, bytes, val));
1215 }
1216 
1217 static void
passthru_write(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)1218 passthru_write(struct pci_devinst *pi, int baridx, uint64_t offset, int size,
1219     uint64_t value)
1220 {
1221 	struct passthru_softc *sc;
1222 	struct passthru_bar_handler *handler;
1223 	struct pci_bar_ioreq pio;
1224 
1225 	sc = pi->pi_arg;
1226 
1227 	if (baridx == pci_msix_table_bar(pi)) {
1228 		msix_table_write(sc, offset, size, value);
1229 	} else {
1230 		assert(size == 1 || size == 2 || size == 4);
1231 
1232 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1233 			if (offset >= handler->off + handler->size) {
1234 				continue;
1235 			} else if (offset < handler->off) {
1236 				assert(offset + size < handler->off);
1237 				/*
1238 				 * The list is sorted in ascending order, so all
1239 				 * remaining handlers will have an even larger
1240 				 * offset.
1241 				 */
1242 				break;
1243 			}
1244 
1245 			assert(offset + size <= handler->off + handler->size);
1246 
1247 			handler->write(pi, baridx,
1248 			    offset - handler->off, size, value);
1249 			return;
1250 		}
1251 
1252 		bzero(&pio, sizeof(pio));
1253 		pio.pbi_sel = sc->psc_sel;
1254 		pio.pbi_op = PCIBARIO_WRITE;
1255 		pio.pbi_bar = baridx;
1256 		pio.pbi_offset = (uint32_t)offset;
1257 		pio.pbi_width = size;
1258 		pio.pbi_value = (uint32_t)value;
1259 
1260 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1261 	}
1262 }
1263 
1264 static uint64_t
passthru_read(struct pci_devinst * pi,int baridx,uint64_t offset,int size)1265 passthru_read(struct pci_devinst *pi, int baridx, uint64_t offset, int size)
1266 {
1267 	struct passthru_softc *sc;
1268 	struct passthru_bar_handler *handler;
1269 	struct pci_bar_ioreq pio;
1270 	uint64_t val;
1271 
1272 	sc = pi->pi_arg;
1273 
1274 	if (baridx == pci_msix_table_bar(pi)) {
1275 		val = msix_table_read(sc, offset, size);
1276 	} else {
1277 		assert(size == 1 || size == 2 || size == 4);
1278 
1279 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1280 			if (offset >= handler->off + handler->size) {
1281 				continue;
1282 			} else if (offset < handler->off) {
1283 				assert(offset + size < handler->off);
1284 				/*
1285 				 * The list is sorted in ascending order, so all
1286 				 * remaining handlers will have an even larger
1287 				 * offset.
1288 				 */
1289 				break;
1290 			}
1291 
1292 			assert(offset + size <= handler->off + handler->size);
1293 
1294 			return (handler->read(pi, baridx,
1295 			    offset - handler->off, size));
1296 		}
1297 
1298 		bzero(&pio, sizeof(pio));
1299 		pio.pbi_sel = sc->psc_sel;
1300 		pio.pbi_op = PCIBARIO_READ;
1301 		pio.pbi_bar = baridx;
1302 		pio.pbi_offset = (uint32_t)offset;
1303 		pio.pbi_width = size;
1304 
1305 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1306 
1307 		val = pio.pbi_value;
1308 	}
1309 
1310 	return (val);
1311 }
1312 
1313 static void
passthru_msix_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1314 passthru_msix_addr(struct pci_devinst *pi, int baridx, int enabled,
1315     uint64_t address)
1316 {
1317 	struct passthru_softc *sc;
1318 	size_t remaining;
1319 	uint32_t table_size, table_offset;
1320 
1321 	sc = pi->pi_arg;
1322 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
1323 	if (table_offset > 0) {
1324 		if (!enabled) {
1325 			if (vm_unmap_pptdev_mmio(pi->pi_vmctx,
1326 						 sc->psc_sel.pc_bus,
1327 						 sc->psc_sel.pc_dev,
1328 						 sc->psc_sel.pc_func, address,
1329 						 table_offset) != 0)
1330 				warnx("pci_passthru: unmap_pptdev_mmio failed");
1331 		} else {
1332 			if (vm_map_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1333 					       sc->psc_sel.pc_dev,
1334 					       sc->psc_sel.pc_func, address,
1335 					       table_offset,
1336 					       sc->psc_bar[baridx].addr) != 0)
1337 				warnx("pci_passthru: map_pptdev_mmio failed");
1338 		}
1339 	}
1340 	table_size = pi->pi_msix.table_offset - table_offset;
1341 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
1342 	table_size = roundup2(table_size, 4096);
1343 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
1344 	if (remaining > 0) {
1345 		address += table_offset + table_size;
1346 		if (!enabled) {
1347 			if (vm_unmap_pptdev_mmio(pi->pi_vmctx,
1348 						 sc->psc_sel.pc_bus,
1349 						 sc->psc_sel.pc_dev,
1350 						 sc->psc_sel.pc_func, address,
1351 						 remaining) != 0)
1352 				warnx("pci_passthru: unmap_pptdev_mmio failed");
1353 		} else {
1354 			if (vm_map_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1355 					       sc->psc_sel.pc_dev,
1356 					       sc->psc_sel.pc_func, address,
1357 					       remaining,
1358 					       sc->psc_bar[baridx].addr +
1359 					       table_offset + table_size) != 0)
1360 				warnx("pci_passthru: map_pptdev_mmio failed");
1361 		}
1362 	}
1363 }
1364 
1365 static int
passthru_mmio_map(struct pci_devinst * pi,int baridx,int enabled,uint64_t address,uint64_t off,uint64_t size)1366 passthru_mmio_map(struct pci_devinst *pi, int baridx, int enabled,
1367     uint64_t address, uint64_t off, uint64_t size)
1368 {
1369 	struct passthru_softc *sc;
1370 
1371 	sc = pi->pi_arg;
1372 	if (!enabled) {
1373 		if (vm_unmap_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1374 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1375 		    size) != 0) {
1376 			warnx("pci_passthru: unmap_pptdev_mmio failed");
1377 			return (-1);
1378 		}
1379 	} else {
1380 		if (vm_map_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1381 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1382 		    size, sc->psc_bar[baridx].addr + off) != 0) {
1383 			warnx("pci_passthru: map_pptdev_mmio failed");
1384 			return (-1);
1385 		}
1386 	}
1387 
1388 	return (0);
1389 }
1390 
1391 static void
passthru_mmio_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1392 passthru_mmio_addr(struct pci_devinst *pi, int baridx, int enabled,
1393     uint64_t address)
1394 {
1395 	struct passthru_softc *sc;
1396 	struct passthru_bar_handler *handler;
1397 	uint64_t off;
1398 
1399 	sc = pi->pi_arg;
1400 
1401 	off = 0;
1402 
1403 	/* The queue is sorted by offset in ascending order. */
1404 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1405 		uint64_t handler_off = trunc_page(handler->off);
1406 		uint64_t handler_end = round_page(handler->off + handler->size);
1407 
1408 		/*
1409 		 * When two handlers point to the same page, handler_off can be
1410 		 * lower than off. That's fine because we have nothing to do in
1411 		 * that case.
1412 		 */
1413 		if (handler_off > off) {
1414 			passthru_mmio_map(pi, baridx, enabled, address, off,
1415 			    handler_off - off);
1416 		}
1417 
1418 		off = handler_end;
1419 	}
1420 
1421 	passthru_mmio_map(pi, baridx, enabled, address, off,
1422 	    sc->psc_bar[baridx].size - off);
1423 }
1424 
1425 static void
passthru_addr_rom(struct pci_devinst * const pi,const int idx,const int enabled)1426 passthru_addr_rom(struct pci_devinst *const pi, const int idx,
1427     const int enabled)
1428 {
1429 	const uint64_t addr = pi->pi_bar[idx].addr;
1430 	const uint64_t size = pi->pi_bar[idx].size;
1431 
1432 	if (!enabled) {
1433 		if (vm_munmap_memseg(pi->pi_vmctx, addr, size) != 0) {
1434 			errx(4, "%s: munmap_memseg @ [%016lx - %016lx] failed",
1435 			    __func__, addr, addr + size);
1436 		}
1437 
1438 	} else {
1439 		if (vm_mmap_memseg(pi->pi_vmctx, addr, VM_PCIROM,
1440 			pi->pi_romoffset, size, PROT_READ | PROT_EXEC) != 0) {
1441 			errx(4, "%s: mmap_memseg @ [%016lx - %016lx]  failed",
1442 			    __func__, addr, addr + size);
1443 		}
1444 	}
1445 }
1446 
1447 static void
passthru_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1448 passthru_addr(struct pci_devinst *pi, int baridx, int enabled, uint64_t address)
1449 {
1450 	switch (pi->pi_bar[baridx].type) {
1451 	case PCIBAR_IO:
1452 		/* IO BARs are emulated */
1453 		break;
1454 	case PCIBAR_ROM:
1455 		passthru_addr_rom(pi, baridx, enabled);
1456 		break;
1457 	case PCIBAR_MEM32:
1458 	case PCIBAR_MEM64:
1459 		if (baridx == pci_msix_table_bar(pi))
1460 			passthru_msix_addr(pi, baridx, enabled, address);
1461 		else
1462 			passthru_mmio_addr(pi, baridx, enabled, address);
1463 		break;
1464 	default:
1465 		errx(4, "%s: invalid BAR type %d", __func__,
1466 		    pi->pi_bar[baridx].type);
1467 	}
1468 }
1469 
1470 static const struct pci_devemu passthru = {
1471 	.pe_emu		= "passthru",
1472 	.pe_init	= passthru_init,
1473 	.pe_legacy_config = passthru_legacy_config,
1474 	.pe_cfgwrite	= passthru_cfgwrite,
1475 	.pe_cfgread	= passthru_cfgread,
1476 	.pe_barwrite 	= passthru_write,
1477 	.pe_barread    	= passthru_read,
1478 	.pe_baraddr	= passthru_addr,
1479 };
1480 PCI_EMUL_SET(passthru);
1481