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