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