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