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