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