xref: /src/usr.sbin/bhyve/pci_passthru.c (revision 7ab5e3f29a50bc9294a139cc0e8e661a7c036ba3)
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 		if (errno == ENOENT) {
991 			EPRINTLN(
992 		    "PCI device at %d/%d/%d is not using the ppt driver",
993 			    bus, slot, func);
994 		} else {
995 			EPRINTLN("vm_assign_pptdev: %s", strerror(errno));
996 		}
997 		goto done;
998 	}
999 
1000 	sc = calloc(1, sizeof(struct passthru_softc));
1001 
1002 	pi->pi_arg = sc;
1003 	sc->psc_pi = pi;
1004 
1005 	for (uint8_t i = 0; i < PCI_BARMAX_WITH_ROM + 1; ++i)
1006 		TAILQ_INIT(&sc->psc_bar_handler[i]);
1007 
1008 	/* initialize config space */
1009 	if ((error = cfginit(pi, bus, slot, func)) != 0)
1010 		goto done;
1011 
1012 	/* initialize ROM */
1013 	if ((error = passthru_init_rom(sc,
1014             get_config_value_node(nvl, "rom"))) != 0)
1015 		goto done;
1016 
1017 	/* Emulate most PCI header register. */
1018 	if ((error = set_pcir_handler(sc, 0, PCIR_MAXLAT + 1,
1019 	    passthru_cfgread_emulate, passthru_cfgwrite_emulate)) != 0)
1020 		goto done;
1021 
1022 	/* Allow access to the physical status register. */
1023 	if ((error = set_pcir_handler(sc, PCIR_COMMAND, 0x04, NULL, NULL)) != 0)
1024 		goto done;
1025 
1026 	SET_FOREACH(devpp, passthru_dev_set) {
1027 		devp = *devpp;
1028 		assert(devp->probe != NULL);
1029 		if (devp->probe(pi) == 0) {
1030 			dev = devp;
1031 			break;
1032 		}
1033 	}
1034 
1035 	if (dev != NULL) {
1036 		error = dev->init(pi, nvl);
1037 		if (error != 0)
1038 			goto done;
1039 	}
1040 
1041 	error = 0;		/* success */
1042 done:
1043 	if (error) {
1044 		if (dev != NULL)
1045 			dev->deinit(pi);
1046 		free(sc);
1047 		vm_unassign_pptdev(pi->pi_vmctx, bus, slot, func);
1048 	}
1049 	return (error);
1050 }
1051 
1052 static int
msicap_access(struct passthru_softc * sc,int coff)1053 msicap_access(struct passthru_softc *sc, int coff)
1054 {
1055 	int caplen;
1056 
1057 	if (sc->psc_msi.capoff == 0)
1058 		return (0);
1059 
1060 	caplen = msi_caplen(sc->psc_msi.msgctrl);
1061 
1062 	if (coff >= sc->psc_msi.capoff && coff < sc->psc_msi.capoff + caplen)
1063 		return (1);
1064 	else
1065 		return (0);
1066 }
1067 
1068 static int
msixcap_access(struct passthru_softc * sc,int coff)1069 msixcap_access(struct passthru_softc *sc, int coff)
1070 {
1071 	if (sc->psc_msix.capoff == 0)
1072 		return (0);
1073 
1074 	return (coff >= sc->psc_msix.capoff &&
1075 	        coff < sc->psc_msix.capoff + MSIX_CAPLEN);
1076 }
1077 
1078 static int
passthru_cfgread_default(struct passthru_softc * sc,struct pci_devinst * pi __unused,int coff,int bytes,uint32_t * rv)1079 passthru_cfgread_default(struct passthru_softc *sc,
1080     struct pci_devinst *pi __unused, int coff, int bytes, uint32_t *rv)
1081 {
1082 	/*
1083 	 * MSI capability is emulated.
1084 	 */
1085 	if (msicap_access(sc, coff) || msixcap_access(sc, coff))
1086 		return (-1);
1087 
1088 	/*
1089 	 * Emulate the command register.  If a single read reads both the
1090 	 * command and status registers, read the status register from the
1091 	 * device's config space.
1092 	 */
1093 	if (coff == PCIR_COMMAND) {
1094 		uint32_t st;
1095 
1096 		if (bytes <= 2)
1097 			return (-1);
1098 		st = passthru_read_config(&sc->psc_sel, PCIR_STATUS, 2);
1099 		*rv = (st << 16) | pci_get_cfgdata16(pi, PCIR_COMMAND);
1100 		return (0);
1101 	}
1102 
1103 	/* Everything else just read from the device's config space */
1104 	*rv = passthru_read_config(&sc->psc_sel, coff, bytes);
1105 
1106 	return (0);
1107 }
1108 
1109 int
passthru_cfgread_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t * rv __unused)1110 passthru_cfgread_emulate(struct passthru_softc *sc __unused,
1111     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1112     uint32_t *rv __unused)
1113 {
1114 	return (-1);
1115 }
1116 
1117 static int
passthru_cfgread(struct pci_devinst * pi,int coff,int bytes,uint32_t * rv)1118 passthru_cfgread(struct pci_devinst *pi, int coff, int bytes, uint32_t *rv)
1119 {
1120 	struct passthru_softc *sc;
1121 
1122 	sc = pi->pi_arg;
1123 
1124 	if (sc->psc_pcir_rhandler[coff] != NULL)
1125 		return (sc->psc_pcir_rhandler[coff](sc, pi, coff, bytes, rv));
1126 
1127 	return (passthru_cfgread_default(sc, pi, coff, bytes, rv));
1128 }
1129 
1130 static int
passthru_cfgwrite_default(struct passthru_softc * sc,struct pci_devinst * pi,int coff,int bytes,uint32_t val)1131 passthru_cfgwrite_default(struct passthru_softc *sc, struct pci_devinst *pi,
1132     int coff, int bytes, uint32_t val)
1133 {
1134 	int error, msix_table_entries, i;
1135 	uint16_t cmd_old;
1136 
1137 	/*
1138 	 * MSI capability is emulated
1139 	 */
1140 	if (msicap_access(sc, coff)) {
1141 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msi.capoff,
1142 		    PCIY_MSI);
1143 		error = vm_setup_pptdev_msi(pi->pi_vmctx, sc->psc_sel.pc_bus,
1144 			sc->psc_sel.pc_dev, sc->psc_sel.pc_func,
1145 			pi->pi_msi.addr, pi->pi_msi.msg_data,
1146 			pi->pi_msi.maxmsgnum);
1147 		if (error != 0)
1148 			err(1, "vm_setup_pptdev_msi");
1149 		return (0);
1150 	}
1151 
1152 	if (msixcap_access(sc, coff)) {
1153 		pci_emul_capwrite(pi, coff, bytes, val, sc->psc_msix.capoff,
1154 		    PCIY_MSIX);
1155 		if (pi->pi_msix.enabled) {
1156 			msix_table_entries = pi->pi_msix.table_count;
1157 			for (i = 0; i < msix_table_entries; i++) {
1158 				error = vm_setup_pptdev_msix(pi->pi_vmctx,
1159 				    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1160 				    sc->psc_sel.pc_func, i,
1161 				    pi->pi_msix.table[i].addr,
1162 				    pi->pi_msix.table[i].msg_data,
1163 				    pi->pi_msix.table[i].vector_control);
1164 
1165 				if (error)
1166 					err(1, "vm_setup_pptdev_msix");
1167 			}
1168 		} else {
1169 			error = vm_disable_pptdev_msix(pi->pi_vmctx,
1170 			    sc->psc_sel.pc_bus, sc->psc_sel.pc_dev,
1171 			    sc->psc_sel.pc_func);
1172 			if (error)
1173 				err(1, "vm_disable_pptdev_msix");
1174 		}
1175 		return (0);
1176 	}
1177 
1178 	/*
1179 	 * The command register is emulated, but the status register
1180 	 * is passed through.
1181 	 */
1182 	if (coff == PCIR_COMMAND) {
1183 		if (bytes <= 2)
1184 			return (-1);
1185 
1186 		/* Update the physical status register. */
1187 		passthru_write_config(&sc->psc_sel, PCIR_STATUS, val >> 16, 2);
1188 
1189 		/* Update the virtual command register. */
1190 		cmd_old = pci_get_cfgdata16(pi, PCIR_COMMAND);
1191 		pci_set_cfgdata16(pi, PCIR_COMMAND, val & 0xffff);
1192 		pci_emul_cmd_changed(pi, cmd_old);
1193 		return (0);
1194 	}
1195 
1196 	passthru_write_config(&sc->psc_sel, coff, bytes, val);
1197 
1198 	return (0);
1199 }
1200 
1201 int
passthru_cfgwrite_emulate(struct passthru_softc * sc __unused,struct pci_devinst * pi __unused,int coff __unused,int bytes __unused,uint32_t val __unused)1202 passthru_cfgwrite_emulate(struct passthru_softc *sc __unused,
1203     struct pci_devinst *pi __unused, int coff __unused, int bytes __unused,
1204     uint32_t val __unused)
1205 {
1206 	return (-1);
1207 }
1208 
1209 static int
passthru_cfgwrite(struct pci_devinst * pi,int coff,int bytes,uint32_t val)1210 passthru_cfgwrite(struct pci_devinst *pi, int coff, int bytes, uint32_t val)
1211 {
1212 	struct passthru_softc *sc;
1213 
1214 	sc = pi->pi_arg;
1215 
1216 	if (sc->psc_pcir_whandler[coff] != NULL)
1217 		return (sc->psc_pcir_whandler[coff](sc, pi, coff, bytes, val));
1218 
1219 	return (passthru_cfgwrite_default(sc, pi, coff, bytes, val));
1220 }
1221 
1222 static void
passthru_write(struct pci_devinst * pi,int baridx,uint64_t offset,int size,uint64_t value)1223 passthru_write(struct pci_devinst *pi, int baridx, uint64_t offset, int size,
1224     uint64_t value)
1225 {
1226 	struct passthru_softc *sc;
1227 	struct passthru_bar_handler *handler;
1228 	struct pci_bar_ioreq pio;
1229 
1230 	sc = pi->pi_arg;
1231 
1232 	if (baridx == pci_msix_table_bar(pi)) {
1233 		msix_table_write(sc, offset, size, value);
1234 	} else {
1235 		assert(size == 1 || size == 2 || size == 4);
1236 
1237 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1238 			if (offset >= handler->off + handler->size) {
1239 				continue;
1240 			} else if (offset < handler->off) {
1241 				assert(offset + size < handler->off);
1242 				/*
1243 				 * The list is sorted in ascending order, so all
1244 				 * remaining handlers will have an even larger
1245 				 * offset.
1246 				 */
1247 				break;
1248 			}
1249 
1250 			assert(offset + size <= handler->off + handler->size);
1251 
1252 			handler->write(pi, baridx,
1253 			    offset - handler->off, size, value);
1254 			return;
1255 		}
1256 
1257 		bzero(&pio, sizeof(pio));
1258 		pio.pbi_sel = sc->psc_sel;
1259 		pio.pbi_op = PCIBARIO_WRITE;
1260 		pio.pbi_bar = baridx;
1261 		pio.pbi_offset = (uint32_t)offset;
1262 		pio.pbi_width = size;
1263 		pio.pbi_value = (uint32_t)value;
1264 
1265 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1266 	}
1267 }
1268 
1269 static uint64_t
passthru_read(struct pci_devinst * pi,int baridx,uint64_t offset,int size)1270 passthru_read(struct pci_devinst *pi, int baridx, uint64_t offset, int size)
1271 {
1272 	struct passthru_softc *sc;
1273 	struct passthru_bar_handler *handler;
1274 	struct pci_bar_ioreq pio;
1275 	uint64_t val;
1276 
1277 	sc = pi->pi_arg;
1278 
1279 	if (baridx == pci_msix_table_bar(pi)) {
1280 		val = msix_table_read(sc, offset, size);
1281 	} else {
1282 		assert(size == 1 || size == 2 || size == 4);
1283 
1284 		TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1285 			if (offset >= handler->off + handler->size) {
1286 				continue;
1287 			} else if (offset < handler->off) {
1288 				assert(offset + size < handler->off);
1289 				/*
1290 				 * The list is sorted in ascending order, so all
1291 				 * remaining handlers will have an even larger
1292 				 * offset.
1293 				 */
1294 				break;
1295 			}
1296 
1297 			assert(offset + size <= handler->off + handler->size);
1298 
1299 			return (handler->read(pi, baridx,
1300 			    offset - handler->off, size));
1301 		}
1302 
1303 		bzero(&pio, sizeof(pio));
1304 		pio.pbi_sel = sc->psc_sel;
1305 		pio.pbi_op = PCIBARIO_READ;
1306 		pio.pbi_bar = baridx;
1307 		pio.pbi_offset = (uint32_t)offset;
1308 		pio.pbi_width = size;
1309 
1310 		(void)ioctl(pcifd, PCIOCBARIO, &pio);
1311 
1312 		val = pio.pbi_value;
1313 	}
1314 
1315 	return (val);
1316 }
1317 
1318 static int
passthru_mmio_map(struct pci_devinst * pi,int baridx,int enabled,uint64_t address,uint64_t off,uint64_t size)1319 passthru_mmio_map(struct pci_devinst *pi, int baridx, int enabled,
1320     uint64_t address, uint64_t off, uint64_t size)
1321 {
1322 	struct passthru_softc *sc;
1323 
1324 	sc = pi->pi_arg;
1325 	if (!enabled) {
1326 		if (vm_unmap_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1327 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1328 		    size) != 0) {
1329 			EPRINTLN("pci_passthru: unmap_pptdev_mmio failed: %s",
1330 			    strerror(errno));
1331 			return (-1);
1332 		}
1333 	} else {
1334 		if (vm_map_pptdev_mmio(pi->pi_vmctx, sc->psc_sel.pc_bus,
1335 		    sc->psc_sel.pc_dev, sc->psc_sel.pc_func, address + off,
1336 		    size, sc->psc_bar[baridx].addr + off) != 0) {
1337 			EPRINTLN("pci_passthru: map_pptdev_mmio failed: %s",
1338 			    strerror(errno));
1339 			return (-1);
1340 		}
1341 	}
1342 
1343 	return (0);
1344 }
1345 
1346 static void
passthru_msix_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1347 passthru_msix_addr(struct pci_devinst *pi, int baridx, int enabled,
1348     uint64_t address)
1349 {
1350 	size_t remaining;
1351 	uint32_t table_size, table_offset;
1352 
1353 	table_offset = rounddown2(pi->pi_msix.table_offset, 4096);
1354 	if (table_offset > 0) {
1355 		(void)passthru_mmio_map(pi, baridx, enabled, address, 0,
1356 		    table_offset);
1357 	}
1358 	table_size = pi->pi_msix.table_offset - table_offset;
1359 	table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE;
1360 	table_size = roundup2(table_size, 4096);
1361 	remaining = pi->pi_bar[baridx].size - table_offset - table_size;
1362 	if (remaining > 0) {
1363 		(void)passthru_mmio_map(pi, baridx, enabled, address,
1364 		    table_offset + table_size, remaining);
1365 	}
1366 }
1367 
1368 static void
passthru_mmio_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1369 passthru_mmio_addr(struct pci_devinst *pi, int baridx, int enabled,
1370     uint64_t address)
1371 {
1372 	struct passthru_softc *sc;
1373 	struct passthru_bar_handler *handler;
1374 	uint64_t off;
1375 
1376 	sc = pi->pi_arg;
1377 
1378 	off = 0;
1379 
1380 	/* The queue is sorted by offset in ascending order. */
1381 	TAILQ_FOREACH(handler, &sc->psc_bar_handler[baridx], chain) {
1382 		uint64_t handler_off = trunc_page(handler->off);
1383 		uint64_t handler_end = round_page(handler->off + handler->size);
1384 
1385 		/*
1386 		 * When two handlers point to the same page, handler_off can be
1387 		 * lower than off. That's fine because we have nothing to do in
1388 		 * that case.
1389 		 */
1390 		if (handler_off > off) {
1391 			passthru_mmio_map(pi, baridx, enabled, address, off,
1392 			    handler_off - off);
1393 		}
1394 
1395 		off = handler_end;
1396 	}
1397 
1398 	passthru_mmio_map(pi, baridx, enabled, address, off,
1399 	    sc->psc_bar[baridx].size - off);
1400 }
1401 
1402 static void
passthru_addr_rom(struct pci_devinst * const pi,const int idx,const int enabled)1403 passthru_addr_rom(struct pci_devinst *const pi, const int idx,
1404     const int enabled)
1405 {
1406 	const uint64_t addr = pi->pi_bar[idx].addr;
1407 	const uint64_t size = pi->pi_bar[idx].size;
1408 
1409 	if (!enabled) {
1410 		if (vm_munmap_memseg(pi->pi_vmctx, addr, size) != 0) {
1411 			errx(4, "%s: munmap_memseg @ [%016lx - %016lx] failed",
1412 			    __func__, addr, addr + size);
1413 		}
1414 
1415 	} else {
1416 		if (vm_mmap_memseg(pi->pi_vmctx, addr, VM_PCIROM,
1417 			pi->pi_romoffset, size, PROT_READ | PROT_EXEC) != 0) {
1418 			errx(4, "%s: mmap_memseg @ [%016lx - %016lx]  failed",
1419 			    __func__, addr, addr + size);
1420 		}
1421 	}
1422 }
1423 
1424 static void
passthru_addr(struct pci_devinst * pi,int baridx,int enabled,uint64_t address)1425 passthru_addr(struct pci_devinst *pi, int baridx, int enabled, uint64_t address)
1426 {
1427 	switch (pi->pi_bar[baridx].type) {
1428 	case PCIBAR_IO:
1429 		/* IO BARs are emulated */
1430 		break;
1431 	case PCIBAR_ROM:
1432 		passthru_addr_rom(pi, baridx, enabled);
1433 		break;
1434 	case PCIBAR_MEM32:
1435 	case PCIBAR_MEM64:
1436 		if (baridx == pci_msix_table_bar(pi))
1437 			passthru_msix_addr(pi, baridx, enabled, address);
1438 		else
1439 			passthru_mmio_addr(pi, baridx, enabled, address);
1440 		break;
1441 	default:
1442 		errx(4, "%s: invalid BAR type %d", __func__,
1443 		    pi->pi_bar[baridx].type);
1444 	}
1445 }
1446 
1447 static const struct pci_devemu passthru = {
1448 	.pe_emu		= "passthru",
1449 	.pe_init	= passthru_init,
1450 	.pe_legacy_config = passthru_legacy_config,
1451 	.pe_cfgwrite	= passthru_cfgwrite,
1452 	.pe_cfgread	= passthru_cfgread,
1453 	.pe_barwrite 	= passthru_write,
1454 	.pe_barread    	= passthru_read,
1455 	.pe_baraddr	= passthru_addr,
1456 };
1457 PCI_EMUL_SET(passthru);
1458