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