xref: /freebsd/usr.sbin/bhyve/pci_emul.c (revision 55bce0c1203e70d8b62a3dedc9235ab39660c6f4)
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/linker_set.h>
34 #include <sys/errno.h>
35 
36 #include <ctype.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <strings.h>
41 #include <assert.h>
42 #include <stdbool.h>
43 
44 #include <machine/vmm.h>
45 #include <vmmapi.h>
46 
47 #include "bhyverun.h"
48 #include "inout.h"
49 #include "mem.h"
50 #include "mptbl.h"
51 #include "pci_emul.h"
52 #include "ioapic.h"
53 
54 #define CONF1_ADDR_PORT    0x0cf8
55 #define CONF1_DATA_PORT    0x0cfc
56 
57 #define	CFGWRITE(pi,off,val,b)						\
58 do {									\
59 	if ((b) == 1) {							\
60 		pci_set_cfgdata8((pi),(off),(val));			\
61 	} else if ((b) == 2) {						\
62 		pci_set_cfgdata16((pi),(off),(val));			\
63 	} else {							\
64 		pci_set_cfgdata32((pi),(off),(val));			\
65 	}								\
66 } while (0)
67 
68 #define MAXSLOTS	(PCI_SLOTMAX + 1)
69 #define	MAXFUNCS	(PCI_FUNCMAX + 1)
70 
71 static struct slotinfo {
72 	char	*si_name;
73 	char	*si_param;
74 	struct pci_devinst *si_devi;
75 	int	si_legacy;
76 } pci_slotinfo[MAXSLOTS][MAXFUNCS];
77 
78 /*
79  * Used to keep track of legacy interrupt owners/requestors
80  */
81 #define NLIRQ		16
82 
83 static struct lirqinfo {
84 	int	li_generic;
85 	int	li_acount;
86 	struct pci_devinst *li_owner;	/* XXX should be a list */
87 } lirq[NLIRQ];
88 
89 SET_DECLARE(pci_devemu_set, struct pci_devemu);
90 
91 static uint64_t pci_emul_iobase;
92 static uint64_t pci_emul_membase32;
93 static uint64_t pci_emul_membase64;
94 
95 #define	PCI_EMUL_IOBASE		0x2000
96 #define	PCI_EMUL_IOLIMIT	0x10000
97 
98 #define	PCI_EMUL_MEMLIMIT32	0xE0000000		/* 3.5GB */
99 
100 #define	PCI_EMUL_MEMBASE64	0xD000000000UL
101 #define	PCI_EMUL_MEMLIMIT64	0xFD00000000UL
102 
103 static struct pci_devemu *pci_emul_finddev(char *name);
104 
105 static int pci_emul_devices;
106 
107 /*
108  * I/O access
109  */
110 
111 /*
112  * Slot options are in the form:
113  *
114  *  <slot>[:<func>],<emul>[,<config>]
115  *
116  *  slot is 0..31
117  *  func is 0..7
118  *  emul is a string describing the type of PCI device e.g. virtio-net
119  *  config is an optional string, depending on the device, that can be
120  *  used for configuration.
121  *   Examples are:
122  *     1,virtio-net,tap0
123  *     3:0,dummy
124  */
125 static void
126 pci_parse_slot_usage(char *aopt)
127 {
128 
129 	fprintf(stderr, "Invalid PCI slot info field \"%s\"\n", aopt);
130 }
131 
132 int
133 pci_parse_slot(char *opt, int legacy)
134 {
135 	char *slot, *func, *emul, *config;
136 	char *str, *cpy;
137 	int error, snum, fnum;
138 
139 	error = -1;
140 	str = cpy = strdup(opt);
141 
142 	config = NULL;
143 
144 	if (strchr(str, ':') != NULL) {
145 		slot = strsep(&str, ":");
146 		func = strsep(&str, ",");
147 	} else {
148 		slot = strsep(&str, ",");
149 		func = NULL;
150 	}
151 
152 	emul = strsep(&str, ",");
153 	if (str != NULL) {
154 		config = strsep(&str, ",");
155 	}
156 
157 	if (emul == NULL) {
158 		pci_parse_slot_usage(opt);
159 		goto done;
160 	}
161 
162 	snum = atoi(slot);
163 	fnum = func ? atoi(func) : 0;
164 
165 	if (snum < 0 || snum >= MAXSLOTS || fnum < 0 || fnum >= MAXFUNCS) {
166 		pci_parse_slot_usage(opt);
167 		goto done;
168 	}
169 
170 	if (pci_slotinfo[snum][fnum].si_name != NULL) {
171 		fprintf(stderr, "pci slot %d:%d already occupied!\n",
172 			snum, fnum);
173 		goto done;
174 	}
175 
176 	if (pci_emul_finddev(emul) == NULL) {
177 		fprintf(stderr, "pci slot %d:%d: unknown device \"%s\"\n",
178 			snum, fnum, emul);
179 		goto done;
180 	}
181 
182 	error = 0;
183 	pci_slotinfo[snum][fnum].si_name = emul;
184 	pci_slotinfo[snum][fnum].si_param = config;
185 	pci_slotinfo[snum][fnum].si_legacy = legacy;
186 
187 done:
188 	if (error)
189 		free(cpy);
190 
191 	return (error);
192 }
193 
194 static int
195 pci_valid_pba_offset(struct pci_devinst *pi, uint64_t offset)
196 {
197 
198 	if (offset < pi->pi_msix.pba_offset)
199 		return (0);
200 
201 	if (offset >= pi->pi_msix.pba_offset + pi->pi_msix.pba_size) {
202 		return (0);
203 	}
204 
205 	return (1);
206 }
207 
208 int
209 pci_emul_msix_twrite(struct pci_devinst *pi, uint64_t offset, int size,
210 		     uint64_t value)
211 {
212 	int msix_entry_offset;
213 	int tab_index;
214 	char *dest;
215 
216 	/* support only 4 or 8 byte writes */
217 	if (size != 4 && size != 8)
218 		return (-1);
219 
220 	/*
221 	 * Return if table index is beyond what device supports
222 	 */
223 	tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
224 	if (tab_index >= pi->pi_msix.table_count)
225 		return (-1);
226 
227 	msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
228 
229 	/* support only aligned writes */
230 	if ((msix_entry_offset % size) != 0)
231 		return (-1);
232 
233 	dest = (char *)(pi->pi_msix.table + tab_index);
234 	dest += msix_entry_offset;
235 
236 	if (size == 4)
237 		*((uint32_t *)dest) = value;
238 	else
239 		*((uint64_t *)dest) = value;
240 
241 	return (0);
242 }
243 
244 uint64_t
245 pci_emul_msix_tread(struct pci_devinst *pi, uint64_t offset, int size)
246 {
247 	char *dest;
248 	int msix_entry_offset;
249 	int tab_index;
250 	uint64_t retval = ~0;
251 
252 	/* support only 4 or 8 byte reads */
253 	if (size != 4 && size != 8)
254 		return (retval);
255 
256 	msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
257 
258 	/* support only aligned reads */
259 	if ((msix_entry_offset % size) != 0) {
260 		return (retval);
261 	}
262 
263 	tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
264 
265 	if (tab_index < pi->pi_msix.table_count) {
266 		/* valid MSI-X Table access */
267 		dest = (char *)(pi->pi_msix.table + tab_index);
268 		dest += msix_entry_offset;
269 
270 		if (size == 4)
271 			retval = *((uint32_t *)dest);
272 		else
273 			retval = *((uint64_t *)dest);
274 	} else if (pci_valid_pba_offset(pi, offset)) {
275 		/* return 0 for PBA access */
276 		retval = 0;
277 	}
278 
279 	return (retval);
280 }
281 
282 int
283 pci_msix_table_bar(struct pci_devinst *pi)
284 {
285 
286 	if (pi->pi_msix.table != NULL)
287 		return (pi->pi_msix.table_bar);
288 	else
289 		return (-1);
290 }
291 
292 int
293 pci_msix_pba_bar(struct pci_devinst *pi)
294 {
295 
296 	if (pi->pi_msix.table != NULL)
297 		return (pi->pi_msix.pba_bar);
298 	else
299 		return (-1);
300 }
301 
302 static int
303 pci_emul_io_handler(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
304 		    uint32_t *eax, void *arg)
305 {
306 	struct pci_devinst *pdi = arg;
307 	struct pci_devemu *pe = pdi->pi_d;
308 	uint64_t offset;
309 	int i;
310 
311 	for (i = 0; i <= PCI_BARMAX; i++) {
312 		if (pdi->pi_bar[i].type == PCIBAR_IO &&
313 		    port >= pdi->pi_bar[i].addr &&
314 		    port + bytes <= pdi->pi_bar[i].addr + pdi->pi_bar[i].size) {
315 			offset = port - pdi->pi_bar[i].addr;
316 			if (in)
317 				*eax = (*pe->pe_barread)(ctx, vcpu, pdi, i,
318 							 offset, bytes);
319 			else
320 				(*pe->pe_barwrite)(ctx, vcpu, pdi, i, offset,
321 						   bytes, *eax);
322 			return (0);
323 		}
324 	}
325 	return (-1);
326 }
327 
328 static int
329 pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
330 		     int size, uint64_t *val, void *arg1, long arg2)
331 {
332 	struct pci_devinst *pdi = arg1;
333 	struct pci_devemu *pe = pdi->pi_d;
334 	uint64_t offset;
335 	int bidx = (int) arg2;
336 
337 	assert(bidx <= PCI_BARMAX);
338 	assert(pdi->pi_bar[bidx].type == PCIBAR_MEM32 ||
339 	       pdi->pi_bar[bidx].type == PCIBAR_MEM64);
340 	assert(addr >= pdi->pi_bar[bidx].addr &&
341 	       addr + size <= pdi->pi_bar[bidx].addr + pdi->pi_bar[bidx].size);
342 
343 	offset = addr - pdi->pi_bar[bidx].addr;
344 
345 	if (dir == MEM_F_WRITE)
346 		(*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset, size, *val);
347 	else
348 		*val = (*pe->pe_barread)(ctx, vcpu, pdi, bidx, offset, size);
349 
350 	return (0);
351 }
352 
353 
354 static int
355 pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,
356 			uint64_t *addr)
357 {
358 	uint64_t base;
359 
360 	assert((size & (size - 1)) == 0);	/* must be a power of 2 */
361 
362 	base = roundup2(*baseptr, size);
363 
364 	if (base + size <= limit) {
365 		*addr = base;
366 		*baseptr = base + size;
367 		return (0);
368 	} else
369 		return (-1);
370 }
371 
372 int
373 pci_emul_alloc_bar(struct pci_devinst *pdi, int idx, enum pcibar_type type,
374 		   uint64_t size)
375 {
376 
377 	return (pci_emul_alloc_pbar(pdi, idx, 0, type, size));
378 }
379 
380 /*
381  * Register (or unregister) the MMIO or I/O region associated with the BAR
382  * register 'idx' of an emulated pci device.
383  */
384 static void
385 modify_bar_registration(struct pci_devinst *pi, int idx, int registration)
386 {
387 	int error;
388 	struct inout_port iop;
389 	struct mem_range mr;
390 
391 	switch (pi->pi_bar[idx].type) {
392 	case PCIBAR_IO:
393 		bzero(&iop, sizeof(struct inout_port));
394 		iop.name = pi->pi_name;
395 		iop.port = pi->pi_bar[idx].addr;
396 		iop.size = pi->pi_bar[idx].size;
397 		if (registration) {
398 			iop.flags = IOPORT_F_INOUT;
399 			iop.handler = pci_emul_io_handler;
400 			iop.arg = pi;
401 			error = register_inout(&iop);
402 		} else
403 			error = unregister_inout(&iop);
404 		break;
405 	case PCIBAR_MEM32:
406 	case PCIBAR_MEM64:
407 		bzero(&mr, sizeof(struct mem_range));
408 		mr.name = pi->pi_name;
409 		mr.base = pi->pi_bar[idx].addr;
410 		mr.size = pi->pi_bar[idx].size;
411 		if (registration) {
412 			mr.flags = MEM_F_RW;
413 			mr.handler = pci_emul_mem_handler;
414 			mr.arg1 = pi;
415 			mr.arg2 = idx;
416 			error = register_mem(&mr);
417 		} else
418 			error = unregister_mem(&mr);
419 		break;
420 	default:
421 		error = EINVAL;
422 		break;
423 	}
424 	assert(error == 0);
425 }
426 
427 static void
428 unregister_bar(struct pci_devinst *pi, int idx)
429 {
430 
431 	modify_bar_registration(pi, idx, 0);
432 }
433 
434 static void
435 register_bar(struct pci_devinst *pi, int idx)
436 {
437 
438 	modify_bar_registration(pi, idx, 1);
439 }
440 
441 /* Are we decoding i/o port accesses for the emulated pci device? */
442 static int
443 porten(struct pci_devinst *pi)
444 {
445 	uint16_t cmd;
446 
447 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
448 
449 	return (cmd & PCIM_CMD_PORTEN);
450 }
451 
452 /* Are we decoding memory accesses for the emulated pci device? */
453 static int
454 memen(struct pci_devinst *pi)
455 {
456 	uint16_t cmd;
457 
458 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
459 
460 	return (cmd & PCIM_CMD_MEMEN);
461 }
462 
463 /*
464  * Update the MMIO or I/O address that is decoded by the BAR register.
465  *
466  * If the pci device has enabled the address space decoding then intercept
467  * the address range decoded by the BAR register.
468  */
469 static void
470 update_bar_address(struct  pci_devinst *pi, uint64_t addr, int idx, int type)
471 {
472 	int decode;
473 
474 	if (pi->pi_bar[idx].type == PCIBAR_IO)
475 		decode = porten(pi);
476 	else
477 		decode = memen(pi);
478 
479 	if (decode)
480 		unregister_bar(pi, idx);
481 
482 	switch (type) {
483 	case PCIBAR_IO:
484 	case PCIBAR_MEM32:
485 		pi->pi_bar[idx].addr = addr;
486 		break;
487 	case PCIBAR_MEM64:
488 		pi->pi_bar[idx].addr &= ~0xffffffffUL;
489 		pi->pi_bar[idx].addr |= addr;
490 		break;
491 	case PCIBAR_MEMHI64:
492 		pi->pi_bar[idx].addr &= 0xffffffff;
493 		pi->pi_bar[idx].addr |= addr;
494 		break;
495 	default:
496 		assert(0);
497 	}
498 
499 	if (decode)
500 		register_bar(pi, idx);
501 }
502 
503 int
504 pci_emul_alloc_pbar(struct pci_devinst *pdi, int idx, uint64_t hostbase,
505 		    enum pcibar_type type, uint64_t size)
506 {
507 	int error;
508 	uint64_t *baseptr, limit, addr, mask, lobits, bar;
509 
510 	assert(idx >= 0 && idx <= PCI_BARMAX);
511 
512 	if ((size & (size - 1)) != 0)
513 		size = 1UL << flsl(size);	/* round up to a power of 2 */
514 
515 	/* Enforce minimum BAR sizes required by the PCI standard */
516 	if (type == PCIBAR_IO) {
517 		if (size < 4)
518 			size = 4;
519 	} else {
520 		if (size < 16)
521 			size = 16;
522 	}
523 
524 	switch (type) {
525 	case PCIBAR_NONE:
526 		baseptr = NULL;
527 		addr = mask = lobits = 0;
528 		break;
529 	case PCIBAR_IO:
530 		if (hostbase &&
531 		    pci_slotinfo[pdi->pi_slot][pdi->pi_func].si_legacy) {
532 			assert(hostbase < PCI_EMUL_IOBASE);
533 			baseptr = &hostbase;
534 		} else {
535 			baseptr = &pci_emul_iobase;
536 		}
537 		limit = PCI_EMUL_IOLIMIT;
538 		mask = PCIM_BAR_IO_BASE;
539 		lobits = PCIM_BAR_IO_SPACE;
540 		break;
541 	case PCIBAR_MEM64:
542 		/*
543 		 * XXX
544 		 * Some drivers do not work well if the 64-bit BAR is allocated
545 		 * above 4GB. Allow for this by allocating small requests under
546 		 * 4GB unless then allocation size is larger than some arbitrary
547 		 * number (32MB currently).
548 		 */
549 		if (size > 32 * 1024 * 1024) {
550 			/*
551 			 * XXX special case for device requiring peer-peer DMA
552 			 */
553 			if (size == 0x100000000UL)
554 				baseptr = &hostbase;
555 			else
556 				baseptr = &pci_emul_membase64;
557 			limit = PCI_EMUL_MEMLIMIT64;
558 			mask = PCIM_BAR_MEM_BASE;
559 			lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
560 				 PCIM_BAR_MEM_PREFETCH;
561 			break;
562 		} else {
563 			baseptr = &pci_emul_membase32;
564 			limit = PCI_EMUL_MEMLIMIT32;
565 			mask = PCIM_BAR_MEM_BASE;
566 			lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64;
567 		}
568 		break;
569 	case PCIBAR_MEM32:
570 		baseptr = &pci_emul_membase32;
571 		limit = PCI_EMUL_MEMLIMIT32;
572 		mask = PCIM_BAR_MEM_BASE;
573 		lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
574 		break;
575 	default:
576 		printf("pci_emul_alloc_base: invalid bar type %d\n", type);
577 		assert(0);
578 	}
579 
580 	if (baseptr != NULL) {
581 		error = pci_emul_alloc_resource(baseptr, limit, size, &addr);
582 		if (error != 0)
583 			return (error);
584 	}
585 
586 	pdi->pi_bar[idx].type = type;
587 	pdi->pi_bar[idx].addr = addr;
588 	pdi->pi_bar[idx].size = size;
589 
590 	/* Initialize the BAR register in config space */
591 	bar = (addr & mask) | lobits;
592 	pci_set_cfgdata32(pdi, PCIR_BAR(idx), bar);
593 
594 	if (type == PCIBAR_MEM64) {
595 		assert(idx + 1 <= PCI_BARMAX);
596 		pdi->pi_bar[idx + 1].type = PCIBAR_MEMHI64;
597 		pci_set_cfgdata32(pdi, PCIR_BAR(idx + 1), bar >> 32);
598 	}
599 
600 	register_bar(pdi, idx);
601 
602 	return (0);
603 }
604 
605 #define	CAP_START_OFFSET	0x40
606 static int
607 pci_emul_add_capability(struct pci_devinst *pi, u_char *capdata, int caplen)
608 {
609 	int i, capoff, capid, reallen;
610 	uint16_t sts;
611 
612 	static u_char endofcap[4] = {
613 		PCIY_RESERVED, 0, 0, 0
614 	};
615 
616 	assert(caplen > 0 && capdata[0] != PCIY_RESERVED);
617 
618 	reallen = roundup2(caplen, 4);		/* dword aligned */
619 
620 	sts = pci_get_cfgdata16(pi, PCIR_STATUS);
621 	if ((sts & PCIM_STATUS_CAPPRESENT) == 0) {
622 		capoff = CAP_START_OFFSET;
623 		pci_set_cfgdata8(pi, PCIR_CAP_PTR, capoff);
624 		pci_set_cfgdata16(pi, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT);
625 	} else {
626 		capoff = pci_get_cfgdata8(pi, PCIR_CAP_PTR);
627 		while (1) {
628 			assert((capoff & 0x3) == 0);
629 			capid = pci_get_cfgdata8(pi, capoff);
630 			if (capid == PCIY_RESERVED)
631 				break;
632 			capoff = pci_get_cfgdata8(pi, capoff + 1);
633 		}
634 	}
635 
636 	/* Check if we have enough space */
637 	if (capoff + reallen + sizeof(endofcap) > PCI_REGMAX + 1)
638 		return (-1);
639 
640 	/* Copy the capability */
641 	for (i = 0; i < caplen; i++)
642 		pci_set_cfgdata8(pi, capoff + i, capdata[i]);
643 
644 	/* Set the next capability pointer */
645 	pci_set_cfgdata8(pi, capoff + 1, capoff + reallen);
646 
647 	/* Copy of the reserved capability which serves as the end marker */
648 	for (i = 0; i < sizeof(endofcap); i++)
649 		pci_set_cfgdata8(pi, capoff + reallen + i, endofcap[i]);
650 
651 	return (0);
652 }
653 
654 static struct pci_devemu *
655 pci_emul_finddev(char *name)
656 {
657 	struct pci_devemu **pdpp, *pdp;
658 
659 	SET_FOREACH(pdpp, pci_devemu_set) {
660 		pdp = *pdpp;
661 		if (!strcmp(pdp->pe_emu, name)) {
662 			return (pdp);
663 		}
664 	}
665 
666 	return (NULL);
667 }
668 
669 static void
670 pci_emul_init(struct vmctx *ctx, struct pci_devemu *pde, int slot, int func,
671 	      char *params)
672 {
673 	struct pci_devinst *pdi;
674 	pdi = malloc(sizeof(struct pci_devinst));
675 	bzero(pdi, sizeof(*pdi));
676 
677 	pdi->pi_vmctx = ctx;
678 	pdi->pi_bus = 0;
679 	pdi->pi_slot = slot;
680 	pdi->pi_func = func;
681 	pdi->pi_d = pde;
682 	snprintf(pdi->pi_name, PI_NAMESZ, "%s-pci-%d", pde->pe_emu, slot);
683 
684 	/* Disable legacy interrupts */
685 	pci_set_cfgdata8(pdi, PCIR_INTLINE, 255);
686 	pci_set_cfgdata8(pdi, PCIR_INTPIN, 0);
687 
688 	pci_set_cfgdata8(pdi, PCIR_COMMAND,
689 		    PCIM_CMD_PORTEN | PCIM_CMD_MEMEN | PCIM_CMD_BUSMASTEREN);
690 
691 	if ((*pde->pe_init)(ctx, pdi, params) != 0) {
692 		free(pdi);
693 	} else {
694 		pci_emul_devices++;
695 		pci_slotinfo[slot][func].si_devi = pdi;
696 	}
697 }
698 
699 void
700 pci_populate_msicap(struct msicap *msicap, int msgnum, int nextptr)
701 {
702 	int mmc;
703 
704 	CTASSERT(sizeof(struct msicap) == 14);
705 
706 	/* Number of msi messages must be a power of 2 between 1 and 32 */
707 	assert((msgnum & (msgnum - 1)) == 0 && msgnum >= 1 && msgnum <= 32);
708 	mmc = ffs(msgnum) - 1;
709 
710 	bzero(msicap, sizeof(struct msicap));
711 	msicap->capid = PCIY_MSI;
712 	msicap->nextptr = nextptr;
713 	msicap->msgctrl = PCIM_MSICTRL_64BIT | (mmc << 1);
714 }
715 
716 int
717 pci_emul_add_msicap(struct pci_devinst *pi, int msgnum)
718 {
719 	struct msicap msicap;
720 
721 	pci_populate_msicap(&msicap, msgnum, 0);
722 
723 	return (pci_emul_add_capability(pi, (u_char *)&msicap, sizeof(msicap)));
724 }
725 
726 static void
727 pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,
728 		     uint32_t msix_tab_size, int nextptr)
729 {
730 	CTASSERT(sizeof(struct msixcap) == 12);
731 
732 	assert(msix_tab_size % 4096 == 0);
733 
734 	bzero(msixcap, sizeof(struct msixcap));
735 	msixcap->capid = PCIY_MSIX;
736 	msixcap->nextptr = nextptr;
737 
738 	/*
739 	 * Message Control Register, all fields set to
740 	 * zero except for the Table Size.
741 	 * Note: Table size N is encoded as N-1
742 	 */
743 	msixcap->msgctrl = msgnum - 1;
744 
745 	/*
746 	 * MSI-X BAR setup:
747 	 * - MSI-X table start at offset 0
748 	 * - PBA table starts at a 4K aligned offset after the MSI-X table
749 	 */
750 	msixcap->table_info = barnum & PCIM_MSIX_BIR_MASK;
751 	msixcap->pba_info = msix_tab_size | (barnum & PCIM_MSIX_BIR_MASK);
752 }
753 
754 static void
755 pci_msix_table_init(struct pci_devinst *pi, int table_entries)
756 {
757 	int i, table_size;
758 
759 	assert(table_entries > 0);
760 	assert(table_entries <= MAX_MSIX_TABLE_ENTRIES);
761 
762 	table_size = table_entries * MSIX_TABLE_ENTRY_SIZE;
763 	pi->pi_msix.table = malloc(table_size);
764 	bzero(pi->pi_msix.table, table_size);
765 
766 	/* set mask bit of vector control register */
767 	for (i = 0; i < table_entries; i++)
768 		pi->pi_msix.table[i].vector_control |= PCIM_MSIX_VCTRL_MASK;
769 }
770 
771 int
772 pci_emul_add_msixcap(struct pci_devinst *pi, int msgnum, int barnum)
773 {
774 	uint16_t pba_index;
775 	uint32_t tab_size;
776 	struct msixcap msixcap;
777 
778 	assert(msgnum >= 1 && msgnum <= MAX_MSIX_TABLE_ENTRIES);
779 	assert(barnum >= 0 && barnum <= PCIR_MAX_BAR_0);
780 
781 	tab_size = msgnum * MSIX_TABLE_ENTRY_SIZE;
782 
783 	/* Align table size to nearest 4K */
784 	tab_size = roundup2(tab_size, 4096);
785 
786 	pi->pi_msix.table_bar = barnum;
787 	pi->pi_msix.pba_bar   = barnum;
788 	pi->pi_msix.table_offset = 0;
789 	pi->pi_msix.table_count = msgnum;
790 	pi->pi_msix.pba_offset = tab_size;
791 
792 	/* calculate the MMIO size required for MSI-X PBA */
793 	pba_index = (msgnum - 1) / (PBA_TABLE_ENTRY_SIZE * 8);
794 	pi->pi_msix.pba_size = (pba_index + 1) * PBA_TABLE_ENTRY_SIZE;
795 
796 	pci_msix_table_init(pi, msgnum);
797 
798 	pci_populate_msixcap(&msixcap, msgnum, barnum, tab_size, 0);
799 
800 	/* allocate memory for MSI-X Table and PBA */
801 	pci_emul_alloc_bar(pi, barnum, PCIBAR_MEM32,
802 				tab_size + pi->pi_msix.pba_size);
803 
804 	return (pci_emul_add_capability(pi, (u_char *)&msixcap,
805 					sizeof(msixcap)));
806 }
807 
808 void
809 msixcap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
810 		 int bytes, uint32_t val)
811 {
812 	uint16_t msgctrl, rwmask;
813 	int off, table_bar;
814 
815 	off = offset - capoff;
816 	table_bar = pi->pi_msix.table_bar;
817 	/* Message Control Register */
818 	if (off == 2 && bytes == 2) {
819 		rwmask = PCIM_MSIXCTRL_MSIX_ENABLE | PCIM_MSIXCTRL_FUNCTION_MASK;
820 		msgctrl = pci_get_cfgdata16(pi, offset);
821 		msgctrl &= ~rwmask;
822 		msgctrl |= val & rwmask;
823 		val = msgctrl;
824 
825 		pi->pi_msix.enabled = val & PCIM_MSIXCTRL_MSIX_ENABLE;
826 		pi->pi_msix.function_mask = val & PCIM_MSIXCTRL_FUNCTION_MASK;
827 	}
828 
829 	CFGWRITE(pi, offset, val, bytes);
830 }
831 
832 void
833 msicap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
834 		int bytes, uint32_t val)
835 {
836 	uint16_t msgctrl, rwmask, msgdata, mme;
837 	uint32_t addrlo;
838 
839 	/*
840 	 * If guest is writing to the message control register make sure
841 	 * we do not overwrite read-only fields.
842 	 */
843 	if ((offset - capoff) == 2 && bytes == 2) {
844 		rwmask = PCIM_MSICTRL_MME_MASK | PCIM_MSICTRL_MSI_ENABLE;
845 		msgctrl = pci_get_cfgdata16(pi, offset);
846 		msgctrl &= ~rwmask;
847 		msgctrl |= val & rwmask;
848 		val = msgctrl;
849 
850 		addrlo = pci_get_cfgdata32(pi, capoff + 4);
851 		if (msgctrl & PCIM_MSICTRL_64BIT)
852 			msgdata = pci_get_cfgdata16(pi, capoff + 12);
853 		else
854 			msgdata = pci_get_cfgdata16(pi, capoff + 8);
855 
856 		/*
857 		 * XXX check delivery mode, destination mode etc
858 		 */
859 		mme = msgctrl & PCIM_MSICTRL_MME_MASK;
860 		pi->pi_msi.enabled = msgctrl & PCIM_MSICTRL_MSI_ENABLE ? 1 : 0;
861 		if (pi->pi_msi.enabled) {
862 			pi->pi_msi.cpu = (addrlo >> 12) & 0xff;
863 			pi->pi_msi.vector = msgdata & 0xff;
864 			pi->pi_msi.msgnum = 1 << (mme >> 4);
865 		} else {
866 			pi->pi_msi.cpu = 0;
867 			pi->pi_msi.vector = 0;
868 			pi->pi_msi.msgnum = 0;
869 		}
870 	}
871 
872 	CFGWRITE(pi, offset, val, bytes);
873 }
874 
875 void
876 pciecap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
877 		 int bytes, uint32_t val)
878 {
879 
880 	/* XXX don't write to the readonly parts */
881 	CFGWRITE(pi, offset, val, bytes);
882 }
883 
884 #define	PCIECAP_VERSION	0x2
885 int
886 pci_emul_add_pciecap(struct pci_devinst *pi, int type)
887 {
888 	int err;
889 	struct pciecap pciecap;
890 
891 	CTASSERT(sizeof(struct pciecap) == 60);
892 
893 	if (type != PCIEM_TYPE_ROOT_PORT)
894 		return (-1);
895 
896 	bzero(&pciecap, sizeof(pciecap));
897 
898 	pciecap.capid = PCIY_EXPRESS;
899 	pciecap.pcie_capabilities = PCIECAP_VERSION | PCIEM_TYPE_ROOT_PORT;
900 	pciecap.link_capabilities = 0x411;	/* gen1, x1 */
901 	pciecap.link_status = 0x11;		/* gen1, x1 */
902 
903 	err = pci_emul_add_capability(pi, (u_char *)&pciecap, sizeof(pciecap));
904 	return (err);
905 }
906 
907 /*
908  * This function assumes that 'coff' is in the capabilities region of the
909  * config space.
910  */
911 static void
912 pci_emul_capwrite(struct pci_devinst *pi, int offset, int bytes, uint32_t val)
913 {
914 	int capid;
915 	uint8_t capoff, nextoff;
916 
917 	/* Do not allow un-aligned writes */
918 	if ((offset & (bytes - 1)) != 0)
919 		return;
920 
921 	/* Find the capability that we want to update */
922 	capoff = CAP_START_OFFSET;
923 	while (1) {
924 		capid = pci_get_cfgdata8(pi, capoff);
925 		if (capid == PCIY_RESERVED)
926 			break;
927 
928 		nextoff = pci_get_cfgdata8(pi, capoff + 1);
929 		if (offset >= capoff && offset < nextoff)
930 			break;
931 
932 		capoff = nextoff;
933 	}
934 	assert(offset >= capoff);
935 
936 	/*
937 	 * Capability ID and Next Capability Pointer are readonly
938 	 */
939 	if (offset == capoff || offset == capoff + 1)
940 		return;
941 
942 	switch (capid) {
943 	case PCIY_MSI:
944 		msicap_cfgwrite(pi, capoff, offset, bytes, val);
945 		break;
946 	case PCIY_MSIX:
947 		msixcap_cfgwrite(pi, capoff, offset, bytes, val);
948 		break;
949 	case PCIY_EXPRESS:
950 		pciecap_cfgwrite(pi, capoff, offset, bytes, val);
951 		break;
952 	default:
953 		break;
954 	}
955 }
956 
957 static int
958 pci_emul_iscap(struct pci_devinst *pi, int offset)
959 {
960 	int found;
961 	uint16_t sts;
962 	uint8_t capid, lastoff;
963 
964 	found = 0;
965 	sts = pci_get_cfgdata16(pi, PCIR_STATUS);
966 	if ((sts & PCIM_STATUS_CAPPRESENT) != 0) {
967 		lastoff = pci_get_cfgdata8(pi, PCIR_CAP_PTR);
968 		while (1) {
969 			assert((lastoff & 0x3) == 0);
970 			capid = pci_get_cfgdata8(pi, lastoff);
971 			if (capid == PCIY_RESERVED)
972 				break;
973 			lastoff = pci_get_cfgdata8(pi, lastoff + 1);
974 		}
975 		if (offset >= CAP_START_OFFSET && offset <= lastoff)
976 			found = 1;
977 	}
978 	return (found);
979 }
980 
981 static int
982 pci_emul_fallback_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
983 			  int size, uint64_t *val, void *arg1, long arg2)
984 {
985 	/*
986 	 * Ignore writes; return 0xff's for reads. The mem read code
987 	 * will take care of truncating to the correct size.
988 	 */
989 	if (dir == MEM_F_READ) {
990 		*val = 0xffffffffffffffff;
991 	}
992 
993 	return (0);
994 }
995 
996 void
997 init_pci(struct vmctx *ctx)
998 {
999 	struct mem_range memp;
1000 	struct pci_devemu *pde;
1001 	struct slotinfo *si;
1002 	size_t lowmem;
1003 	int slot, func;
1004 	int error;
1005 
1006 	pci_emul_iobase = PCI_EMUL_IOBASE;
1007 	pci_emul_membase32 = vm_get_lowmem_limit(ctx);
1008 	pci_emul_membase64 = PCI_EMUL_MEMBASE64;
1009 
1010 	for (slot = 0; slot < MAXSLOTS; slot++) {
1011 		for (func = 0; func < MAXFUNCS; func++) {
1012 			si = &pci_slotinfo[slot][func];
1013 			if (si->si_name != NULL) {
1014 				pde = pci_emul_finddev(si->si_name);
1015 				assert(pde != NULL);
1016 				pci_emul_init(ctx, pde, slot, func,
1017 					      si->si_param);
1018 			}
1019 		}
1020 	}
1021 
1022 	/*
1023 	 * Allow ISA IRQs 5,10,11,12, and 15 to be available for
1024 	 * generic use
1025 	 */
1026 	lirq[5].li_generic = 1;
1027 	lirq[10].li_generic = 1;
1028 	lirq[11].li_generic = 1;
1029 	lirq[12].li_generic = 1;
1030 	lirq[15].li_generic = 1;
1031 
1032 	/*
1033 	 * The guest physical memory map looks like the following:
1034 	 * [0,		    lowmem)		guest system memory
1035 	 * [lowmem,	    lowmem_limit)	memory hole (may be absent)
1036 	 * [lowmem_limit,   4GB)		PCI hole (32-bit BAR allocation)
1037 	 * [4GB,	    4GB + highmem)
1038 	 *
1039 	 * Accesses to memory addresses that are not allocated to system
1040 	 * memory or PCI devices return 0xff's.
1041 	 */
1042 	error = vm_get_memory_seg(ctx, 0, &lowmem);
1043 	assert(error == 0);
1044 
1045 	memset(&memp, 0, sizeof(struct mem_range));
1046 	memp.name = "PCI hole";
1047 	memp.flags = MEM_F_RW;
1048 	memp.base = lowmem;
1049 	memp.size = (4ULL * 1024 * 1024 * 1024) - lowmem;
1050 	memp.handler = pci_emul_fallback_handler;
1051 
1052 	error = register_mem_fallback(&memp);
1053 	assert(error == 0);
1054 }
1055 
1056 int
1057 pci_msi_enabled(struct pci_devinst *pi)
1058 {
1059 	return (pi->pi_msi.enabled);
1060 }
1061 
1062 int
1063 pci_msi_msgnum(struct pci_devinst *pi)
1064 {
1065 	if (pi->pi_msi.enabled)
1066 		return (pi->pi_msi.msgnum);
1067 	else
1068 		return (0);
1069 }
1070 
1071 int
1072 pci_msix_enabled(struct pci_devinst *pi)
1073 {
1074 
1075 	return (pi->pi_msix.enabled && !pi->pi_msi.enabled);
1076 }
1077 
1078 void
1079 pci_generate_msix(struct pci_devinst *pi, int index)
1080 {
1081 	struct msix_table_entry *mte;
1082 
1083 	if (!pci_msix_enabled(pi))
1084 		return;
1085 
1086 	if (pi->pi_msix.function_mask)
1087 		return;
1088 
1089 	if (index >= pi->pi_msix.table_count)
1090 		return;
1091 
1092 	mte = &pi->pi_msix.table[index];
1093 	if ((mte->vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
1094 		/* XXX Set PBA bit if interrupt is disabled */
1095 		vm_lapic_irq(pi->pi_vmctx,
1096 			     (mte->addr >> 12) & 0xff, mte->msg_data & 0xff);
1097 	}
1098 }
1099 
1100 void
1101 pci_generate_msi(struct pci_devinst *pi, int msg)
1102 {
1103 
1104 	if (pci_msi_enabled(pi) && msg < pci_msi_msgnum(pi)) {
1105 		vm_lapic_irq(pi->pi_vmctx,
1106 			     pi->pi_msi.cpu,
1107 			     pi->pi_msi.vector + msg);
1108 	}
1109 }
1110 
1111 int
1112 pci_is_legacy(struct pci_devinst *pi)
1113 {
1114 
1115 	return (pci_slotinfo[pi->pi_slot][pi->pi_func].si_legacy);
1116 }
1117 
1118 static int
1119 pci_lintr_alloc(struct pci_devinst *pi, int vec)
1120 {
1121 	int i;
1122 
1123 	assert(vec < NLIRQ);
1124 
1125 	if (vec == -1) {
1126 		for (i = 0; i < NLIRQ; i++) {
1127 			if (lirq[i].li_generic &&
1128 			    lirq[i].li_owner == NULL) {
1129 				vec = i;
1130 				break;
1131 			}
1132 		}
1133 	} else {
1134 		if (lirq[vec].li_owner != NULL) {
1135 			vec = -1;
1136 		}
1137 	}
1138 	assert(vec != -1);
1139 
1140 	lirq[vec].li_owner = pi;
1141 	pi->pi_lintr_pin = vec;
1142 
1143 	return (vec);
1144 }
1145 
1146 int
1147 pci_lintr_request(struct pci_devinst *pi, int vec)
1148 {
1149 
1150 	vec = pci_lintr_alloc(pi, vec);
1151 	pci_set_cfgdata8(pi, PCIR_INTLINE, vec);
1152 	pci_set_cfgdata8(pi, PCIR_INTPIN, 1);
1153 	return (0);
1154 }
1155 
1156 void
1157 pci_lintr_assert(struct pci_devinst *pi)
1158 {
1159 
1160 	assert(pi->pi_lintr_pin);
1161 	ioapic_assert_pin(pi->pi_vmctx, pi->pi_lintr_pin);
1162 }
1163 
1164 void
1165 pci_lintr_deassert(struct pci_devinst *pi)
1166 {
1167 
1168 	assert(pi->pi_lintr_pin);
1169 	ioapic_deassert_pin(pi->pi_vmctx, pi->pi_lintr_pin);
1170 }
1171 
1172 /*
1173  * Return 1 if the emulated device in 'slot' is a multi-function device.
1174  * Return 0 otherwise.
1175  */
1176 static int
1177 pci_emul_is_mfdev(int slot)
1178 {
1179 	int f, numfuncs;
1180 
1181 	numfuncs = 0;
1182 	for (f = 0; f < MAXFUNCS; f++) {
1183 		if (pci_slotinfo[slot][f].si_devi != NULL) {
1184 			numfuncs++;
1185 		}
1186 	}
1187 	return (numfuncs > 1);
1188 }
1189 
1190 /*
1191  * Ensure that the PCIM_MFDEV bit is properly set (or unset) depending on
1192  * whether or not is a multi-function being emulated in the pci 'slot'.
1193  */
1194 static void
1195 pci_emul_hdrtype_fixup(int slot, int off, int bytes, uint32_t *rv)
1196 {
1197 	int mfdev;
1198 
1199 	if (off <= PCIR_HDRTYPE && off + bytes > PCIR_HDRTYPE) {
1200 		mfdev = pci_emul_is_mfdev(slot);
1201 		switch (bytes) {
1202 		case 1:
1203 		case 2:
1204 			*rv &= ~PCIM_MFDEV;
1205 			if (mfdev) {
1206 				*rv |= PCIM_MFDEV;
1207 			}
1208 			break;
1209 		case 4:
1210 			*rv &= ~(PCIM_MFDEV << 16);
1211 			if (mfdev) {
1212 				*rv |= (PCIM_MFDEV << 16);
1213 			}
1214 			break;
1215 		}
1216 	}
1217 }
1218 
1219 static int cfgbus, cfgslot, cfgfunc, cfgoff;
1220 
1221 static int
1222 pci_emul_cfgaddr(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1223 		 uint32_t *eax, void *arg)
1224 {
1225 	uint32_t x;
1226 
1227 	assert(!in);
1228 
1229 	if (bytes != 4)
1230 		return (-1);
1231 
1232 	x = *eax;
1233 	cfgoff = x & PCI_REGMAX;
1234 	cfgfunc = (x >> 8) & PCI_FUNCMAX;
1235 	cfgslot = (x >> 11) & PCI_SLOTMAX;
1236 	cfgbus = (x >> 16) & PCI_BUSMAX;
1237 
1238 	return (0);
1239 }
1240 INOUT_PORT(pci_cfgaddr, CONF1_ADDR_PORT, IOPORT_F_OUT, pci_emul_cfgaddr);
1241 
1242 static uint32_t
1243 bits_changed(uint32_t old, uint32_t new, uint32_t mask)
1244 {
1245 
1246 	return ((old ^ new) & mask);
1247 }
1248 
1249 static void
1250 pci_emul_cmdwrite(struct pci_devinst *pi, uint32_t new, int bytes)
1251 {
1252 	int i;
1253 	uint16_t old;
1254 
1255 	/*
1256 	 * The command register is at an offset of 4 bytes and thus the
1257 	 * guest could write 1, 2 or 4 bytes starting at this offset.
1258 	 */
1259 
1260 	old = pci_get_cfgdata16(pi, PCIR_COMMAND);	/* stash old value */
1261 	CFGWRITE(pi, PCIR_COMMAND, new, bytes);		/* update config */
1262 	new = pci_get_cfgdata16(pi, PCIR_COMMAND);	/* get updated value */
1263 
1264 	/*
1265 	 * If the MMIO or I/O address space decoding has changed then
1266 	 * register/unregister all BARs that decode that address space.
1267 	 */
1268 	for (i = 0; i < PCI_BARMAX; i++) {
1269 		switch (pi->pi_bar[i].type) {
1270 			case PCIBAR_NONE:
1271 			case PCIBAR_MEMHI64:
1272 				break;
1273 			case PCIBAR_IO:
1274 				/* I/O address space decoding changed? */
1275 				if (bits_changed(old, new, PCIM_CMD_PORTEN)) {
1276 					if (porten(pi))
1277 						register_bar(pi, i);
1278 					else
1279 						unregister_bar(pi, i);
1280 				}
1281 				break;
1282 			case PCIBAR_MEM32:
1283 			case PCIBAR_MEM64:
1284 				/* MMIO address space decoding changed? */
1285 				if (bits_changed(old, new, PCIM_CMD_MEMEN)) {
1286 					if (memen(pi))
1287 						register_bar(pi, i);
1288 					else
1289 						unregister_bar(pi, i);
1290 				}
1291 				break;
1292 			default:
1293 				assert(0);
1294 		}
1295 	}
1296 }
1297 
1298 static int
1299 pci_emul_cfgdata(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1300 		 uint32_t *eax, void *arg)
1301 {
1302 	struct pci_devinst *pi;
1303 	struct pci_devemu *pe;
1304 	int coff, idx, needcfg;
1305 	uint64_t addr, bar, mask;
1306 
1307 	assert(bytes == 1 || bytes == 2 || bytes == 4);
1308 
1309 	if (cfgbus == 0)
1310 		pi = pci_slotinfo[cfgslot][cfgfunc].si_devi;
1311 	else
1312 		pi = NULL;
1313 
1314 	coff = cfgoff + (port - CONF1_DATA_PORT);
1315 
1316 #if 0
1317 	printf("pcicfg-%s from 0x%0x of %d bytes (%d/%d/%d)\n\r",
1318 		in ? "read" : "write", coff, bytes, cfgbus, cfgslot, cfgfunc);
1319 #endif
1320 
1321 	/*
1322 	 * Just return if there is no device at this cfgslot:cfgfunc or
1323 	 * if the guest is doing an un-aligned access
1324 	 */
1325 	if (pi == NULL || (coff & (bytes - 1)) != 0) {
1326 		if (in)
1327 			*eax = 0xffffffff;
1328 		return (0);
1329 	}
1330 
1331 	pe = pi->pi_d;
1332 
1333 	/*
1334 	 * Config read
1335 	 */
1336 	if (in) {
1337 		/* Let the device emulation override the default handler */
1338 		if (pe->pe_cfgread != NULL) {
1339 			needcfg = pe->pe_cfgread(ctx, vcpu, pi,
1340 						    coff, bytes, eax);
1341 		} else {
1342 			needcfg = 1;
1343 		}
1344 
1345 		if (needcfg) {
1346 			if (bytes == 1)
1347 				*eax = pci_get_cfgdata8(pi, coff);
1348 			else if (bytes == 2)
1349 				*eax = pci_get_cfgdata16(pi, coff);
1350 			else
1351 				*eax = pci_get_cfgdata32(pi, coff);
1352 		}
1353 
1354 		pci_emul_hdrtype_fixup(cfgslot, coff, bytes, eax);
1355 	} else {
1356 		/* Let the device emulation override the default handler */
1357 		if (pe->pe_cfgwrite != NULL &&
1358 		    (*pe->pe_cfgwrite)(ctx, vcpu, pi, coff, bytes, *eax) == 0)
1359 			return (0);
1360 
1361 		/*
1362 		 * Special handling for write to BAR registers
1363 		 */
1364 		if (coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1)) {
1365 			/*
1366 			 * Ignore writes to BAR registers that are not
1367 			 * 4-byte aligned.
1368 			 */
1369 			if (bytes != 4 || (coff & 0x3) != 0)
1370 				return (0);
1371 			idx = (coff - PCIR_BAR(0)) / 4;
1372 			mask = ~(pi->pi_bar[idx].size - 1);
1373 			switch (pi->pi_bar[idx].type) {
1374 			case PCIBAR_NONE:
1375 				pi->pi_bar[idx].addr = bar = 0;
1376 				break;
1377 			case PCIBAR_IO:
1378 				addr = *eax & mask;
1379 				addr &= 0xffff;
1380 				bar = addr | PCIM_BAR_IO_SPACE;
1381 				/*
1382 				 * Register the new BAR value for interception
1383 				 */
1384 				if (addr != pi->pi_bar[idx].addr) {
1385 					update_bar_address(pi, addr, idx,
1386 							   PCIBAR_IO);
1387 				}
1388 				break;
1389 			case PCIBAR_MEM32:
1390 				addr = bar = *eax & mask;
1391 				bar |= PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
1392 				if (addr != pi->pi_bar[idx].addr) {
1393 					update_bar_address(pi, addr, idx,
1394 							   PCIBAR_MEM32);
1395 				}
1396 				break;
1397 			case PCIBAR_MEM64:
1398 				addr = bar = *eax & mask;
1399 				bar |= PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
1400 				       PCIM_BAR_MEM_PREFETCH;
1401 				if (addr != (uint32_t)pi->pi_bar[idx].addr) {
1402 					update_bar_address(pi, addr, idx,
1403 							   PCIBAR_MEM64);
1404 				}
1405 				break;
1406 			case PCIBAR_MEMHI64:
1407 				mask = ~(pi->pi_bar[idx - 1].size - 1);
1408 				addr = ((uint64_t)*eax << 32) & mask;
1409 				bar = addr >> 32;
1410 				if (bar != pi->pi_bar[idx - 1].addr >> 32) {
1411 					update_bar_address(pi, addr, idx - 1,
1412 							   PCIBAR_MEMHI64);
1413 				}
1414 				break;
1415 			default:
1416 				assert(0);
1417 			}
1418 			pci_set_cfgdata32(pi, coff, bar);
1419 
1420 		} else if (pci_emul_iscap(pi, coff)) {
1421 			pci_emul_capwrite(pi, coff, bytes, *eax);
1422 		} else if (coff == PCIR_COMMAND) {
1423 			pci_emul_cmdwrite(pi, *eax, bytes);
1424 		} else {
1425 			CFGWRITE(pi, coff, *eax, bytes);
1426 		}
1427 	}
1428 
1429 	return (0);
1430 }
1431 
1432 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+0, IOPORT_F_INOUT, pci_emul_cfgdata);
1433 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+1, IOPORT_F_INOUT, pci_emul_cfgdata);
1434 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+2, IOPORT_F_INOUT, pci_emul_cfgdata);
1435 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+3, IOPORT_F_INOUT, pci_emul_cfgdata);
1436 
1437 /*
1438  * I/O ports to configure PCI IRQ routing. We ignore all writes to it.
1439  */
1440 static int
1441 pci_irq_port_handler(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1442 		     uint32_t *eax, void *arg)
1443 {
1444 	assert(in == 0);
1445 	return (0);
1446 }
1447 INOUT_PORT(pci_irq, 0xC00, IOPORT_F_OUT, pci_irq_port_handler);
1448 INOUT_PORT(pci_irq, 0xC01, IOPORT_F_OUT, pci_irq_port_handler);
1449 
1450 #define PCI_EMUL_TEST
1451 #ifdef PCI_EMUL_TEST
1452 /*
1453  * Define a dummy test device
1454  */
1455 #define DIOSZ	20
1456 #define DMEMSZ	4096
1457 struct pci_emul_dsoftc {
1458 	uint8_t   ioregs[DIOSZ];
1459 	uint8_t	  memregs[DMEMSZ];
1460 };
1461 
1462 #define	PCI_EMUL_MSI_MSGS	 4
1463 #define	PCI_EMUL_MSIX_MSGS	16
1464 
1465 static int
1466 pci_emul_dinit(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
1467 {
1468 	int error;
1469 	struct pci_emul_dsoftc *sc;
1470 
1471 	sc = malloc(sizeof(struct pci_emul_dsoftc));
1472 	memset(sc, 0, sizeof(struct pci_emul_dsoftc));
1473 
1474 	pi->pi_arg = sc;
1475 
1476 	pci_set_cfgdata16(pi, PCIR_DEVICE, 0x0001);
1477 	pci_set_cfgdata16(pi, PCIR_VENDOR, 0x10DD);
1478 	pci_set_cfgdata8(pi, PCIR_CLASS, 0x02);
1479 
1480 	error = pci_emul_add_msicap(pi, PCI_EMUL_MSI_MSGS);
1481 	assert(error == 0);
1482 
1483 	error = pci_emul_alloc_bar(pi, 0, PCIBAR_IO, DIOSZ);
1484 	assert(error == 0);
1485 
1486 	error = pci_emul_alloc_bar(pi, 1, PCIBAR_MEM32, DMEMSZ);
1487 	assert(error == 0);
1488 
1489 	return (0);
1490 }
1491 
1492 static void
1493 pci_emul_diow(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
1494 	      uint64_t offset, int size, uint64_t value)
1495 {
1496 	int i;
1497 	struct pci_emul_dsoftc *sc = pi->pi_arg;
1498 
1499 	if (baridx == 0) {
1500 		if (offset + size > DIOSZ) {
1501 			printf("diow: iow too large, offset %ld size %d\n",
1502 			       offset, size);
1503 			return;
1504 		}
1505 
1506 		if (size == 1) {
1507 			sc->ioregs[offset] = value & 0xff;
1508 		} else if (size == 2) {
1509 			*(uint16_t *)&sc->ioregs[offset] = value & 0xffff;
1510 		} else if (size == 4) {
1511 			*(uint32_t *)&sc->ioregs[offset] = value;
1512 		} else {
1513 			printf("diow: iow unknown size %d\n", size);
1514 		}
1515 
1516 		/*
1517 		 * Special magic value to generate an interrupt
1518 		 */
1519 		if (offset == 4 && size == 4 && pci_msi_enabled(pi))
1520 			pci_generate_msi(pi, value % pci_msi_msgnum(pi));
1521 
1522 		if (value == 0xabcdef) {
1523 			for (i = 0; i < pci_msi_msgnum(pi); i++)
1524 				pci_generate_msi(pi, i);
1525 		}
1526 	}
1527 
1528 	if (baridx == 1) {
1529 		if (offset + size > DMEMSZ) {
1530 			printf("diow: memw too large, offset %ld size %d\n",
1531 			       offset, size);
1532 			return;
1533 		}
1534 
1535 		if (size == 1) {
1536 			sc->memregs[offset] = value;
1537 		} else if (size == 2) {
1538 			*(uint16_t *)&sc->memregs[offset] = value;
1539 		} else if (size == 4) {
1540 			*(uint32_t *)&sc->memregs[offset] = value;
1541 		} else if (size == 8) {
1542 			*(uint64_t *)&sc->memregs[offset] = value;
1543 		} else {
1544 			printf("diow: memw unknown size %d\n", size);
1545 		}
1546 
1547 		/*
1548 		 * magic interrupt ??
1549 		 */
1550 	}
1551 
1552 	if (baridx > 1) {
1553 		printf("diow: unknown bar idx %d\n", baridx);
1554 	}
1555 }
1556 
1557 static uint64_t
1558 pci_emul_dior(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
1559 	      uint64_t offset, int size)
1560 {
1561 	struct pci_emul_dsoftc *sc = pi->pi_arg;
1562 	uint32_t value;
1563 
1564 	if (baridx == 0) {
1565 		if (offset + size > DIOSZ) {
1566 			printf("dior: ior too large, offset %ld size %d\n",
1567 			       offset, size);
1568 			return (0);
1569 		}
1570 
1571 		if (size == 1) {
1572 			value = sc->ioregs[offset];
1573 		} else if (size == 2) {
1574 			value = *(uint16_t *) &sc->ioregs[offset];
1575 		} else if (size == 4) {
1576 			value = *(uint32_t *) &sc->ioregs[offset];
1577 		} else {
1578 			printf("dior: ior unknown size %d\n", size);
1579 		}
1580 	}
1581 
1582 	if (baridx == 1) {
1583 		if (offset + size > DMEMSZ) {
1584 			printf("dior: memr too large, offset %ld size %d\n",
1585 			       offset, size);
1586 			return (0);
1587 		}
1588 
1589 		if (size == 1) {
1590 			value = sc->memregs[offset];
1591 		} else if (size == 2) {
1592 			value = *(uint16_t *) &sc->memregs[offset];
1593 		} else if (size == 4) {
1594 			value = *(uint32_t *) &sc->memregs[offset];
1595 		} else if (size == 8) {
1596 			value = *(uint64_t *) &sc->memregs[offset];
1597 		} else {
1598 			printf("dior: ior unknown size %d\n", size);
1599 		}
1600 	}
1601 
1602 
1603 	if (baridx > 1) {
1604 		printf("dior: unknown bar idx %d\n", baridx);
1605 		return (0);
1606 	}
1607 
1608 	return (value);
1609 }
1610 
1611 struct pci_devemu pci_dummy = {
1612 	.pe_emu = "dummy",
1613 	.pe_init = pci_emul_dinit,
1614 	.pe_barwrite = pci_emul_diow,
1615 	.pe_barread = pci_emul_dior
1616 };
1617 PCI_EMUL_SET(pci_dummy);
1618 
1619 #endif /* PCI_EMUL_TEST */
1620