]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/pci_emul.c
bhyve: Don't leak uninitialized bits in NVMe completion statuses.
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / pci_emul.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 #include <sys/linker_set.h>
36 #include <sys/mman.h>
37
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <pthread.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <strings.h>
46 #include <assert.h>
47 #include <stdbool.h>
48 #include <sysexits.h>
49
50 #include <machine/vmm.h>
51 #include <machine/vmm_snapshot.h>
52 #include <vmmapi.h>
53
54 #include "acpi.h"
55 #include "bhyverun.h"
56 #include "config.h"
57 #include "debug.h"
58 #include "inout.h"
59 #include "ioapic.h"
60 #include "mem.h"
61 #include "pci_emul.h"
62 #include "pci_irq.h"
63 #include "pci_lpc.h"
64
65 #define CONF1_ADDR_PORT    0x0cf8
66 #define CONF1_DATA_PORT    0x0cfc
67
68 #define CONF1_ENABLE       0x80000000ul
69
70 #define MAXBUSES        (PCI_BUSMAX + 1)
71 #define MAXSLOTS        (PCI_SLOTMAX + 1)
72 #define MAXFUNCS        (PCI_FUNCMAX + 1)
73
74 #define GB              (1024 * 1024 * 1024UL)
75
76 struct funcinfo {
77         nvlist_t *fi_config;
78         struct pci_devemu *fi_pde;
79         struct pci_devinst *fi_devi;
80 };
81
82 struct intxinfo {
83         int     ii_count;
84         int     ii_pirq_pin;
85         int     ii_ioapic_irq;
86 };
87
88 struct slotinfo {
89         struct intxinfo si_intpins[4];
90         struct funcinfo si_funcs[MAXFUNCS];
91 };
92
93 struct businfo {
94         uint16_t iobase, iolimit;               /* I/O window */
95         uint32_t membase32, memlimit32;         /* mmio window below 4GB */
96         uint64_t membase64, memlimit64;         /* mmio window above 4GB */
97         struct slotinfo slotinfo[MAXSLOTS];
98 };
99
100 static struct businfo *pci_businfo[MAXBUSES];
101
102 SET_DECLARE(pci_devemu_set, struct pci_devemu);
103
104 static uint64_t pci_emul_iobase;
105 static uint8_t *pci_emul_rombase;
106 static uint64_t pci_emul_romoffset;
107 static uint8_t *pci_emul_romlim;
108 static uint64_t pci_emul_membase32;
109 static uint64_t pci_emul_membase64;
110 static uint64_t pci_emul_memlim64;
111
112 struct pci_bar_allocation {
113         TAILQ_ENTRY(pci_bar_allocation) chain;
114         struct pci_devinst *pdi;
115         int idx;
116         enum pcibar_type type;
117         uint64_t size;
118 };
119
120 static TAILQ_HEAD(pci_bar_list, pci_bar_allocation) pci_bars =
121     TAILQ_HEAD_INITIALIZER(pci_bars);
122
123 #define PCI_EMUL_IOBASE         0x2000
124 #define PCI_EMUL_IOLIMIT        0x10000
125
126 #define PCI_EMUL_ROMSIZE 0x10000000
127
128 #define PCI_EMUL_ECFG_BASE      0xE0000000                  /* 3.5GB */
129 #define PCI_EMUL_ECFG_SIZE      (MAXBUSES * 1024 * 1024)    /* 1MB per bus */
130 SYSRES_MEM(PCI_EMUL_ECFG_BASE, PCI_EMUL_ECFG_SIZE);
131
132 /*
133  * OVMF always uses 0xC0000000 as base address for 32 bit PCI MMIO. Don't
134  * change this address without changing it in OVMF.
135  */
136 #define PCI_EMUL_MEMBASE32 0xC0000000
137 #define PCI_EMUL_MEMLIMIT32     PCI_EMUL_ECFG_BASE
138 #define PCI_EMUL_MEMSIZE64      (32*GB)
139
140 static struct pci_devemu *pci_emul_finddev(const char *name);
141 static void pci_lintr_route(struct pci_devinst *pi);
142 static void pci_lintr_update(struct pci_devinst *pi);
143 static void pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot,
144     int func, int coff, int bytes, uint32_t *val);
145
146 static __inline void
147 CFGWRITE(struct pci_devinst *pi, int coff, uint32_t val, int bytes)
148 {
149
150         if (bytes == 1)
151                 pci_set_cfgdata8(pi, coff, val);
152         else if (bytes == 2)
153                 pci_set_cfgdata16(pi, coff, val);
154         else
155                 pci_set_cfgdata32(pi, coff, val);
156 }
157
158 static __inline uint32_t
159 CFGREAD(struct pci_devinst *pi, int coff, int bytes)
160 {
161
162         if (bytes == 1)
163                 return (pci_get_cfgdata8(pi, coff));
164         else if (bytes == 2)
165                 return (pci_get_cfgdata16(pi, coff));
166         else
167                 return (pci_get_cfgdata32(pi, coff));
168 }
169
170 static int
171 is_pcir_bar(int coff)
172 {
173         return (coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1));
174 }
175
176 static int
177 is_pcir_bios(int coff)
178 {
179         return (coff >= PCIR_BIOS && coff < PCIR_BIOS + 4);
180 }
181
182 /*
183  * I/O access
184  */
185
186 /*
187  * Slot options are in the form:
188  *
189  *  <bus>:<slot>:<func>,<emul>[,<config>]
190  *  <slot>[:<func>],<emul>[,<config>]
191  *
192  *  slot is 0..31
193  *  func is 0..7
194  *  emul is a string describing the type of PCI device e.g. virtio-net
195  *  config is an optional string, depending on the device, that can be
196  *  used for configuration.
197  *   Examples are:
198  *     1,virtio-net,tap0
199  *     3:0,dummy
200  */
201 static void
202 pci_parse_slot_usage(char *aopt)
203 {
204
205         EPRINTLN("Invalid PCI slot info field \"%s\"", aopt);
206 }
207
208 /*
209  * Helper function to parse a list of comma-separated options where
210  * each option is formatted as "name[=value]".  If no value is
211  * provided, the option is treated as a boolean and is given a value
212  * of true.
213  */
214 int
215 pci_parse_legacy_config(nvlist_t *nvl, const char *opt)
216 {
217         char *config, *name, *tofree, *value;
218
219         if (opt == NULL)
220                 return (0);
221
222         config = tofree = strdup(opt);
223         while ((name = strsep(&config, ",")) != NULL) {
224                 value = strchr(name, '=');
225                 if (value != NULL) {
226                         *value = '\0';
227                         value++;
228                         set_config_value_node(nvl, name, value);
229                 } else
230                         set_config_bool_node(nvl, name, true);
231         }
232         free(tofree);
233         return (0);
234 }
235
236 /*
237  * PCI device configuration is stored in MIBs that encode the device's
238  * location:
239  *
240  * pci.<bus>.<slot>.<func>
241  *
242  * Where "bus", "slot", and "func" are all decimal values without
243  * leading zeroes.  Each valid device must have a "device" node which
244  * identifies the driver model of the device.
245  *
246  * Device backends can provide a parser for the "config" string.  If
247  * a custom parser is not provided, pci_parse_legacy_config() is used
248  * to parse the string.
249  */
250 int
251 pci_parse_slot(char *opt)
252 {
253         char node_name[sizeof("pci.XXX.XX.X")];
254         struct pci_devemu *pde;
255         char *emul, *config, *str, *cp;
256         int error, bnum, snum, fnum;
257         nvlist_t *nvl;
258
259         error = -1;
260         str = strdup(opt);
261
262         emul = config = NULL;
263         if ((cp = strchr(str, ',')) != NULL) {
264                 *cp = '\0';
265                 emul = cp + 1;
266                 if ((cp = strchr(emul, ',')) != NULL) {
267                         *cp = '\0';
268                         config = cp + 1;
269                 }
270         } else {
271                 pci_parse_slot_usage(opt);
272                 goto done;
273         }
274
275         /* <bus>:<slot>:<func> */
276         if (sscanf(str, "%d:%d:%d", &bnum, &snum, &fnum) != 3) {
277                 bnum = 0;
278                 /* <slot>:<func> */
279                 if (sscanf(str, "%d:%d", &snum, &fnum) != 2) {
280                         fnum = 0;
281                         /* <slot> */
282                         if (sscanf(str, "%d", &snum) != 1) {
283                                 snum = -1;
284                         }
285                 }
286         }
287
288         if (bnum < 0 || bnum >= MAXBUSES || snum < 0 || snum >= MAXSLOTS ||
289             fnum < 0 || fnum >= MAXFUNCS) {
290                 pci_parse_slot_usage(opt);
291                 goto done;
292         }
293
294         pde = pci_emul_finddev(emul);
295         if (pde == NULL) {
296                 EPRINTLN("pci slot %d:%d:%d: unknown device \"%s\"", bnum, snum,
297                     fnum, emul);
298                 goto done;
299         }
300
301         snprintf(node_name, sizeof(node_name), "pci.%d.%d.%d", bnum, snum,
302             fnum);
303         nvl = find_config_node(node_name);
304         if (nvl != NULL) {
305                 EPRINTLN("pci slot %d:%d:%d already occupied!", bnum, snum,
306                     fnum);
307                 goto done;
308         }
309         nvl = create_config_node(node_name);
310         if (pde->pe_alias != NULL)
311                 set_config_value_node(nvl, "device", pde->pe_alias);
312         else
313                 set_config_value_node(nvl, "device", pde->pe_emu);
314
315         if (pde->pe_legacy_config != NULL)
316                 error = pde->pe_legacy_config(nvl, config);
317         else
318                 error = pci_parse_legacy_config(nvl, config);
319 done:
320         free(str);
321         return (error);
322 }
323
324 void
325 pci_print_supported_devices(void)
326 {
327         struct pci_devemu **pdpp, *pdp;
328
329         SET_FOREACH(pdpp, pci_devemu_set) {
330                 pdp = *pdpp;
331                 printf("%s\n", pdp->pe_emu);
332         }
333 }
334
335 static int
336 pci_valid_pba_offset(struct pci_devinst *pi, uint64_t offset)
337 {
338
339         if (offset < pi->pi_msix.pba_offset)
340                 return (0);
341
342         if (offset >= pi->pi_msix.pba_offset + pi->pi_msix.pba_size) {
343                 return (0);
344         }
345
346         return (1);
347 }
348
349 int
350 pci_emul_msix_twrite(struct pci_devinst *pi, uint64_t offset, int size,
351                      uint64_t value)
352 {
353         int msix_entry_offset;
354         int tab_index;
355         char *dest;
356
357         /* support only 4 or 8 byte writes */
358         if (size != 4 && size != 8)
359                 return (-1);
360
361         /*
362          * Return if table index is beyond what device supports
363          */
364         tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
365         if (tab_index >= pi->pi_msix.table_count)
366                 return (-1);
367
368         msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
369
370         /* support only aligned writes */
371         if ((msix_entry_offset % size) != 0)
372                 return (-1);
373
374         dest = (char *)(pi->pi_msix.table + tab_index);
375         dest += msix_entry_offset;
376
377         if (size == 4)
378                 *((uint32_t *)dest) = value;
379         else
380                 *((uint64_t *)dest) = value;
381
382         return (0);
383 }
384
385 uint64_t
386 pci_emul_msix_tread(struct pci_devinst *pi, uint64_t offset, int size)
387 {
388         char *dest;
389         int msix_entry_offset;
390         int tab_index;
391         uint64_t retval = ~0;
392
393         /*
394          * The PCI standard only allows 4 and 8 byte accesses to the MSI-X
395          * table but we also allow 1 byte access to accommodate reads from
396          * ddb.
397          */
398         if (size != 1 && size != 4 && size != 8)
399                 return (retval);
400
401         msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
402
403         /* support only aligned reads */
404         if ((msix_entry_offset % size) != 0) {
405                 return (retval);
406         }
407
408         tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
409
410         if (tab_index < pi->pi_msix.table_count) {
411                 /* valid MSI-X Table access */
412                 dest = (char *)(pi->pi_msix.table + tab_index);
413                 dest += msix_entry_offset;
414
415                 if (size == 1)
416                         retval = *((uint8_t *)dest);
417                 else if (size == 4)
418                         retval = *((uint32_t *)dest);
419                 else
420                         retval = *((uint64_t *)dest);
421         } else if (pci_valid_pba_offset(pi, offset)) {
422                 /* return 0 for PBA access */
423                 retval = 0;
424         }
425
426         return (retval);
427 }
428
429 int
430 pci_msix_table_bar(struct pci_devinst *pi)
431 {
432
433         if (pi->pi_msix.table != NULL)
434                 return (pi->pi_msix.table_bar);
435         else
436                 return (-1);
437 }
438
439 int
440 pci_msix_pba_bar(struct pci_devinst *pi)
441 {
442
443         if (pi->pi_msix.table != NULL)
444                 return (pi->pi_msix.pba_bar);
445         else
446                 return (-1);
447 }
448
449 static int
450 pci_emul_io_handler(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
451                     uint32_t *eax, void *arg)
452 {
453         struct pci_devinst *pdi = arg;
454         struct pci_devemu *pe = pdi->pi_d;
455         uint64_t offset;
456         int i;
457
458         assert(port >= 0);
459
460         for (i = 0; i <= PCI_BARMAX; i++) {
461                 if (pdi->pi_bar[i].type == PCIBAR_IO &&
462                     (uint64_t)port >= pdi->pi_bar[i].addr &&
463                     (uint64_t)port + bytes <=
464                     pdi->pi_bar[i].addr + pdi->pi_bar[i].size) {
465                         offset = port - pdi->pi_bar[i].addr;
466                         if (in)
467                                 *eax = (*pe->pe_barread)(ctx, vcpu, pdi, i,
468                                                          offset, bytes);
469                         else
470                                 (*pe->pe_barwrite)(ctx, vcpu, pdi, i, offset,
471                                                    bytes, *eax);
472                         return (0);
473                 }
474         }
475         return (-1);
476 }
477
478 static int
479 pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
480                      int size, uint64_t *val, void *arg1, long arg2)
481 {
482         struct pci_devinst *pdi = arg1;
483         struct pci_devemu *pe = pdi->pi_d;
484         uint64_t offset;
485         int bidx = (int) arg2;
486
487         assert(bidx <= PCI_BARMAX);
488         assert(pdi->pi_bar[bidx].type == PCIBAR_MEM32 ||
489                pdi->pi_bar[bidx].type == PCIBAR_MEM64);
490         assert(addr >= pdi->pi_bar[bidx].addr &&
491                addr + size <= pdi->pi_bar[bidx].addr + pdi->pi_bar[bidx].size);
492
493         offset = addr - pdi->pi_bar[bidx].addr;
494
495         if (dir == MEM_F_WRITE) {
496                 if (size == 8) {
497                         (*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset,
498                                            4, *val & 0xffffffff);
499                         (*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset + 4,
500                                            4, *val >> 32);
501                 } else {
502                         (*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset,
503                                            size, *val);
504                 }
505         } else {
506                 if (size == 8) {
507                         *val = (*pe->pe_barread)(ctx, vcpu, pdi, bidx,
508                                                  offset, 4);
509                         *val |= (*pe->pe_barread)(ctx, vcpu, pdi, bidx,
510                                                   offset + 4, 4) << 32;
511                 } else {
512                         *val = (*pe->pe_barread)(ctx, vcpu, pdi, bidx,
513                                                  offset, size);
514                 }
515         }
516
517         return (0);
518 }
519
520
521 static int
522 pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,
523                         uint64_t *addr)
524 {
525         uint64_t base;
526
527         assert((size & (size - 1)) == 0);       /* must be a power of 2 */
528
529         base = roundup2(*baseptr, size);
530
531         if (base + size <= limit) {
532                 *addr = base;
533                 *baseptr = base + size;
534                 return (0);
535         } else
536                 return (-1);
537 }
538
539 /*
540  * Register (or unregister) the MMIO or I/O region associated with the BAR
541  * register 'idx' of an emulated pci device.
542  */
543 static void
544 modify_bar_registration(struct pci_devinst *pi, int idx, int registration)
545 {
546         struct pci_devemu *pe;
547         int error;
548         struct inout_port iop;
549         struct mem_range mr;
550
551         pe = pi->pi_d;
552         switch (pi->pi_bar[idx].type) {
553         case PCIBAR_IO:
554                 bzero(&iop, sizeof(struct inout_port));
555                 iop.name = pi->pi_name;
556                 iop.port = pi->pi_bar[idx].addr;
557                 iop.size = pi->pi_bar[idx].size;
558                 if (registration) {
559                         iop.flags = IOPORT_F_INOUT;
560                         iop.handler = pci_emul_io_handler;
561                         iop.arg = pi;
562                         error = register_inout(&iop);
563                 } else
564                         error = unregister_inout(&iop);
565                 if (pe->pe_baraddr != NULL)
566                         (*pe->pe_baraddr)(pi->pi_vmctx, pi, idx, registration,
567                                           pi->pi_bar[idx].addr);
568                 break;
569         case PCIBAR_MEM32:
570         case PCIBAR_MEM64:
571                 bzero(&mr, sizeof(struct mem_range));
572                 mr.name = pi->pi_name;
573                 mr.base = pi->pi_bar[idx].addr;
574                 mr.size = pi->pi_bar[idx].size;
575                 if (registration) {
576                         mr.flags = MEM_F_RW;
577                         mr.handler = pci_emul_mem_handler;
578                         mr.arg1 = pi;
579                         mr.arg2 = idx;
580                         error = register_mem(&mr);
581                 } else
582                         error = unregister_mem(&mr);
583                 if (pe->pe_baraddr != NULL)
584                         (*pe->pe_baraddr)(pi->pi_vmctx, pi, idx, registration,
585                                           pi->pi_bar[idx].addr);
586                 break;
587         case PCIBAR_ROM:
588                 error = 0;
589                 if (pe->pe_baraddr != NULL)
590                         (*pe->pe_baraddr)(pi->pi_vmctx, pi, idx, registration,
591                             pi->pi_bar[idx].addr);
592                 break;
593         default:
594                 error = EINVAL;
595                 break;
596         }
597         assert(error == 0);
598 }
599
600 static void
601 unregister_bar(struct pci_devinst *pi, int idx)
602 {
603
604         modify_bar_registration(pi, idx, 0);
605 }
606
607 static void
608 register_bar(struct pci_devinst *pi, int idx)
609 {
610
611         modify_bar_registration(pi, idx, 1);
612 }
613
614 /* Is the ROM enabled for the emulated pci device? */
615 static int
616 romen(struct pci_devinst *pi)
617 {
618         return (pi->pi_bar[PCI_ROM_IDX].lobits & PCIM_BIOS_ENABLE) ==
619             PCIM_BIOS_ENABLE;
620 }
621
622 /* Are we decoding i/o port accesses for the emulated pci device? */
623 static int
624 porten(struct pci_devinst *pi)
625 {
626         uint16_t cmd;
627
628         cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
629
630         return (cmd & PCIM_CMD_PORTEN);
631 }
632
633 /* Are we decoding memory accesses for the emulated pci device? */
634 static int
635 memen(struct pci_devinst *pi)
636 {
637         uint16_t cmd;
638
639         cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
640
641         return (cmd & PCIM_CMD_MEMEN);
642 }
643
644 /*
645  * Update the MMIO or I/O address that is decoded by the BAR register.
646  *
647  * If the pci device has enabled the address space decoding then intercept
648  * the address range decoded by the BAR register.
649  */
650 static void
651 update_bar_address(struct pci_devinst *pi, uint64_t addr, int idx, int type)
652 {
653         int decode;
654
655         if (pi->pi_bar[idx].type == PCIBAR_IO)
656                 decode = porten(pi);
657         else
658                 decode = memen(pi);
659
660         if (decode)
661                 unregister_bar(pi, idx);
662
663         switch (type) {
664         case PCIBAR_IO:
665         case PCIBAR_MEM32:
666                 pi->pi_bar[idx].addr = addr;
667                 break;
668         case PCIBAR_MEM64:
669                 pi->pi_bar[idx].addr &= ~0xffffffffUL;
670                 pi->pi_bar[idx].addr |= addr;
671                 break;
672         case PCIBAR_MEMHI64:
673                 pi->pi_bar[idx].addr &= 0xffffffff;
674                 pi->pi_bar[idx].addr |= addr;
675                 break;
676         default:
677                 assert(0);
678         }
679
680         if (decode)
681                 register_bar(pi, idx);
682 }
683
684 int
685 pci_emul_alloc_bar(struct pci_devinst *pdi, int idx, enum pcibar_type type,
686     uint64_t size)
687 {
688         assert((type == PCIBAR_ROM) || (idx >= 0 && idx <= PCI_BARMAX));
689         assert((type != PCIBAR_ROM) || (idx == PCI_ROM_IDX));
690
691         if ((size & (size - 1)) != 0)
692                 size = 1UL << flsl(size);       /* round up to a power of 2 */
693
694         /* Enforce minimum BAR sizes required by the PCI standard */
695         if (type == PCIBAR_IO) {
696                 if (size < 4)
697                         size = 4;
698         } else if (type == PCIBAR_ROM) {
699                 if (size < ~PCIM_BIOS_ADDR_MASK + 1)
700                         size = ~PCIM_BIOS_ADDR_MASK + 1;
701         } else {
702                 if (size < 16)
703                         size = 16;
704         }
705
706         /*
707          * To reduce fragmentation of the MMIO space, we allocate the BARs by
708          * size. Therefore, don't allocate the BAR yet. We create a list of all
709          * BAR allocation which is sorted by BAR size. When all PCI devices are
710          * initialized, we will assign an address to the BARs.
711          */
712
713         /* create a new list entry */
714         struct pci_bar_allocation *const new_bar = malloc(sizeof(*new_bar));
715         memset(new_bar, 0, sizeof(*new_bar));
716         new_bar->pdi = pdi;
717         new_bar->idx = idx;
718         new_bar->type = type;
719         new_bar->size = size;
720
721         /*
722          * Search for a BAR which size is lower than the size of our newly
723          * allocated BAR.
724          */
725         struct pci_bar_allocation *bar = NULL;
726         TAILQ_FOREACH(bar, &pci_bars, chain) {
727                 if (bar->size < size) {
728                         break;
729                 }
730         }
731
732         if (bar == NULL) {
733                 /*
734                  * Either the list is empty or new BAR is the smallest BAR of
735                  * the list. Append it to the end of our list.
736                  */
737                 TAILQ_INSERT_TAIL(&pci_bars, new_bar, chain);
738         } else {
739                 /*
740                  * The found BAR is smaller than our new BAR. For that reason,
741                  * insert our new BAR before the found BAR.
742                  */
743                 TAILQ_INSERT_BEFORE(bar, new_bar, chain);
744         }
745
746         /*
747          * pci_passthru devices synchronize their physical and virtual command
748          * register on init. For that reason, the virtual cmd reg should be
749          * updated as early as possible.
750          */
751         uint16_t enbit = 0;
752         switch (type) {
753         case PCIBAR_IO:
754                 enbit = PCIM_CMD_PORTEN;
755                 break;
756         case PCIBAR_MEM64:
757         case PCIBAR_MEM32:
758                 enbit = PCIM_CMD_MEMEN;
759                 break;
760         default:
761                 enbit = 0;
762                 break;
763         }
764
765         const uint16_t cmd = pci_get_cfgdata16(pdi, PCIR_COMMAND);
766         pci_set_cfgdata16(pdi, PCIR_COMMAND, cmd | enbit);
767
768         return (0);
769 }
770
771 static int
772 pci_emul_assign_bar(struct pci_devinst *const pdi, const int idx,
773     const enum pcibar_type type, const uint64_t size)
774 {
775         int error;
776         uint64_t *baseptr, limit, addr, mask, lobits, bar;
777
778         switch (type) {
779         case PCIBAR_NONE:
780                 baseptr = NULL;
781                 addr = mask = lobits = 0;
782                 break;
783         case PCIBAR_IO:
784                 baseptr = &pci_emul_iobase;
785                 limit = PCI_EMUL_IOLIMIT;
786                 mask = PCIM_BAR_IO_BASE;
787                 lobits = PCIM_BAR_IO_SPACE;
788                 break;
789         case PCIBAR_MEM64:
790                 /*
791                  * XXX
792                  * Some drivers do not work well if the 64-bit BAR is allocated
793                  * above 4GB. Allow for this by allocating small requests under
794                  * 4GB unless then allocation size is larger than some arbitrary
795                  * number (128MB currently).
796                  */
797                 if (size > 128 * 1024 * 1024) {
798                         baseptr = &pci_emul_membase64;
799                         limit = pci_emul_memlim64;
800                         mask = PCIM_BAR_MEM_BASE;
801                         lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
802                                  PCIM_BAR_MEM_PREFETCH;
803                 } else {
804                         baseptr = &pci_emul_membase32;
805                         limit = PCI_EMUL_MEMLIMIT32;
806                         mask = PCIM_BAR_MEM_BASE;
807                         lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64;
808                 }
809                 break;
810         case PCIBAR_MEM32:
811                 baseptr = &pci_emul_membase32;
812                 limit = PCI_EMUL_MEMLIMIT32;
813                 mask = PCIM_BAR_MEM_BASE;
814                 lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
815                 break;
816         case PCIBAR_ROM:
817                 /* do not claim memory for ROM. OVMF will do it for us. */
818                 baseptr = NULL;
819                 limit = 0;
820                 mask = PCIM_BIOS_ADDR_MASK;
821                 lobits = 0;
822                 break;
823         default:
824                 printf("pci_emul_alloc_base: invalid bar type %d\n", type);
825                 assert(0);
826         }
827
828         if (baseptr != NULL) {
829                 error = pci_emul_alloc_resource(baseptr, limit, size, &addr);
830                 if (error != 0)
831                         return (error);
832         } else {
833                 addr = 0;
834         }
835
836         pdi->pi_bar[idx].type = type;
837         pdi->pi_bar[idx].addr = addr;
838         pdi->pi_bar[idx].size = size;
839         /*
840          * passthru devices are using same lobits as physical device they set
841          * this property
842          */
843         if (pdi->pi_bar[idx].lobits != 0) {
844                 lobits = pdi->pi_bar[idx].lobits;
845         } else {
846                 pdi->pi_bar[idx].lobits = lobits;
847         }
848
849         /* Initialize the BAR register in config space */
850         bar = (addr & mask) | lobits;
851         pci_set_cfgdata32(pdi, PCIR_BAR(idx), bar);
852
853         if (type == PCIBAR_MEM64) {
854                 assert(idx + 1 <= PCI_BARMAX);
855                 pdi->pi_bar[idx + 1].type = PCIBAR_MEMHI64;
856                 pci_set_cfgdata32(pdi, PCIR_BAR(idx + 1), bar >> 32);
857         }
858
859         if (type != PCIBAR_ROM) {
860                 register_bar(pdi, idx);
861         }
862
863         return (0);
864 }
865
866 int
867 pci_emul_alloc_rom(struct pci_devinst *const pdi, const uint64_t size,
868     void **const addr)
869 {
870         /* allocate ROM space once on first call */
871         if (pci_emul_rombase == 0) {
872                 pci_emul_rombase = vm_create_devmem(pdi->pi_vmctx, VM_PCIROM,
873                     "pcirom", PCI_EMUL_ROMSIZE);
874                 if (pci_emul_rombase == MAP_FAILED) {
875                         warnx("%s: failed to create rom segment", __func__);
876                         return (-1);
877                 }
878                 pci_emul_romlim = pci_emul_rombase + PCI_EMUL_ROMSIZE;
879                 pci_emul_romoffset = 0;
880         }
881
882         /* ROM size should be a power of 2 and greater than 2 KB */
883         const uint64_t rom_size = MAX(1UL << flsl(size),
884             ~PCIM_BIOS_ADDR_MASK + 1);
885
886         /* check if ROM fits into ROM space */
887         if (pci_emul_romoffset + rom_size > PCI_EMUL_ROMSIZE) {
888                 warnx("%s: no space left in rom segment:", __func__);
889                 warnx("%16lu bytes left",
890                     PCI_EMUL_ROMSIZE - pci_emul_romoffset);
891                 warnx("%16lu bytes required by %d/%d/%d", rom_size, pdi->pi_bus,
892                     pdi->pi_slot, pdi->pi_func);
893                 return (-1);
894         }
895
896         /* allocate ROM BAR */
897         const int error = pci_emul_alloc_bar(pdi, PCI_ROM_IDX, PCIBAR_ROM,
898             rom_size);
899         if (error)
900                 return error;
901
902         /* return address */
903         *addr = pci_emul_rombase + pci_emul_romoffset;
904
905         /* save offset into ROM Space */
906         pdi->pi_romoffset = pci_emul_romoffset;
907
908         /* increase offset for next ROM */
909         pci_emul_romoffset += rom_size;
910
911         return (0);
912 }
913
914 #define CAP_START_OFFSET        0x40
915 static int
916 pci_emul_add_capability(struct pci_devinst *pi, u_char *capdata, int caplen)
917 {
918         int i, capoff, reallen;
919         uint16_t sts;
920
921         assert(caplen > 0);
922
923         reallen = roundup2(caplen, 4);          /* dword aligned */
924
925         sts = pci_get_cfgdata16(pi, PCIR_STATUS);
926         if ((sts & PCIM_STATUS_CAPPRESENT) == 0)
927                 capoff = CAP_START_OFFSET;
928         else
929                 capoff = pi->pi_capend + 1;
930
931         /* Check if we have enough space */
932         if (capoff + reallen > PCI_REGMAX + 1)
933                 return (-1);
934
935         /* Set the previous capability pointer */
936         if ((sts & PCIM_STATUS_CAPPRESENT) == 0) {
937                 pci_set_cfgdata8(pi, PCIR_CAP_PTR, capoff);
938                 pci_set_cfgdata16(pi, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT);
939         } else
940                 pci_set_cfgdata8(pi, pi->pi_prevcap + 1, capoff);
941
942         /* Copy the capability */
943         for (i = 0; i < caplen; i++)
944                 pci_set_cfgdata8(pi, capoff + i, capdata[i]);
945
946         /* Set the next capability pointer */
947         pci_set_cfgdata8(pi, capoff + 1, 0);
948
949         pi->pi_prevcap = capoff;
950         pi->pi_capend = capoff + reallen - 1;
951         return (0);
952 }
953
954 static struct pci_devemu *
955 pci_emul_finddev(const char *name)
956 {
957         struct pci_devemu **pdpp, *pdp;
958
959         SET_FOREACH(pdpp, pci_devemu_set) {
960                 pdp = *pdpp;
961                 if (!strcmp(pdp->pe_emu, name)) {
962                         return (pdp);
963                 }
964         }
965
966         return (NULL);
967 }
968
969 static int
970 pci_emul_init(struct vmctx *ctx, struct pci_devemu *pde, int bus, int slot,
971     int func, struct funcinfo *fi)
972 {
973         struct pci_devinst *pdi;
974         int err;
975
976         pdi = calloc(1, sizeof(struct pci_devinst));
977
978         pdi->pi_vmctx = ctx;
979         pdi->pi_bus = bus;
980         pdi->pi_slot = slot;
981         pdi->pi_func = func;
982         pthread_mutex_init(&pdi->pi_lintr.lock, NULL);
983         pdi->pi_lintr.pin = 0;
984         pdi->pi_lintr.state = IDLE;
985         pdi->pi_lintr.pirq_pin = 0;
986         pdi->pi_lintr.ioapic_irq = 0;
987         pdi->pi_d = pde;
988         snprintf(pdi->pi_name, PI_NAMESZ, "%s-pci-%d", pde->pe_emu, slot);
989
990         /* Disable legacy interrupts */
991         pci_set_cfgdata8(pdi, PCIR_INTLINE, 255);
992         pci_set_cfgdata8(pdi, PCIR_INTPIN, 0);
993
994         pci_set_cfgdata8(pdi, PCIR_COMMAND, PCIM_CMD_BUSMASTEREN);
995
996         err = (*pde->pe_init)(ctx, pdi, fi->fi_config);
997         if (err == 0)
998                 fi->fi_devi = pdi;
999         else
1000                 free(pdi);
1001
1002         return (err);
1003 }
1004
1005 void
1006 pci_populate_msicap(struct msicap *msicap, int msgnum, int nextptr)
1007 {
1008         int mmc;
1009
1010         /* Number of msi messages must be a power of 2 between 1 and 32 */
1011         assert((msgnum & (msgnum - 1)) == 0 && msgnum >= 1 && msgnum <= 32);
1012         mmc = ffs(msgnum) - 1;
1013
1014         bzero(msicap, sizeof(struct msicap));
1015         msicap->capid = PCIY_MSI;
1016         msicap->nextptr = nextptr;
1017         msicap->msgctrl = PCIM_MSICTRL_64BIT | (mmc << 1);
1018 }
1019
1020 int
1021 pci_emul_add_msicap(struct pci_devinst *pi, int msgnum)
1022 {
1023         struct msicap msicap;
1024
1025         pci_populate_msicap(&msicap, msgnum, 0);
1026
1027         return (pci_emul_add_capability(pi, (u_char *)&msicap, sizeof(msicap)));
1028 }
1029
1030 static void
1031 pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,
1032                      uint32_t msix_tab_size)
1033 {
1034
1035         assert(msix_tab_size % 4096 == 0);
1036
1037         bzero(msixcap, sizeof(struct msixcap));
1038         msixcap->capid = PCIY_MSIX;
1039
1040         /*
1041          * Message Control Register, all fields set to
1042          * zero except for the Table Size.
1043          * Note: Table size N is encoded as N-1
1044          */
1045         msixcap->msgctrl = msgnum - 1;
1046
1047         /*
1048          * MSI-X BAR setup:
1049          * - MSI-X table start at offset 0
1050          * - PBA table starts at a 4K aligned offset after the MSI-X table
1051          */
1052         msixcap->table_info = barnum & PCIM_MSIX_BIR_MASK;
1053         msixcap->pba_info = msix_tab_size | (barnum & PCIM_MSIX_BIR_MASK);
1054 }
1055
1056 static void
1057 pci_msix_table_init(struct pci_devinst *pi, int table_entries)
1058 {
1059         int i, table_size;
1060
1061         assert(table_entries > 0);
1062         assert(table_entries <= MAX_MSIX_TABLE_ENTRIES);
1063
1064         table_size = table_entries * MSIX_TABLE_ENTRY_SIZE;
1065         pi->pi_msix.table = calloc(1, table_size);
1066
1067         /* set mask bit of vector control register */
1068         for (i = 0; i < table_entries; i++)
1069                 pi->pi_msix.table[i].vector_control |= PCIM_MSIX_VCTRL_MASK;
1070 }
1071
1072 int
1073 pci_emul_add_msixcap(struct pci_devinst *pi, int msgnum, int barnum)
1074 {
1075         uint32_t tab_size;
1076         struct msixcap msixcap;
1077
1078         assert(msgnum >= 1 && msgnum <= MAX_MSIX_TABLE_ENTRIES);
1079         assert(barnum >= 0 && barnum <= PCIR_MAX_BAR_0);
1080
1081         tab_size = msgnum * MSIX_TABLE_ENTRY_SIZE;
1082
1083         /* Align table size to nearest 4K */
1084         tab_size = roundup2(tab_size, 4096);
1085
1086         pi->pi_msix.table_bar = barnum;
1087         pi->pi_msix.pba_bar   = barnum;
1088         pi->pi_msix.table_offset = 0;
1089         pi->pi_msix.table_count = msgnum;
1090         pi->pi_msix.pba_offset = tab_size;
1091         pi->pi_msix.pba_size = PBA_SIZE(msgnum);
1092
1093         pci_msix_table_init(pi, msgnum);
1094
1095         pci_populate_msixcap(&msixcap, msgnum, barnum, tab_size);
1096
1097         /* allocate memory for MSI-X Table and PBA */
1098         pci_emul_alloc_bar(pi, barnum, PCIBAR_MEM32,
1099                                 tab_size + pi->pi_msix.pba_size);
1100
1101         return (pci_emul_add_capability(pi, (u_char *)&msixcap,
1102                                         sizeof(msixcap)));
1103 }
1104
1105 static void
1106 msixcap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
1107                  int bytes, uint32_t val)
1108 {
1109         uint16_t msgctrl, rwmask;
1110         int off;
1111
1112         off = offset - capoff;
1113         /* Message Control Register */
1114         if (off == 2 && bytes == 2) {
1115                 rwmask = PCIM_MSIXCTRL_MSIX_ENABLE | PCIM_MSIXCTRL_FUNCTION_MASK;
1116                 msgctrl = pci_get_cfgdata16(pi, offset);
1117                 msgctrl &= ~rwmask;
1118                 msgctrl |= val & rwmask;
1119                 val = msgctrl;
1120
1121                 pi->pi_msix.enabled = val & PCIM_MSIXCTRL_MSIX_ENABLE;
1122                 pi->pi_msix.function_mask = val & PCIM_MSIXCTRL_FUNCTION_MASK;
1123                 pci_lintr_update(pi);
1124         }
1125
1126         CFGWRITE(pi, offset, val, bytes);
1127 }
1128
1129 static void
1130 msicap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
1131                 int bytes, uint32_t val)
1132 {
1133         uint16_t msgctrl, rwmask, msgdata, mme;
1134         uint32_t addrlo;
1135
1136         /*
1137          * If guest is writing to the message control register make sure
1138          * we do not overwrite read-only fields.
1139          */
1140         if ((offset - capoff) == 2 && bytes == 2) {
1141                 rwmask = PCIM_MSICTRL_MME_MASK | PCIM_MSICTRL_MSI_ENABLE;
1142                 msgctrl = pci_get_cfgdata16(pi, offset);
1143                 msgctrl &= ~rwmask;
1144                 msgctrl |= val & rwmask;
1145                 val = msgctrl;
1146         }
1147         CFGWRITE(pi, offset, val, bytes);
1148
1149         msgctrl = pci_get_cfgdata16(pi, capoff + 2);
1150         addrlo = pci_get_cfgdata32(pi, capoff + 4);
1151         if (msgctrl & PCIM_MSICTRL_64BIT)
1152                 msgdata = pci_get_cfgdata16(pi, capoff + 12);
1153         else
1154                 msgdata = pci_get_cfgdata16(pi, capoff + 8);
1155
1156         mme = msgctrl & PCIM_MSICTRL_MME_MASK;
1157         pi->pi_msi.enabled = msgctrl & PCIM_MSICTRL_MSI_ENABLE ? 1 : 0;
1158         if (pi->pi_msi.enabled) {
1159                 pi->pi_msi.addr = addrlo;
1160                 pi->pi_msi.msg_data = msgdata;
1161                 pi->pi_msi.maxmsgnum = 1 << (mme >> 4);
1162         } else {
1163                 pi->pi_msi.maxmsgnum = 0;
1164         }
1165         pci_lintr_update(pi);
1166 }
1167
1168 static void
1169 pciecap_cfgwrite(struct pci_devinst *pi, int capoff __unused, int offset,
1170     int bytes, uint32_t val)
1171 {
1172
1173         /* XXX don't write to the readonly parts */
1174         CFGWRITE(pi, offset, val, bytes);
1175 }
1176
1177 #define PCIECAP_VERSION 0x2
1178 int
1179 pci_emul_add_pciecap(struct pci_devinst *pi, int type)
1180 {
1181         int err;
1182         struct pciecap pciecap;
1183
1184         bzero(&pciecap, sizeof(pciecap));
1185
1186         /*
1187          * Use the integrated endpoint type for endpoints on a root complex bus.
1188          *
1189          * NB: bhyve currently only supports a single PCI bus that is the root
1190          * complex bus, so all endpoints are integrated.
1191          */
1192         if ((type == PCIEM_TYPE_ENDPOINT) && (pi->pi_bus == 0))
1193                 type = PCIEM_TYPE_ROOT_INT_EP;
1194
1195         pciecap.capid = PCIY_EXPRESS;
1196         pciecap.pcie_capabilities = PCIECAP_VERSION | type;
1197         if (type != PCIEM_TYPE_ROOT_INT_EP) {
1198                 pciecap.link_capabilities = 0x411;      /* gen1, x1 */
1199                 pciecap.link_status = 0x11;             /* gen1, x1 */
1200         }
1201
1202         err = pci_emul_add_capability(pi, (u_char *)&pciecap, sizeof(pciecap));
1203         return (err);
1204 }
1205
1206 /*
1207  * This function assumes that 'coff' is in the capabilities region of the
1208  * config space. A capoff parameter of zero will force a search for the
1209  * offset and type.
1210  */
1211 void
1212 pci_emul_capwrite(struct pci_devinst *pi, int offset, int bytes, uint32_t val,
1213     uint8_t capoff, int capid)
1214 {
1215         uint8_t nextoff;
1216
1217         /* Do not allow un-aligned writes */
1218         if ((offset & (bytes - 1)) != 0)
1219                 return;
1220
1221         if (capoff == 0) {
1222                 /* Find the capability that we want to update */
1223                 capoff = CAP_START_OFFSET;
1224                 while (1) {
1225                         nextoff = pci_get_cfgdata8(pi, capoff + 1);
1226                         if (nextoff == 0)
1227                                 break;
1228                         if (offset >= capoff && offset < nextoff)
1229                                 break;
1230
1231                         capoff = nextoff;
1232                 }
1233                 assert(offset >= capoff);
1234                 capid = pci_get_cfgdata8(pi, capoff);
1235         }
1236
1237         /*
1238          * Capability ID and Next Capability Pointer are readonly.
1239          * However, some o/s's do 4-byte writes that include these.
1240          * For this case, trim the write back to 2 bytes and adjust
1241          * the data.
1242          */
1243         if (offset == capoff || offset == capoff + 1) {
1244                 if (offset == capoff && bytes == 4) {
1245                         bytes = 2;
1246                         offset += 2;
1247                         val >>= 16;
1248                 } else
1249                         return;
1250         }
1251
1252         switch (capid) {
1253         case PCIY_MSI:
1254                 msicap_cfgwrite(pi, capoff, offset, bytes, val);
1255                 break;
1256         case PCIY_MSIX:
1257                 msixcap_cfgwrite(pi, capoff, offset, bytes, val);
1258                 break;
1259         case PCIY_EXPRESS:
1260                 pciecap_cfgwrite(pi, capoff, offset, bytes, val);
1261                 break;
1262         default:
1263                 break;
1264         }
1265 }
1266
1267 static int
1268 pci_emul_iscap(struct pci_devinst *pi, int offset)
1269 {
1270         uint16_t sts;
1271
1272         sts = pci_get_cfgdata16(pi, PCIR_STATUS);
1273         if ((sts & PCIM_STATUS_CAPPRESENT) != 0) {
1274                 if (offset >= CAP_START_OFFSET && offset <= pi->pi_capend)
1275                         return (1);
1276         }
1277         return (0);
1278 }
1279
1280 static int
1281 pci_emul_fallback_handler(struct vmctx *ctx __unused, int vcpu __unused,
1282     int dir, uint64_t addr __unused, int size __unused, uint64_t *val,
1283     void *arg1 __unused, long arg2 __unused)
1284 {
1285         /*
1286          * Ignore writes; return 0xff's for reads. The mem read code
1287          * will take care of truncating to the correct size.
1288          */
1289         if (dir == MEM_F_READ) {
1290                 *val = 0xffffffffffffffff;
1291         }
1292
1293         return (0);
1294 }
1295
1296 static int
1297 pci_emul_ecfg_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
1298     int bytes, uint64_t *val, void *arg1 __unused, long arg2 __unused)
1299 {
1300         int bus, slot, func, coff, in;
1301
1302         coff = addr & 0xfff;
1303         func = (addr >> 12) & 0x7;
1304         slot = (addr >> 15) & 0x1f;
1305         bus = (addr >> 20) & 0xff;
1306         in = (dir == MEM_F_READ);
1307         if (in)
1308                 *val = ~0UL;
1309         pci_cfgrw(ctx, vcpu, in, bus, slot, func, coff, bytes, (uint32_t *)val);
1310         return (0);
1311 }
1312
1313 uint64_t
1314 pci_ecfg_base(void)
1315 {
1316
1317         return (PCI_EMUL_ECFG_BASE);
1318 }
1319
1320 #define BUSIO_ROUNDUP           32
1321 #define BUSMEM32_ROUNDUP        (1024 * 1024)
1322 #define BUSMEM64_ROUNDUP        (512 * 1024 * 1024)
1323
1324 int
1325 init_pci(struct vmctx *ctx)
1326 {
1327         char node_name[sizeof("pci.XXX.XX.X")];
1328         struct mem_range mr;
1329         struct pci_devemu *pde;
1330         struct businfo *bi;
1331         struct slotinfo *si;
1332         struct funcinfo *fi;
1333         nvlist_t *nvl;
1334         const char *emul;
1335         size_t lowmem;
1336         int bus, slot, func;
1337         int error;
1338
1339         if (vm_get_lowmem_limit(ctx) > PCI_EMUL_MEMBASE32)
1340                 errx(EX_OSERR, "Invalid lowmem limit");
1341
1342         pci_emul_iobase = PCI_EMUL_IOBASE;
1343         pci_emul_membase32 = PCI_EMUL_MEMBASE32;
1344
1345         pci_emul_membase64 = 4*GB + vm_get_highmem_size(ctx);
1346         pci_emul_membase64 = roundup2(pci_emul_membase64, PCI_EMUL_MEMSIZE64);
1347         pci_emul_memlim64 = pci_emul_membase64 + PCI_EMUL_MEMSIZE64;
1348
1349         for (bus = 0; bus < MAXBUSES; bus++) {
1350                 snprintf(node_name, sizeof(node_name), "pci.%d", bus);
1351                 nvl = find_config_node(node_name);
1352                 if (nvl == NULL)
1353                         continue;
1354                 pci_businfo[bus] = calloc(1, sizeof(struct businfo));
1355                 bi = pci_businfo[bus];
1356
1357                 /*
1358                  * Keep track of the i/o and memory resources allocated to
1359                  * this bus.
1360                  */
1361                 bi->iobase = pci_emul_iobase;
1362                 bi->membase32 = pci_emul_membase32;
1363                 bi->membase64 = pci_emul_membase64;
1364
1365                 /* first run: init devices */
1366                 for (slot = 0; slot < MAXSLOTS; slot++) {
1367                         si = &bi->slotinfo[slot];
1368                         for (func = 0; func < MAXFUNCS; func++) {
1369                                 fi = &si->si_funcs[func];
1370                                 snprintf(node_name, sizeof(node_name),
1371                                     "pci.%d.%d.%d", bus, slot, func);
1372                                 nvl = find_config_node(node_name);
1373                                 if (nvl == NULL)
1374                                         continue;
1375
1376                                 fi->fi_config = nvl;
1377                                 emul = get_config_value_node(nvl, "device");
1378                                 if (emul == NULL) {
1379                                         EPRINTLN("pci slot %d:%d:%d: missing "
1380                                             "\"device\" value", bus, slot, func);
1381                                         return (EINVAL);
1382                                 }
1383                                 pde = pci_emul_finddev(emul);
1384                                 if (pde == NULL) {
1385                                         EPRINTLN("pci slot %d:%d:%d: unknown "
1386                                             "device \"%s\"", bus, slot, func,
1387                                             emul);
1388                                         return (EINVAL);
1389                                 }
1390                                 if (pde->pe_alias != NULL) {
1391                                         EPRINTLN("pci slot %d:%d:%d: legacy "
1392                                             "device \"%s\", use \"%s\" instead",
1393                                             bus, slot, func, emul,
1394                                             pde->pe_alias);
1395                                         return (EINVAL);
1396                                 }
1397                                 fi->fi_pde = pde;
1398                                 error = pci_emul_init(ctx, pde, bus, slot,
1399                                     func, fi);
1400                                 if (error)
1401                                         return (error);
1402                         }
1403                 }
1404
1405                 /* second run: assign BARs and free list */
1406                 struct pci_bar_allocation *bar;
1407                 struct pci_bar_allocation *bar_tmp;
1408                 TAILQ_FOREACH_SAFE(bar, &pci_bars, chain, bar_tmp) {
1409                         pci_emul_assign_bar(bar->pdi, bar->idx, bar->type,
1410                             bar->size);
1411                         free(bar);
1412                 }
1413                 TAILQ_INIT(&pci_bars);
1414
1415                 /*
1416                  * Add some slop to the I/O and memory resources decoded by
1417                  * this bus to give a guest some flexibility if it wants to
1418                  * reprogram the BARs.
1419                  */
1420                 pci_emul_iobase += BUSIO_ROUNDUP;
1421                 pci_emul_iobase = roundup2(pci_emul_iobase, BUSIO_ROUNDUP);
1422                 bi->iolimit = pci_emul_iobase;
1423
1424                 pci_emul_membase32 += BUSMEM32_ROUNDUP;
1425                 pci_emul_membase32 = roundup2(pci_emul_membase32,
1426                     BUSMEM32_ROUNDUP);
1427                 bi->memlimit32 = pci_emul_membase32;
1428
1429                 pci_emul_membase64 += BUSMEM64_ROUNDUP;
1430                 pci_emul_membase64 = roundup2(pci_emul_membase64,
1431                     BUSMEM64_ROUNDUP);
1432                 bi->memlimit64 = pci_emul_membase64;
1433         }
1434
1435         /*
1436          * PCI backends are initialized before routing INTx interrupts
1437          * so that LPC devices are able to reserve ISA IRQs before
1438          * routing PIRQ pins.
1439          */
1440         for (bus = 0; bus < MAXBUSES; bus++) {
1441                 if ((bi = pci_businfo[bus]) == NULL)
1442                         continue;
1443
1444                 for (slot = 0; slot < MAXSLOTS; slot++) {
1445                         si = &bi->slotinfo[slot];
1446                         for (func = 0; func < MAXFUNCS; func++) {
1447                                 fi = &si->si_funcs[func];
1448                                 if (fi->fi_devi == NULL)
1449                                         continue;
1450                                 pci_lintr_route(fi->fi_devi);
1451                         }
1452                 }
1453         }
1454         lpc_pirq_routed();
1455
1456         /*
1457          * The guest physical memory map looks like the following:
1458          * [0,              lowmem)             guest system memory
1459          * [lowmem,         0xC0000000)         memory hole (may be absent)
1460          * [0xC0000000,     0xE0000000)         PCI hole (32-bit BAR allocation)
1461          * [0xE0000000,     0xF0000000)         PCI extended config window
1462          * [0xF0000000,     4GB)                LAPIC, IOAPIC, HPET, firmware
1463          * [4GB,            4GB + highmem)
1464          */
1465
1466         /*
1467          * Accesses to memory addresses that are not allocated to system
1468          * memory or PCI devices return 0xff's.
1469          */
1470         lowmem = vm_get_lowmem_size(ctx);
1471         bzero(&mr, sizeof(struct mem_range));
1472         mr.name = "PCI hole";
1473         mr.flags = MEM_F_RW | MEM_F_IMMUTABLE;
1474         mr.base = lowmem;
1475         mr.size = (4ULL * 1024 * 1024 * 1024) - lowmem;
1476         mr.handler = pci_emul_fallback_handler;
1477         error = register_mem_fallback(&mr);
1478         assert(error == 0);
1479
1480         /* PCI extended config space */
1481         bzero(&mr, sizeof(struct mem_range));
1482         mr.name = "PCI ECFG";
1483         mr.flags = MEM_F_RW | MEM_F_IMMUTABLE;
1484         mr.base = PCI_EMUL_ECFG_BASE;
1485         mr.size = PCI_EMUL_ECFG_SIZE;
1486         mr.handler = pci_emul_ecfg_handler;
1487         error = register_mem(&mr);
1488         assert(error == 0);
1489
1490         return (0);
1491 }
1492
1493 static void
1494 pci_apic_prt_entry(int bus __unused, int slot, int pin, int pirq_pin __unused,
1495     int ioapic_irq, void *arg __unused)
1496 {
1497
1498         dsdt_line("  Package ()");
1499         dsdt_line("  {");
1500         dsdt_line("    0x%X,", slot << 16 | 0xffff);
1501         dsdt_line("    0x%02X,", pin - 1);
1502         dsdt_line("    Zero,");
1503         dsdt_line("    0x%X", ioapic_irq);
1504         dsdt_line("  },");
1505 }
1506
1507 static void
1508 pci_pirq_prt_entry(int bus __unused, int slot, int pin, int pirq_pin,
1509     int ioapic_irq __unused, void *arg __unused)
1510 {
1511         char *name;
1512
1513         name = lpc_pirq_name(pirq_pin);
1514         if (name == NULL)
1515                 return;
1516         dsdt_line("  Package ()");
1517         dsdt_line("  {");
1518         dsdt_line("    0x%X,", slot << 16 | 0xffff);
1519         dsdt_line("    0x%02X,", pin - 1);
1520         dsdt_line("    %s,", name);
1521         dsdt_line("    0x00");
1522         dsdt_line("  },");
1523         free(name);
1524 }
1525
1526 /*
1527  * A bhyve virtual machine has a flat PCI hierarchy with a root port
1528  * corresponding to each PCI bus.
1529  */
1530 static void
1531 pci_bus_write_dsdt(int bus)
1532 {
1533         struct businfo *bi;
1534         struct slotinfo *si;
1535         struct pci_devinst *pi;
1536         int count, func, slot;
1537
1538         /*
1539          * If there are no devices on this 'bus' then just return.
1540          */
1541         if ((bi = pci_businfo[bus]) == NULL) {
1542                 /*
1543                  * Bus 0 is special because it decodes the I/O ports used
1544                  * for PCI config space access even if there are no devices
1545                  * on it.
1546                  */
1547                 if (bus != 0)
1548                         return;
1549         }
1550
1551         dsdt_line("  Device (PC%02X)", bus);
1552         dsdt_line("  {");
1553         dsdt_line("    Name (_HID, EisaId (\"PNP0A03\"))");
1554
1555         dsdt_line("    Method (_BBN, 0, NotSerialized)");
1556         dsdt_line("    {");
1557         dsdt_line("        Return (0x%08X)", bus);
1558         dsdt_line("    }");
1559         dsdt_line("    Name (_CRS, ResourceTemplate ()");
1560         dsdt_line("    {");
1561         dsdt_line("      WordBusNumber (ResourceProducer, MinFixed, "
1562             "MaxFixed, PosDecode,");
1563         dsdt_line("        0x0000,             // Granularity");
1564         dsdt_line("        0x%04X,             // Range Minimum", bus);
1565         dsdt_line("        0x%04X,             // Range Maximum", bus);
1566         dsdt_line("        0x0000,             // Translation Offset");
1567         dsdt_line("        0x0001,             // Length");
1568         dsdt_line("        ,, )");
1569
1570         if (bus == 0) {
1571                 dsdt_indent(3);
1572                 dsdt_fixed_ioport(0xCF8, 8);
1573                 dsdt_unindent(3);
1574
1575                 dsdt_line("      WordIO (ResourceProducer, MinFixed, MaxFixed, "
1576                     "PosDecode, EntireRange,");
1577                 dsdt_line("        0x0000,             // Granularity");
1578                 dsdt_line("        0x0000,             // Range Minimum");
1579                 dsdt_line("        0x0CF7,             // Range Maximum");
1580                 dsdt_line("        0x0000,             // Translation Offset");
1581                 dsdt_line("        0x0CF8,             // Length");
1582                 dsdt_line("        ,, , TypeStatic)");
1583
1584                 dsdt_line("      WordIO (ResourceProducer, MinFixed, MaxFixed, "
1585                     "PosDecode, EntireRange,");
1586                 dsdt_line("        0x0000,             // Granularity");
1587                 dsdt_line("        0x0D00,             // Range Minimum");
1588                 dsdt_line("        0x%04X,             // Range Maximum",
1589                     PCI_EMUL_IOBASE - 1);
1590                 dsdt_line("        0x0000,             // Translation Offset");
1591                 dsdt_line("        0x%04X,             // Length",
1592                     PCI_EMUL_IOBASE - 0x0D00);
1593                 dsdt_line("        ,, , TypeStatic)");
1594
1595                 if (bi == NULL) {
1596                         dsdt_line("    })");
1597                         goto done;
1598                 }
1599         }
1600         assert(bi != NULL);
1601
1602         /* i/o window */
1603         dsdt_line("      WordIO (ResourceProducer, MinFixed, MaxFixed, "
1604             "PosDecode, EntireRange,");
1605         dsdt_line("        0x0000,             // Granularity");
1606         dsdt_line("        0x%04X,             // Range Minimum", bi->iobase);
1607         dsdt_line("        0x%04X,             // Range Maximum",
1608             bi->iolimit - 1);
1609         dsdt_line("        0x0000,             // Translation Offset");
1610         dsdt_line("        0x%04X,             // Length",
1611             bi->iolimit - bi->iobase);
1612         dsdt_line("        ,, , TypeStatic)");
1613
1614         /* mmio window (32-bit) */
1615         dsdt_line("      DWordMemory (ResourceProducer, PosDecode, "
1616             "MinFixed, MaxFixed, NonCacheable, ReadWrite,");
1617         dsdt_line("        0x00000000,         // Granularity");
1618         dsdt_line("        0x%08X,         // Range Minimum\n", bi->membase32);
1619         dsdt_line("        0x%08X,         // Range Maximum\n",
1620             bi->memlimit32 - 1);
1621         dsdt_line("        0x00000000,         // Translation Offset");
1622         dsdt_line("        0x%08X,         // Length\n",
1623             bi->memlimit32 - bi->membase32);
1624         dsdt_line("        ,, , AddressRangeMemory, TypeStatic)");
1625
1626         /* mmio window (64-bit) */
1627         dsdt_line("      QWordMemory (ResourceProducer, PosDecode, "
1628             "MinFixed, MaxFixed, NonCacheable, ReadWrite,");
1629         dsdt_line("        0x0000000000000000, // Granularity");
1630         dsdt_line("        0x%016lX, // Range Minimum\n", bi->membase64);
1631         dsdt_line("        0x%016lX, // Range Maximum\n",
1632             bi->memlimit64 - 1);
1633         dsdt_line("        0x0000000000000000, // Translation Offset");
1634         dsdt_line("        0x%016lX, // Length\n",
1635             bi->memlimit64 - bi->membase64);
1636         dsdt_line("        ,, , AddressRangeMemory, TypeStatic)");
1637         dsdt_line("    })");
1638
1639         count = pci_count_lintr(bus);
1640         if (count != 0) {
1641                 dsdt_indent(2);
1642                 dsdt_line("Name (PPRT, Package ()");
1643                 dsdt_line("{");
1644                 pci_walk_lintr(bus, pci_pirq_prt_entry, NULL);
1645                 dsdt_line("})");
1646                 dsdt_line("Name (APRT, Package ()");
1647                 dsdt_line("{");
1648                 pci_walk_lintr(bus, pci_apic_prt_entry, NULL);
1649                 dsdt_line("})");
1650                 dsdt_line("Method (_PRT, 0, NotSerialized)");
1651                 dsdt_line("{");
1652                 dsdt_line("  If (PICM)");
1653                 dsdt_line("  {");
1654                 dsdt_line("    Return (APRT)");
1655                 dsdt_line("  }");
1656                 dsdt_line("  Else");
1657                 dsdt_line("  {");
1658                 dsdt_line("    Return (PPRT)");
1659                 dsdt_line("  }");
1660                 dsdt_line("}");
1661                 dsdt_unindent(2);
1662         }
1663
1664         dsdt_indent(2);
1665         for (slot = 0; slot < MAXSLOTS; slot++) {
1666                 si = &bi->slotinfo[slot];
1667                 for (func = 0; func < MAXFUNCS; func++) {
1668                         pi = si->si_funcs[func].fi_devi;
1669                         if (pi != NULL && pi->pi_d->pe_write_dsdt != NULL)
1670                                 pi->pi_d->pe_write_dsdt(pi);
1671                 }
1672         }
1673         dsdt_unindent(2);
1674 done:
1675         dsdt_line("  }");
1676 }
1677
1678 void
1679 pci_write_dsdt(void)
1680 {
1681         int bus;
1682
1683         dsdt_indent(1);
1684         dsdt_line("Name (PICM, 0x00)");
1685         dsdt_line("Method (_PIC, 1, NotSerialized)");
1686         dsdt_line("{");
1687         dsdt_line("  Store (Arg0, PICM)");
1688         dsdt_line("}");
1689         dsdt_line("");
1690         dsdt_line("Scope (_SB)");
1691         dsdt_line("{");
1692         for (bus = 0; bus < MAXBUSES; bus++)
1693                 pci_bus_write_dsdt(bus);
1694         dsdt_line("}");
1695         dsdt_unindent(1);
1696 }
1697
1698 int
1699 pci_bus_configured(int bus)
1700 {
1701         assert(bus >= 0 && bus < MAXBUSES);
1702         return (pci_businfo[bus] != NULL);
1703 }
1704
1705 int
1706 pci_msi_enabled(struct pci_devinst *pi)
1707 {
1708         return (pi->pi_msi.enabled);
1709 }
1710
1711 int
1712 pci_msi_maxmsgnum(struct pci_devinst *pi)
1713 {
1714         if (pi->pi_msi.enabled)
1715                 return (pi->pi_msi.maxmsgnum);
1716         else
1717                 return (0);
1718 }
1719
1720 int
1721 pci_msix_enabled(struct pci_devinst *pi)
1722 {
1723
1724         return (pi->pi_msix.enabled && !pi->pi_msi.enabled);
1725 }
1726
1727 void
1728 pci_generate_msix(struct pci_devinst *pi, int index)
1729 {
1730         struct msix_table_entry *mte;
1731
1732         if (!pci_msix_enabled(pi))
1733                 return;
1734
1735         if (pi->pi_msix.function_mask)
1736                 return;
1737
1738         if (index >= pi->pi_msix.table_count)
1739                 return;
1740
1741         mte = &pi->pi_msix.table[index];
1742         if ((mte->vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
1743                 /* XXX Set PBA bit if interrupt is disabled */
1744                 vm_lapic_msi(pi->pi_vmctx, mte->addr, mte->msg_data);
1745         }
1746 }
1747
1748 void
1749 pci_generate_msi(struct pci_devinst *pi, int index)
1750 {
1751
1752         if (pci_msi_enabled(pi) && index < pci_msi_maxmsgnum(pi)) {
1753                 vm_lapic_msi(pi->pi_vmctx, pi->pi_msi.addr,
1754                              pi->pi_msi.msg_data + index);
1755         }
1756 }
1757
1758 static bool
1759 pci_lintr_permitted(struct pci_devinst *pi)
1760 {
1761         uint16_t cmd;
1762
1763         cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
1764         return (!(pi->pi_msi.enabled || pi->pi_msix.enabled ||
1765                 (cmd & PCIM_CMD_INTxDIS)));
1766 }
1767
1768 void
1769 pci_lintr_request(struct pci_devinst *pi)
1770 {
1771         struct businfo *bi;
1772         struct slotinfo *si;
1773         int bestpin, bestcount, pin;
1774
1775         bi = pci_businfo[pi->pi_bus];
1776         assert(bi != NULL);
1777
1778         /*
1779          * Just allocate a pin from our slot.  The pin will be
1780          * assigned IRQs later when interrupts are routed.
1781          */
1782         si = &bi->slotinfo[pi->pi_slot];
1783         bestpin = 0;
1784         bestcount = si->si_intpins[0].ii_count;
1785         for (pin = 1; pin < 4; pin++) {
1786                 if (si->si_intpins[pin].ii_count < bestcount) {
1787                         bestpin = pin;
1788                         bestcount = si->si_intpins[pin].ii_count;
1789                 }
1790         }
1791
1792         si->si_intpins[bestpin].ii_count++;
1793         pi->pi_lintr.pin = bestpin + 1;
1794         pci_set_cfgdata8(pi, PCIR_INTPIN, bestpin + 1);
1795 }
1796
1797 static void
1798 pci_lintr_route(struct pci_devinst *pi)
1799 {
1800         struct businfo *bi;
1801         struct intxinfo *ii;
1802
1803         if (pi->pi_lintr.pin == 0)
1804                 return;
1805
1806         bi = pci_businfo[pi->pi_bus];
1807         assert(bi != NULL);
1808         ii = &bi->slotinfo[pi->pi_slot].si_intpins[pi->pi_lintr.pin - 1];
1809
1810         /*
1811          * Attempt to allocate an I/O APIC pin for this intpin if one
1812          * is not yet assigned.
1813          */
1814         if (ii->ii_ioapic_irq == 0)
1815                 ii->ii_ioapic_irq = ioapic_pci_alloc_irq(pi);
1816         assert(ii->ii_ioapic_irq > 0);
1817
1818         /*
1819          * Attempt to allocate a PIRQ pin for this intpin if one is
1820          * not yet assigned.
1821          */
1822         if (ii->ii_pirq_pin == 0)
1823                 ii->ii_pirq_pin = pirq_alloc_pin(pi);
1824         assert(ii->ii_pirq_pin > 0);
1825
1826         pi->pi_lintr.ioapic_irq = ii->ii_ioapic_irq;
1827         pi->pi_lintr.pirq_pin = ii->ii_pirq_pin;
1828         pci_set_cfgdata8(pi, PCIR_INTLINE, pirq_irq(ii->ii_pirq_pin));
1829 }
1830
1831 void
1832 pci_lintr_assert(struct pci_devinst *pi)
1833 {
1834
1835         assert(pi->pi_lintr.pin > 0);
1836
1837         pthread_mutex_lock(&pi->pi_lintr.lock);
1838         if (pi->pi_lintr.state == IDLE) {
1839                 if (pci_lintr_permitted(pi)) {
1840                         pi->pi_lintr.state = ASSERTED;
1841                         pci_irq_assert(pi);
1842                 } else
1843                         pi->pi_lintr.state = PENDING;
1844         }
1845         pthread_mutex_unlock(&pi->pi_lintr.lock);
1846 }
1847
1848 void
1849 pci_lintr_deassert(struct pci_devinst *pi)
1850 {
1851
1852         assert(pi->pi_lintr.pin > 0);
1853
1854         pthread_mutex_lock(&pi->pi_lintr.lock);
1855         if (pi->pi_lintr.state == ASSERTED) {
1856                 pi->pi_lintr.state = IDLE;
1857                 pci_irq_deassert(pi);
1858         } else if (pi->pi_lintr.state == PENDING)
1859                 pi->pi_lintr.state = IDLE;
1860         pthread_mutex_unlock(&pi->pi_lintr.lock);
1861 }
1862
1863 static void
1864 pci_lintr_update(struct pci_devinst *pi)
1865 {
1866
1867         pthread_mutex_lock(&pi->pi_lintr.lock);
1868         if (pi->pi_lintr.state == ASSERTED && !pci_lintr_permitted(pi)) {
1869                 pci_irq_deassert(pi);
1870                 pi->pi_lintr.state = PENDING;
1871         } else if (pi->pi_lintr.state == PENDING && pci_lintr_permitted(pi)) {
1872                 pi->pi_lintr.state = ASSERTED;
1873                 pci_irq_assert(pi);
1874         }
1875         pthread_mutex_unlock(&pi->pi_lintr.lock);
1876 }
1877
1878 int
1879 pci_count_lintr(int bus)
1880 {
1881         int count, slot, pin;
1882         struct slotinfo *slotinfo;
1883
1884         count = 0;
1885         if (pci_businfo[bus] != NULL) {
1886                 for (slot = 0; slot < MAXSLOTS; slot++) {
1887                         slotinfo = &pci_businfo[bus]->slotinfo[slot];
1888                         for (pin = 0; pin < 4; pin++) {
1889                                 if (slotinfo->si_intpins[pin].ii_count != 0)
1890                                         count++;
1891                         }
1892                 }
1893         }
1894         return (count);
1895 }
1896
1897 void
1898 pci_walk_lintr(int bus, pci_lintr_cb cb, void *arg)
1899 {
1900         struct businfo *bi;
1901         struct slotinfo *si;
1902         struct intxinfo *ii;
1903         int slot, pin;
1904
1905         if ((bi = pci_businfo[bus]) == NULL)
1906                 return;
1907
1908         for (slot = 0; slot < MAXSLOTS; slot++) {
1909                 si = &bi->slotinfo[slot];
1910                 for (pin = 0; pin < 4; pin++) {
1911                         ii = &si->si_intpins[pin];
1912                         if (ii->ii_count != 0)
1913                                 cb(bus, slot, pin + 1, ii->ii_pirq_pin,
1914                                     ii->ii_ioapic_irq, arg);
1915                 }
1916         }
1917 }
1918
1919 /*
1920  * Return 1 if the emulated device in 'slot' is a multi-function device.
1921  * Return 0 otherwise.
1922  */
1923 static int
1924 pci_emul_is_mfdev(int bus, int slot)
1925 {
1926         struct businfo *bi;
1927         struct slotinfo *si;
1928         int f, numfuncs;
1929
1930         numfuncs = 0;
1931         if ((bi = pci_businfo[bus]) != NULL) {
1932                 si = &bi->slotinfo[slot];
1933                 for (f = 0; f < MAXFUNCS; f++) {
1934                         if (si->si_funcs[f].fi_devi != NULL) {
1935                                 numfuncs++;
1936                         }
1937                 }
1938         }
1939         return (numfuncs > 1);
1940 }
1941
1942 /*
1943  * Ensure that the PCIM_MFDEV bit is properly set (or unset) depending on
1944  * whether or not is a multi-function being emulated in the pci 'slot'.
1945  */
1946 static void
1947 pci_emul_hdrtype_fixup(int bus, int slot, int off, int bytes, uint32_t *rv)
1948 {
1949         int mfdev;
1950
1951         if (off <= PCIR_HDRTYPE && off + bytes > PCIR_HDRTYPE) {
1952                 mfdev = pci_emul_is_mfdev(bus, slot);
1953                 switch (bytes) {
1954                 case 1:
1955                 case 2:
1956                         *rv &= ~PCIM_MFDEV;
1957                         if (mfdev) {
1958                                 *rv |= PCIM_MFDEV;
1959                         }
1960                         break;
1961                 case 4:
1962                         *rv &= ~(PCIM_MFDEV << 16);
1963                         if (mfdev) {
1964                                 *rv |= (PCIM_MFDEV << 16);
1965                         }
1966                         break;
1967                 }
1968         }
1969 }
1970
1971 /*
1972  * Update device state in response to changes to the PCI command
1973  * register.
1974  */
1975 void
1976 pci_emul_cmd_changed(struct pci_devinst *pi, uint16_t old)
1977 {
1978         int i;
1979         uint16_t changed, new;
1980
1981         new = pci_get_cfgdata16(pi, PCIR_COMMAND);
1982         changed = old ^ new;
1983
1984         /*
1985          * If the MMIO or I/O address space decoding has changed then
1986          * register/unregister all BARs that decode that address space.
1987          */
1988         for (i = 0; i <= PCI_BARMAX_WITH_ROM; i++) {
1989                 switch (pi->pi_bar[i].type) {
1990                         case PCIBAR_NONE:
1991                         case PCIBAR_MEMHI64:
1992                                 break;
1993                         case PCIBAR_IO:
1994                                 /* I/O address space decoding changed? */
1995                                 if (changed & PCIM_CMD_PORTEN) {
1996                                         if (new & PCIM_CMD_PORTEN)
1997                                                 register_bar(pi, i);
1998                                         else
1999                                                 unregister_bar(pi, i);
2000                                 }
2001                                 break;
2002                         case PCIBAR_ROM:
2003                                 /* skip (un-)register of ROM if it disabled */
2004                                 if (!romen(pi))
2005                                         break;
2006                                 /* fallthrough */
2007                         case PCIBAR_MEM32:
2008                         case PCIBAR_MEM64:
2009                                 /* MMIO address space decoding changed? */
2010                                 if (changed & PCIM_CMD_MEMEN) {
2011                                         if (new & PCIM_CMD_MEMEN)
2012                                                 register_bar(pi, i);
2013                                         else
2014                                                 unregister_bar(pi, i);
2015                                 }
2016                                 break;
2017                         default:
2018                                 assert(0);
2019                 }
2020         }
2021
2022         /*
2023          * If INTx has been unmasked and is pending, assert the
2024          * interrupt.
2025          */
2026         pci_lintr_update(pi);
2027 }
2028
2029 static void
2030 pci_emul_cmdsts_write(struct pci_devinst *pi, int coff, uint32_t new, int bytes)
2031 {
2032         int rshift;
2033         uint32_t cmd, old, readonly;
2034
2035         cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);      /* stash old value */
2036
2037         /*
2038          * From PCI Local Bus Specification 3.0 sections 6.2.2 and 6.2.3.
2039          *
2040          * XXX Bits 8, 11, 12, 13, 14 and 15 in the status register are
2041          * 'write 1 to clear'. However these bits are not set to '1' by
2042          * any device emulation so it is simpler to treat them as readonly.
2043          */
2044         rshift = (coff & 0x3) * 8;
2045         readonly = 0xFFFFF880 >> rshift;
2046
2047         old = CFGREAD(pi, coff, bytes);
2048         new &= ~readonly;
2049         new |= (old & readonly);
2050         CFGWRITE(pi, coff, new, bytes);                 /* update config */
2051
2052         pci_emul_cmd_changed(pi, cmd);
2053 }
2054
2055 static void
2056 pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot, int func,
2057     int coff, int bytes, uint32_t *eax)
2058 {
2059         struct businfo *bi;
2060         struct slotinfo *si;
2061         struct pci_devinst *pi;
2062         struct pci_devemu *pe;
2063         int idx, needcfg;
2064         uint64_t addr, bar, mask;
2065
2066         if ((bi = pci_businfo[bus]) != NULL) {
2067                 si = &bi->slotinfo[slot];
2068                 pi = si->si_funcs[func].fi_devi;
2069         } else
2070                 pi = NULL;
2071
2072         /*
2073          * Just return if there is no device at this slot:func or if the
2074          * the guest is doing an un-aligned access.
2075          */
2076         if (pi == NULL || (bytes != 1 && bytes != 2 && bytes != 4) ||
2077             (coff & (bytes - 1)) != 0) {
2078                 if (in)
2079                         *eax = 0xffffffff;
2080                 return;
2081         }
2082
2083         /*
2084          * Ignore all writes beyond the standard config space and return all
2085          * ones on reads.
2086          */
2087         if (coff >= PCI_REGMAX + 1) {
2088                 if (in) {
2089                         *eax = 0xffffffff;
2090                         /*
2091                          * Extended capabilities begin at offset 256 in config
2092                          * space. Absence of extended capabilities is signaled
2093                          * with all 0s in the extended capability header at
2094                          * offset 256.
2095                          */
2096                         if (coff <= PCI_REGMAX + 4)
2097                                 *eax = 0x00000000;
2098                 }
2099                 return;
2100         }
2101
2102         pe = pi->pi_d;
2103
2104         /*
2105          * Config read
2106          */
2107         if (in) {
2108                 /* Let the device emulation override the default handler */
2109                 if (pe->pe_cfgread != NULL) {
2110                         needcfg = pe->pe_cfgread(ctx, vcpu, pi, coff, bytes,
2111                             eax);
2112                 } else {
2113                         needcfg = 1;
2114                 }
2115
2116                 if (needcfg)
2117                         *eax = CFGREAD(pi, coff, bytes);
2118
2119                 pci_emul_hdrtype_fixup(bus, slot, coff, bytes, eax);
2120         } else {
2121                 /* Let the device emulation override the default handler */
2122                 if (pe->pe_cfgwrite != NULL &&
2123                     (*pe->pe_cfgwrite)(ctx, vcpu, pi, coff, bytes, *eax) == 0)
2124                         return;
2125
2126                 /*
2127                  * Special handling for write to BAR and ROM registers
2128                  */
2129                 if (is_pcir_bar(coff) || is_pcir_bios(coff)) {
2130                         /*
2131                          * Ignore writes to BAR registers that are not
2132                          * 4-byte aligned.
2133                          */
2134                         if (bytes != 4 || (coff & 0x3) != 0)
2135                                 return;
2136
2137                         if (is_pcir_bar(coff)) {
2138                                 idx = (coff - PCIR_BAR(0)) / 4;
2139                         } else if (is_pcir_bios(coff)) {
2140                                 idx = PCI_ROM_IDX;
2141                         } else {
2142                                 errx(4, "%s: invalid BAR offset %d", __func__,
2143                                     coff);
2144                         }
2145
2146                         mask = ~(pi->pi_bar[idx].size - 1);
2147                         switch (pi->pi_bar[idx].type) {
2148                         case PCIBAR_NONE:
2149                                 pi->pi_bar[idx].addr = bar = 0;
2150                                 break;
2151                         case PCIBAR_IO:
2152                                 addr = *eax & mask;
2153                                 addr &= 0xffff;
2154                                 bar = addr | pi->pi_bar[idx].lobits;
2155                                 /*
2156                                  * Register the new BAR value for interception
2157                                  */
2158                                 if (addr != pi->pi_bar[idx].addr) {
2159                                         update_bar_address(pi, addr, idx,
2160                                                            PCIBAR_IO);
2161                                 }
2162                                 break;
2163                         case PCIBAR_MEM32:
2164                                 addr = bar = *eax & mask;
2165                                 bar |= pi->pi_bar[idx].lobits;
2166                                 if (addr != pi->pi_bar[idx].addr) {
2167                                         update_bar_address(pi, addr, idx,
2168                                                            PCIBAR_MEM32);
2169                                 }
2170                                 break;
2171                         case PCIBAR_MEM64:
2172                                 addr = bar = *eax & mask;
2173                                 bar |= pi->pi_bar[idx].lobits;
2174                                 if (addr != (uint32_t)pi->pi_bar[idx].addr) {
2175                                         update_bar_address(pi, addr, idx,
2176                                                            PCIBAR_MEM64);
2177                                 }
2178                                 break;
2179                         case PCIBAR_MEMHI64:
2180                                 mask = ~(pi->pi_bar[idx - 1].size - 1);
2181                                 addr = ((uint64_t)*eax << 32) & mask;
2182                                 bar = addr >> 32;
2183                                 if (bar != pi->pi_bar[idx - 1].addr >> 32) {
2184                                         update_bar_address(pi, addr, idx - 1,
2185                                                            PCIBAR_MEMHI64);
2186                                 }
2187                                 break;
2188                         case PCIBAR_ROM:
2189                                 addr = bar = *eax & mask;
2190                                 if (memen(pi) && romen(pi)) {
2191                                         unregister_bar(pi, idx);
2192                                 }
2193                                 pi->pi_bar[idx].addr = addr;
2194                                 pi->pi_bar[idx].lobits = *eax &
2195                                     PCIM_BIOS_ENABLE;
2196                                 /* romen could have changed it value */
2197                                 if (memen(pi) && romen(pi)) {
2198                                         register_bar(pi, idx);
2199                                 }
2200                                 bar |= pi->pi_bar[idx].lobits;
2201                                 break;
2202                         default:
2203                                 assert(0);
2204                         }
2205                         pci_set_cfgdata32(pi, coff, bar);
2206
2207                 } else if (pci_emul_iscap(pi, coff)) {
2208                         pci_emul_capwrite(pi, coff, bytes, *eax, 0, 0);
2209                 } else if (coff >= PCIR_COMMAND && coff < PCIR_REVID) {
2210                         pci_emul_cmdsts_write(pi, coff, *eax, bytes);
2211                 } else {
2212                         CFGWRITE(pi, coff, *eax, bytes);
2213                 }
2214         }
2215 }
2216
2217 static int cfgenable, cfgbus, cfgslot, cfgfunc, cfgoff;
2218
2219 static int
2220 pci_emul_cfgaddr(struct vmctx *ctx __unused, int vcpu __unused, int in,
2221     int port __unused, int bytes, uint32_t *eax, void *arg __unused)
2222 {
2223         uint32_t x;
2224
2225         if (bytes != 4) {
2226                 if (in)
2227                         *eax = (bytes == 2) ? 0xffff : 0xff;
2228                 return (0);
2229         }
2230
2231         if (in) {
2232                 x = (cfgbus << 16) | (cfgslot << 11) | (cfgfunc << 8) | cfgoff;
2233                 if (cfgenable)
2234                         x |= CONF1_ENABLE;
2235                 *eax = x;
2236         } else {
2237                 x = *eax;
2238                 cfgenable = (x & CONF1_ENABLE) == CONF1_ENABLE;
2239                 cfgoff = (x & PCI_REGMAX) & ~0x03;
2240                 cfgfunc = (x >> 8) & PCI_FUNCMAX;
2241                 cfgslot = (x >> 11) & PCI_SLOTMAX;
2242                 cfgbus = (x >> 16) & PCI_BUSMAX;
2243         }
2244
2245         return (0);
2246 }
2247 INOUT_PORT(pci_cfgaddr, CONF1_ADDR_PORT, IOPORT_F_INOUT, pci_emul_cfgaddr);
2248
2249 static int
2250 pci_emul_cfgdata(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
2251     uint32_t *eax, void *arg __unused)
2252 {
2253         int coff;
2254
2255         assert(bytes == 1 || bytes == 2 || bytes == 4);
2256
2257         coff = cfgoff + (port - CONF1_DATA_PORT);
2258         if (cfgenable) {
2259                 pci_cfgrw(ctx, vcpu, in, cfgbus, cfgslot, cfgfunc, coff, bytes,
2260                     eax);
2261         } else {
2262                 /* Ignore accesses to cfgdata if not enabled by cfgaddr */
2263                 if (in)
2264                         *eax = 0xffffffff;
2265         }
2266         return (0);
2267 }
2268
2269 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+0, IOPORT_F_INOUT, pci_emul_cfgdata);
2270 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+1, IOPORT_F_INOUT, pci_emul_cfgdata);
2271 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+2, IOPORT_F_INOUT, pci_emul_cfgdata);
2272 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+3, IOPORT_F_INOUT, pci_emul_cfgdata);
2273
2274 #ifdef BHYVE_SNAPSHOT
2275 /*
2276  * Saves/restores PCI device emulated state. Returns 0 on success.
2277  */
2278 static int
2279 pci_snapshot_pci_dev(struct vm_snapshot_meta *meta)
2280 {
2281         struct pci_devinst *pi;
2282         int i;
2283         int ret;
2284
2285         pi = meta->dev_data;
2286
2287         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msi.enabled, meta, ret, done);
2288         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msi.addr, meta, ret, done);
2289         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msi.msg_data, meta, ret, done);
2290         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msi.maxmsgnum, meta, ret, done);
2291
2292         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.enabled, meta, ret, done);
2293         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.table_bar, meta, ret, done);
2294         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.pba_bar, meta, ret, done);
2295         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.table_offset, meta, ret, done);
2296         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.table_count, meta, ret, done);
2297         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.pba_offset, meta, ret, done);
2298         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.pba_size, meta, ret, done);
2299         SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.function_mask, meta, ret, done);
2300
2301         SNAPSHOT_BUF_OR_LEAVE(pi->pi_cfgdata, sizeof(pi->pi_cfgdata),
2302                               meta, ret, done);
2303
2304         for (i = 0; i < (int)nitems(pi->pi_bar); i++) {
2305                 SNAPSHOT_VAR_OR_LEAVE(pi->pi_bar[i].type, meta, ret, done);
2306                 SNAPSHOT_VAR_OR_LEAVE(pi->pi_bar[i].size, meta, ret, done);
2307                 SNAPSHOT_VAR_OR_LEAVE(pi->pi_bar[i].addr, meta, ret, done);
2308         }
2309
2310         /* Restore MSI-X table. */
2311         for (i = 0; i < pi->pi_msix.table_count; i++) {
2312                 SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.table[i].addr,
2313                                       meta, ret, done);
2314                 SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.table[i].msg_data,
2315                                       meta, ret, done);
2316                 SNAPSHOT_VAR_OR_LEAVE(pi->pi_msix.table[i].vector_control,
2317                                       meta, ret, done);
2318         }
2319
2320 done:
2321         return (ret);
2322 }
2323
2324 static int
2325 pci_find_slotted_dev(const char *dev_name, struct pci_devemu **pde,
2326                      struct pci_devinst **pdi)
2327 {
2328         struct businfo *bi;
2329         struct slotinfo *si;
2330         struct funcinfo *fi;
2331         int bus, slot, func;
2332
2333         assert(dev_name != NULL);
2334         assert(pde != NULL);
2335         assert(pdi != NULL);
2336
2337         for (bus = 0; bus < MAXBUSES; bus++) {
2338                 if ((bi = pci_businfo[bus]) == NULL)
2339                         continue;
2340
2341                 for (slot = 0; slot < MAXSLOTS; slot++) {
2342                         si = &bi->slotinfo[slot];
2343                         for (func = 0; func < MAXFUNCS; func++) {
2344                                 fi = &si->si_funcs[func];
2345                                 if (fi->fi_pde == NULL)
2346                                         continue;
2347                                 if (strcmp(dev_name, fi->fi_pde->pe_emu) != 0)
2348                                         continue;
2349
2350                                 *pde = fi->fi_pde;
2351                                 *pdi = fi->fi_devi;
2352                                 return (0);
2353                         }
2354                 }
2355         }
2356
2357         return (EINVAL);
2358 }
2359
2360 int
2361 pci_snapshot(struct vm_snapshot_meta *meta)
2362 {
2363         struct pci_devemu *pde;
2364         struct pci_devinst *pdi;
2365         int ret;
2366
2367         assert(meta->dev_name != NULL);
2368
2369         ret = pci_find_slotted_dev(meta->dev_name, &pde, &pdi);
2370         if (ret != 0) {
2371                 fprintf(stderr, "%s: no such name: %s\r\n",
2372                         __func__, meta->dev_name);
2373                 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
2374                 return (0);
2375         }
2376
2377         meta->dev_data = pdi;
2378
2379         if (pde->pe_snapshot == NULL) {
2380                 fprintf(stderr, "%s: not implemented yet for: %s\r\n",
2381                         __func__, meta->dev_name);
2382                 return (-1);
2383         }
2384
2385         ret = pci_snapshot_pci_dev(meta);
2386         if (ret != 0) {
2387                 fprintf(stderr, "%s: failed to snapshot pci dev\r\n",
2388                         __func__);
2389                 return (-1);
2390         }
2391
2392         ret = (*pde->pe_snapshot)(meta);
2393
2394         return (ret);
2395 }
2396
2397 int
2398 pci_pause(struct vmctx *ctx, const char *dev_name)
2399 {
2400         struct pci_devemu *pde;
2401         struct pci_devinst *pdi;
2402         int ret;
2403
2404         assert(dev_name != NULL);
2405
2406         ret = pci_find_slotted_dev(dev_name, &pde, &pdi);
2407         if (ret != 0) {
2408                 /*
2409                  * It is possible to call this function without
2410                  * checking that the device is inserted first.
2411                  */
2412                 fprintf(stderr, "%s: no such name: %s\n", __func__, dev_name);
2413                 return (0);
2414         }
2415
2416         if (pde->pe_pause == NULL) {
2417                 /* The pause/resume functionality is optional. */
2418                 fprintf(stderr, "%s: not implemented for: %s\n",
2419                         __func__, dev_name);
2420                 return (0);
2421         }
2422
2423         return (*pde->pe_pause)(ctx, pdi);
2424 }
2425
2426 int
2427 pci_resume(struct vmctx *ctx, const char *dev_name)
2428 {
2429         struct pci_devemu *pde;
2430         struct pci_devinst *pdi;
2431         int ret;
2432
2433         assert(dev_name != NULL);
2434
2435         ret = pci_find_slotted_dev(dev_name, &pde, &pdi);
2436         if (ret != 0) {
2437                 /*
2438                  * It is possible to call this function without
2439                  * checking that the device is inserted first.
2440                  */
2441                 fprintf(stderr, "%s: no such name: %s\n", __func__, dev_name);
2442                 return (0);
2443         }
2444
2445         if (pde->pe_resume == NULL) {
2446                 /* The pause/resume functionality is optional. */
2447                 fprintf(stderr, "%s: not implemented for: %s\n",
2448                         __func__, dev_name);
2449                 return (0);
2450         }
2451
2452         return (*pde->pe_resume)(ctx, pdi);
2453 }
2454 #endif
2455
2456 #define PCI_EMUL_TEST
2457 #ifdef PCI_EMUL_TEST
2458 /*
2459  * Define a dummy test device
2460  */
2461 #define DIOSZ   8
2462 #define DMEMSZ  4096
2463 struct pci_emul_dsoftc {
2464         uint8_t   ioregs[DIOSZ];
2465         uint8_t   memregs[2][DMEMSZ];
2466 };
2467
2468 #define PCI_EMUL_MSI_MSGS        4
2469 #define PCI_EMUL_MSIX_MSGS      16
2470
2471 static int
2472 pci_emul_dinit(struct vmctx *ctx __unused, struct pci_devinst *pi,
2473     nvlist_t *nvl __unused)
2474 {
2475         int error;
2476         struct pci_emul_dsoftc *sc;
2477
2478         sc = calloc(1, sizeof(struct pci_emul_dsoftc));
2479
2480         pi->pi_arg = sc;
2481
2482         pci_set_cfgdata16(pi, PCIR_DEVICE, 0x0001);
2483         pci_set_cfgdata16(pi, PCIR_VENDOR, 0x10DD);
2484         pci_set_cfgdata8(pi, PCIR_CLASS, 0x02);
2485
2486         error = pci_emul_add_msicap(pi, PCI_EMUL_MSI_MSGS);
2487         assert(error == 0);
2488
2489         error = pci_emul_alloc_bar(pi, 0, PCIBAR_IO, DIOSZ);
2490         assert(error == 0);
2491
2492         error = pci_emul_alloc_bar(pi, 1, PCIBAR_MEM32, DMEMSZ);
2493         assert(error == 0);
2494
2495         error = pci_emul_alloc_bar(pi, 2, PCIBAR_MEM32, DMEMSZ);
2496         assert(error == 0);
2497
2498         return (0);
2499 }
2500
2501 static void
2502 pci_emul_diow(struct vmctx *ctx __unused, int vcpu __unused,
2503     struct pci_devinst *pi, int baridx, uint64_t offset, int size,
2504     uint64_t value)
2505 {
2506         int i;
2507         struct pci_emul_dsoftc *sc = pi->pi_arg;
2508
2509         if (baridx == 0) {
2510                 if (offset + size > DIOSZ) {
2511                         printf("diow: iow too large, offset %ld size %d\n",
2512                                offset, size);
2513                         return;
2514                 }
2515
2516                 if (size == 1) {
2517                         sc->ioregs[offset] = value & 0xff;
2518                 } else if (size == 2) {
2519                         *(uint16_t *)&sc->ioregs[offset] = value & 0xffff;
2520                 } else if (size == 4) {
2521                         *(uint32_t *)&sc->ioregs[offset] = value;
2522                 } else {
2523                         printf("diow: iow unknown size %d\n", size);
2524                 }
2525
2526                 /*
2527                  * Special magic value to generate an interrupt
2528                  */
2529                 if (offset == 4 && size == 4 && pci_msi_enabled(pi))
2530                         pci_generate_msi(pi, value % pci_msi_maxmsgnum(pi));
2531
2532                 if (value == 0xabcdef) {
2533                         for (i = 0; i < pci_msi_maxmsgnum(pi); i++)
2534                                 pci_generate_msi(pi, i);
2535                 }
2536         }
2537
2538         if (baridx == 1 || baridx == 2) {
2539                 if (offset + size > DMEMSZ) {
2540                         printf("diow: memw too large, offset %ld size %d\n",
2541                                offset, size);
2542                         return;
2543                 }
2544
2545                 i = baridx - 1;         /* 'memregs' index */
2546
2547                 if (size == 1) {
2548                         sc->memregs[i][offset] = value;
2549                 } else if (size == 2) {
2550                         *(uint16_t *)&sc->memregs[i][offset] = value;
2551                 } else if (size == 4) {
2552                         *(uint32_t *)&sc->memregs[i][offset] = value;
2553                 } else if (size == 8) {
2554                         *(uint64_t *)&sc->memregs[i][offset] = value;
2555                 } else {
2556                         printf("diow: memw unknown size %d\n", size);
2557                 }
2558
2559                 /*
2560                  * magic interrupt ??
2561                  */
2562         }
2563
2564         if (baridx > 2 || baridx < 0) {
2565                 printf("diow: unknown bar idx %d\n", baridx);
2566         }
2567 }
2568
2569 static uint64_t
2570 pci_emul_dior(struct vmctx *ctx __unused, int vcpu __unused,
2571     struct pci_devinst *pi, int baridx, uint64_t offset, int size)
2572 {
2573         struct pci_emul_dsoftc *sc = pi->pi_arg;
2574         uint32_t value;
2575         int i;
2576
2577         if (baridx == 0) {
2578                 if (offset + size > DIOSZ) {
2579                         printf("dior: ior too large, offset %ld size %d\n",
2580                                offset, size);
2581                         return (0);
2582                 }
2583
2584                 value = 0;
2585                 if (size == 1) {
2586                         value = sc->ioregs[offset];
2587                 } else if (size == 2) {
2588                         value = *(uint16_t *) &sc->ioregs[offset];
2589                 } else if (size == 4) {
2590                         value = *(uint32_t *) &sc->ioregs[offset];
2591                 } else {
2592                         printf("dior: ior unknown size %d\n", size);
2593                 }
2594         }
2595
2596         if (baridx == 1 || baridx == 2) {
2597                 if (offset + size > DMEMSZ) {
2598                         printf("dior: memr too large, offset %ld size %d\n",
2599                                offset, size);
2600                         return (0);
2601                 }
2602
2603                 i = baridx - 1;         /* 'memregs' index */
2604
2605                 if (size == 1) {
2606                         value = sc->memregs[i][offset];
2607                 } else if (size == 2) {
2608                         value = *(uint16_t *) &sc->memregs[i][offset];
2609                 } else if (size == 4) {
2610                         value = *(uint32_t *) &sc->memregs[i][offset];
2611                 } else if (size == 8) {
2612                         value = *(uint64_t *) &sc->memregs[i][offset];
2613                 } else {
2614                         printf("dior: ior unknown size %d\n", size);
2615                 }
2616         }
2617
2618
2619         if (baridx > 2 || baridx < 0) {
2620                 printf("dior: unknown bar idx %d\n", baridx);
2621                 return (0);
2622         }
2623
2624         return (value);
2625 }
2626
2627 #ifdef BHYVE_SNAPSHOT
2628 static int
2629 pci_emul_snapshot(struct vm_snapshot_meta *meta __unused)
2630 {
2631         return (0);
2632 }
2633 #endif
2634
2635 static const struct pci_devemu pci_dummy = {
2636         .pe_emu = "dummy",
2637         .pe_init = pci_emul_dinit,
2638         .pe_barwrite = pci_emul_diow,
2639         .pe_barread = pci_emul_dior,
2640 #ifdef BHYVE_SNAPSHOT
2641         .pe_snapshot = pci_emul_snapshot,
2642 #endif
2643 };
2644 PCI_EMUL_SET(pci_dummy);
2645
2646 #endif /* PCI_EMUL_TEST */