xref: /illumos-gate/usr/src/cmd/bhyve/pci_emul.c (revision 84659b24a533984de271059abf9a1092835d15a9)
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  * This file and its contents are supplied under the terms of the
32  * Common Development and Distribution License ("CDDL"), version 1.0.
33  * You may only use this file in accordance with the terms of version
34  * 1.0 of the CDDL.
35  *
36  * A full copy of the text of the CDDL should have accompanied this
37  * source.  A copy of the CDDL is also available via the Internet at
38  * http://www.illumos.org/license/CDDL.
39  *
40  * Copyright 2014 Pluribus Networks Inc.
41  * Copyright 2018 Joyent, Inc.
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include <sys/param.h>
48 #include <sys/linker_set.h>
49 
50 #include <ctype.h>
51 #include <errno.h>
52 #include <pthread.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <strings.h>
57 #include <assert.h>
58 #include <stdbool.h>
59 
60 #include <machine/vmm.h>
61 #include <vmmapi.h>
62 
63 #include "acpi.h"
64 #include "bhyverun.h"
65 #include "inout.h"
66 #include "ioapic.h"
67 #include "mem.h"
68 #include "pci_emul.h"
69 #include "pci_irq.h"
70 #include "pci_lpc.h"
71 
72 #define CONF1_ADDR_PORT	   0x0cf8
73 #define CONF1_DATA_PORT	   0x0cfc
74 
75 #define CONF1_ENABLE	   0x80000000ul
76 
77 #define	MAXBUSES	(PCI_BUSMAX + 1)
78 #define MAXSLOTS	(PCI_SLOTMAX + 1)
79 #define	MAXFUNCS	(PCI_FUNCMAX + 1)
80 
81 struct funcinfo {
82 	char	*fi_name;
83 	char	*fi_param;
84 	struct pci_devinst *fi_devi;
85 };
86 
87 struct intxinfo {
88 	int	ii_count;
89 	int	ii_pirq_pin;
90 	int	ii_ioapic_irq;
91 };
92 
93 struct slotinfo {
94 	struct intxinfo si_intpins[4];
95 	struct funcinfo si_funcs[MAXFUNCS];
96 };
97 
98 struct businfo {
99 	uint16_t iobase, iolimit;		/* I/O window */
100 	uint32_t membase32, memlimit32;		/* mmio window below 4GB */
101 	uint64_t membase64, memlimit64;		/* mmio window above 4GB */
102 	struct slotinfo slotinfo[MAXSLOTS];
103 };
104 
105 static struct businfo *pci_businfo[MAXBUSES];
106 
107 SET_DECLARE(pci_devemu_set, struct pci_devemu);
108 
109 static uint64_t pci_emul_iobase;
110 static uint64_t pci_emul_membase32;
111 static uint64_t pci_emul_membase64;
112 
113 #define	PCI_EMUL_IOBASE		0x2000
114 #define	PCI_EMUL_IOLIMIT	0x10000
115 
116 #define	PCI_EMUL_ECFG_BASE	0xE0000000		    /* 3.5GB */
117 #define	PCI_EMUL_ECFG_SIZE	(MAXBUSES * 1024 * 1024)    /* 1MB per bus */
118 SYSRES_MEM(PCI_EMUL_ECFG_BASE, PCI_EMUL_ECFG_SIZE);
119 
120 #define	PCI_EMUL_MEMLIMIT32	PCI_EMUL_ECFG_BASE
121 
122 #define	PCI_EMUL_MEMBASE64	0xD000000000UL
123 #define	PCI_EMUL_MEMLIMIT64	0xFD00000000UL
124 
125 static struct pci_devemu *pci_emul_finddev(char *name);
126 static void pci_lintr_route(struct pci_devinst *pi);
127 static void pci_lintr_update(struct pci_devinst *pi);
128 static void pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot,
129     int func, int coff, int bytes, uint32_t *val);
130 
131 static __inline void
132 CFGWRITE(struct pci_devinst *pi, int coff, uint32_t val, int bytes)
133 {
134 
135 	if (bytes == 1)
136 		pci_set_cfgdata8(pi, coff, val);
137 	else if (bytes == 2)
138 		pci_set_cfgdata16(pi, coff, val);
139 	else
140 		pci_set_cfgdata32(pi, coff, val);
141 }
142 
143 static __inline uint32_t
144 CFGREAD(struct pci_devinst *pi, int coff, int bytes)
145 {
146 
147 	if (bytes == 1)
148 		return (pci_get_cfgdata8(pi, coff));
149 	else if (bytes == 2)
150 		return (pci_get_cfgdata16(pi, coff));
151 	else
152 		return (pci_get_cfgdata32(pi, coff));
153 }
154 
155 /*
156  * I/O access
157  */
158 
159 /*
160  * Slot options are in the form:
161  *
162  *  <bus>:<slot>:<func>,<emul>[,<config>]
163  *  <slot>[:<func>],<emul>[,<config>]
164  *
165  *  slot is 0..31
166  *  func is 0..7
167  *  emul is a string describing the type of PCI device e.g. virtio-net
168  *  config is an optional string, depending on the device, that can be
169  *  used for configuration.
170  *   Examples are:
171  *     1,virtio-net,tap0
172  *     3:0,dummy
173  */
174 static void
175 pci_parse_slot_usage(char *aopt)
176 {
177 
178 	fprintf(stderr, "Invalid PCI slot info field \"%s\"\n", aopt);
179 }
180 
181 int
182 pci_parse_slot(char *opt)
183 {
184 	struct businfo *bi;
185 	struct slotinfo *si;
186 	char *emul, *config, *str, *cp;
187 	int error, bnum, snum, fnum;
188 
189 	error = -1;
190 	str = strdup(opt);
191 
192 	emul = config = NULL;
193 	if ((cp = strchr(str, ',')) != NULL) {
194 		*cp = '\0';
195 		emul = cp + 1;
196 		if ((cp = strchr(emul, ',')) != NULL) {
197 			*cp = '\0';
198 			config = cp + 1;
199 		}
200 	} else {
201 		pci_parse_slot_usage(opt);
202 		goto done;
203 	}
204 
205 	/* <bus>:<slot>:<func> */
206 	if (sscanf(str, "%d:%d:%d", &bnum, &snum, &fnum) != 3) {
207 		bnum = 0;
208 		/* <slot>:<func> */
209 		if (sscanf(str, "%d:%d", &snum, &fnum) != 2) {
210 			fnum = 0;
211 			/* <slot> */
212 			if (sscanf(str, "%d", &snum) != 1) {
213 				snum = -1;
214 			}
215 		}
216 	}
217 
218 	if (bnum < 0 || bnum >= MAXBUSES || snum < 0 || snum >= MAXSLOTS ||
219 	    fnum < 0 || fnum >= MAXFUNCS) {
220 		pci_parse_slot_usage(opt);
221 		goto done;
222 	}
223 
224 	if (pci_businfo[bnum] == NULL)
225 		pci_businfo[bnum] = calloc(1, sizeof(struct businfo));
226 
227 	bi = pci_businfo[bnum];
228 	si = &bi->slotinfo[snum];
229 
230 	if (si->si_funcs[fnum].fi_name != NULL) {
231 		fprintf(stderr, "pci slot %d:%d already occupied!\n",
232 			snum, fnum);
233 		goto done;
234 	}
235 
236 	if (pci_emul_finddev(emul) == NULL) {
237 		fprintf(stderr, "pci slot %d:%d: unknown device \"%s\"\n",
238 			snum, fnum, emul);
239 		goto done;
240 	}
241 
242 	error = 0;
243 	si->si_funcs[fnum].fi_name = emul;
244 	si->si_funcs[fnum].fi_param = config;
245 
246 done:
247 	if (error)
248 		free(str);
249 
250 	return (error);
251 }
252 
253 void
254 pci_print_supported_devices()
255 {
256 	struct pci_devemu **pdpp, *pdp;
257 
258 	SET_FOREACH(pdpp, pci_devemu_set) {
259 		pdp = *pdpp;
260 		printf("%s\n", pdp->pe_emu);
261 	}
262 }
263 
264 static int
265 pci_valid_pba_offset(struct pci_devinst *pi, uint64_t offset)
266 {
267 
268 	if (offset < pi->pi_msix.pba_offset)
269 		return (0);
270 
271 	if (offset >= pi->pi_msix.pba_offset + pi->pi_msix.pba_size) {
272 		return (0);
273 	}
274 
275 	return (1);
276 }
277 
278 int
279 pci_emul_msix_twrite(struct pci_devinst *pi, uint64_t offset, int size,
280 		     uint64_t value)
281 {
282 	int msix_entry_offset;
283 	int tab_index;
284 	char *dest;
285 
286 	/* support only 4 or 8 byte writes */
287 	if (size != 4 && size != 8)
288 		return (-1);
289 
290 	/*
291 	 * Return if table index is beyond what device supports
292 	 */
293 	tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
294 	if (tab_index >= pi->pi_msix.table_count)
295 		return (-1);
296 
297 	msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
298 
299 	/* support only aligned writes */
300 	if ((msix_entry_offset % size) != 0)
301 		return (-1);
302 
303 	dest = (char *)(pi->pi_msix.table + tab_index);
304 	dest += msix_entry_offset;
305 
306 	if (size == 4)
307 		*((uint32_t *)dest) = value;
308 	else
309 		*((uint64_t *)dest) = value;
310 
311 	return (0);
312 }
313 
314 uint64_t
315 pci_emul_msix_tread(struct pci_devinst *pi, uint64_t offset, int size)
316 {
317 	char *dest;
318 	int msix_entry_offset;
319 	int tab_index;
320 	uint64_t retval = ~0;
321 
322 	/*
323 	 * The PCI standard only allows 4 and 8 byte accesses to the MSI-X
324 	 * table but we also allow 1 byte access to accommodate reads from
325 	 * ddb.
326 	 */
327 	if (size != 1 && size != 4 && size != 8)
328 		return (retval);
329 
330 	msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
331 
332 	/* support only aligned reads */
333 	if ((msix_entry_offset % size) != 0) {
334 		return (retval);
335 	}
336 
337 	tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
338 
339 	if (tab_index < pi->pi_msix.table_count) {
340 		/* valid MSI-X Table access */
341 		dest = (char *)(pi->pi_msix.table + tab_index);
342 		dest += msix_entry_offset;
343 
344 		if (size == 1)
345 			retval = *((uint8_t *)dest);
346 		else if (size == 4)
347 			retval = *((uint32_t *)dest);
348 		else
349 			retval = *((uint64_t *)dest);
350 	} else if (pci_valid_pba_offset(pi, offset)) {
351 		/* return 0 for PBA access */
352 		retval = 0;
353 	}
354 
355 	return (retval);
356 }
357 
358 int
359 pci_msix_table_bar(struct pci_devinst *pi)
360 {
361 
362 	if (pi->pi_msix.table != NULL)
363 		return (pi->pi_msix.table_bar);
364 	else
365 		return (-1);
366 }
367 
368 int
369 pci_msix_pba_bar(struct pci_devinst *pi)
370 {
371 
372 	if (pi->pi_msix.table != NULL)
373 		return (pi->pi_msix.pba_bar);
374 	else
375 		return (-1);
376 }
377 
378 static int
379 pci_emul_io_handler(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
380 		    uint32_t *eax, void *arg)
381 {
382 	struct pci_devinst *pdi = arg;
383 	struct pci_devemu *pe = pdi->pi_d;
384 	uint64_t offset;
385 	int i;
386 
387 	for (i = 0; i <= PCI_BARMAX; i++) {
388 		if (pdi->pi_bar[i].type == PCIBAR_IO &&
389 		    port >= pdi->pi_bar[i].addr &&
390 		    port + bytes <= pdi->pi_bar[i].addr + pdi->pi_bar[i].size) {
391 			offset = port - pdi->pi_bar[i].addr;
392 			if (in)
393 				*eax = (*pe->pe_barread)(ctx, vcpu, pdi, i,
394 							 offset, bytes);
395 			else
396 				(*pe->pe_barwrite)(ctx, vcpu, pdi, i, offset,
397 						   bytes, *eax);
398 			return (0);
399 		}
400 	}
401 	return (-1);
402 }
403 
404 static int
405 pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
406 		     int size, uint64_t *val, void *arg1, long arg2)
407 {
408 	struct pci_devinst *pdi = arg1;
409 	struct pci_devemu *pe = pdi->pi_d;
410 	uint64_t offset;
411 	int bidx = (int) arg2;
412 
413 	assert(bidx <= PCI_BARMAX);
414 	assert(pdi->pi_bar[bidx].type == PCIBAR_MEM32 ||
415 	       pdi->pi_bar[bidx].type == PCIBAR_MEM64);
416 	assert(addr >= pdi->pi_bar[bidx].addr &&
417 	       addr + size <= pdi->pi_bar[bidx].addr + pdi->pi_bar[bidx].size);
418 
419 	offset = addr - pdi->pi_bar[bidx].addr;
420 
421 	if (dir == MEM_F_WRITE) {
422 		if (size == 8) {
423 			(*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset,
424 					   4, *val & 0xffffffff);
425 			(*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset + 4,
426 					   4, *val >> 32);
427 		} else {
428 			(*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset,
429 					   size, *val);
430 		}
431 	} else {
432 		if (size == 8) {
433 			*val = (*pe->pe_barread)(ctx, vcpu, pdi, bidx,
434 						 offset, 4);
435 			*val |= (*pe->pe_barread)(ctx, vcpu, pdi, bidx,
436 						  offset + 4, 4) << 32;
437 		} else {
438 			*val = (*pe->pe_barread)(ctx, vcpu, pdi, bidx,
439 						 offset, size);
440 		}
441 	}
442 
443 	return (0);
444 }
445 
446 
447 static int
448 pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,
449 			uint64_t *addr)
450 {
451 	uint64_t base;
452 
453 	assert((size & (size - 1)) == 0);	/* must be a power of 2 */
454 
455 	base = roundup2(*baseptr, size);
456 
457 	if (base + size <= limit) {
458 		*addr = base;
459 		*baseptr = base + size;
460 		return (0);
461 	} else
462 		return (-1);
463 }
464 
465 int
466 pci_emul_alloc_bar(struct pci_devinst *pdi, int idx, enum pcibar_type type,
467 		   uint64_t size)
468 {
469 
470 	return (pci_emul_alloc_pbar(pdi, idx, 0, type, size));
471 }
472 
473 /*
474  * Register (or unregister) the MMIO or I/O region associated with the BAR
475  * register 'idx' of an emulated pci device.
476  */
477 static void
478 modify_bar_registration(struct pci_devinst *pi, int idx, int registration)
479 {
480 	int error;
481 	struct inout_port iop;
482 	struct mem_range mr;
483 
484 	switch (pi->pi_bar[idx].type) {
485 	case PCIBAR_IO:
486 		bzero(&iop, sizeof(struct inout_port));
487 		iop.name = pi->pi_name;
488 		iop.port = pi->pi_bar[idx].addr;
489 		iop.size = pi->pi_bar[idx].size;
490 		if (registration) {
491 			iop.flags = IOPORT_F_INOUT;
492 			iop.handler = pci_emul_io_handler;
493 			iop.arg = pi;
494 			error = register_inout(&iop);
495 		} else
496 			error = unregister_inout(&iop);
497 		break;
498 	case PCIBAR_MEM32:
499 	case PCIBAR_MEM64:
500 		bzero(&mr, sizeof(struct mem_range));
501 		mr.name = pi->pi_name;
502 		mr.base = pi->pi_bar[idx].addr;
503 		mr.size = pi->pi_bar[idx].size;
504 		if (registration) {
505 			mr.flags = MEM_F_RW;
506 			mr.handler = pci_emul_mem_handler;
507 			mr.arg1 = pi;
508 			mr.arg2 = idx;
509 			error = register_mem(&mr);
510 		} else
511 			error = unregister_mem(&mr);
512 		break;
513 	default:
514 		error = EINVAL;
515 		break;
516 	}
517 	assert(error == 0);
518 }
519 
520 static void
521 unregister_bar(struct pci_devinst *pi, int idx)
522 {
523 
524 	modify_bar_registration(pi, idx, 0);
525 }
526 
527 static void
528 register_bar(struct pci_devinst *pi, int idx)
529 {
530 
531 	modify_bar_registration(pi, idx, 1);
532 }
533 
534 /* Are we decoding i/o port accesses for the emulated pci device? */
535 static int
536 porten(struct pci_devinst *pi)
537 {
538 	uint16_t cmd;
539 
540 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
541 
542 	return (cmd & PCIM_CMD_PORTEN);
543 }
544 
545 /* Are we decoding memory accesses for the emulated pci device? */
546 static int
547 memen(struct pci_devinst *pi)
548 {
549 	uint16_t cmd;
550 
551 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
552 
553 	return (cmd & PCIM_CMD_MEMEN);
554 }
555 
556 /*
557  * Update the MMIO or I/O address that is decoded by the BAR register.
558  *
559  * If the pci device has enabled the address space decoding then intercept
560  * the address range decoded by the BAR register.
561  */
562 static void
563 update_bar_address(struct pci_devinst *pi, uint64_t addr, int idx, int type)
564 {
565 	int decode;
566 
567 	if (pi->pi_bar[idx].type == PCIBAR_IO)
568 		decode = porten(pi);
569 	else
570 		decode = memen(pi);
571 
572 	if (decode)
573 		unregister_bar(pi, idx);
574 
575 	switch (type) {
576 	case PCIBAR_IO:
577 	case PCIBAR_MEM32:
578 		pi->pi_bar[idx].addr = addr;
579 		break;
580 	case PCIBAR_MEM64:
581 		pi->pi_bar[idx].addr &= ~0xffffffffUL;
582 		pi->pi_bar[idx].addr |= addr;
583 		break;
584 	case PCIBAR_MEMHI64:
585 		pi->pi_bar[idx].addr &= 0xffffffff;
586 		pi->pi_bar[idx].addr |= addr;
587 		break;
588 	default:
589 		assert(0);
590 	}
591 
592 	if (decode)
593 		register_bar(pi, idx);
594 }
595 
596 int
597 pci_emul_alloc_pbar(struct pci_devinst *pdi, int idx, uint64_t hostbase,
598 		    enum pcibar_type type, uint64_t size)
599 {
600 	uint64_t *baseptr = NULL;
601 	uint64_t limit = 0, lobits = 0;
602 	uint64_t addr, mask, bar;
603 	uint16_t cmd, enbit;
604 	int error;
605 
606 	assert(idx >= 0 && idx <= PCI_BARMAX);
607 
608 	if ((size & (size - 1)) != 0)
609 		size = 1UL << flsl(size);	/* round up to a power of 2 */
610 
611 	/* Enforce minimum BAR sizes required by the PCI standard */
612 	if (type == PCIBAR_IO) {
613 		if (size < 4)
614 			size = 4;
615 	} else {
616 		if (size < 16)
617 			size = 16;
618 	}
619 
620 	switch (type) {
621 	case PCIBAR_NONE:
622 		baseptr = NULL;
623 		addr = mask = lobits = enbit = 0;
624 		break;
625 	case PCIBAR_IO:
626 		baseptr = &pci_emul_iobase;
627 		limit = PCI_EMUL_IOLIMIT;
628 		mask = PCIM_BAR_IO_BASE;
629 		lobits = PCIM_BAR_IO_SPACE;
630 		enbit = PCIM_CMD_PORTEN;
631 		break;
632 	case PCIBAR_MEM64:
633 		/*
634 		 * XXX
635 		 * Some drivers do not work well if the 64-bit BAR is allocated
636 		 * above 4GB. Allow for this by allocating small requests under
637 		 * 4GB unless then allocation size is larger than some arbitrary
638 		 * number (32MB currently).
639 		 */
640 		if (size > 32 * 1024 * 1024) {
641 			/*
642 			 * XXX special case for device requiring peer-peer DMA
643 			 */
644 			if (size == 0x100000000UL)
645 				baseptr = &hostbase;
646 			else
647 				baseptr = &pci_emul_membase64;
648 			limit = PCI_EMUL_MEMLIMIT64;
649 			mask = PCIM_BAR_MEM_BASE;
650 			lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
651 				 PCIM_BAR_MEM_PREFETCH;
652 		} else {
653 			baseptr = &pci_emul_membase32;
654 			limit = PCI_EMUL_MEMLIMIT32;
655 			mask = PCIM_BAR_MEM_BASE;
656 			lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64;
657 		}
658 		enbit = PCIM_CMD_MEMEN;
659 		break;
660 	case PCIBAR_MEM32:
661 		baseptr = &pci_emul_membase32;
662 		limit = PCI_EMUL_MEMLIMIT32;
663 		mask = PCIM_BAR_MEM_BASE;
664 		lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
665 		enbit = PCIM_CMD_MEMEN;
666 		break;
667 	default:
668 		printf("pci_emul_alloc_base: invalid bar type %d\n", type);
669 #ifdef FreeBSD
670 		assert(0);
671 #else
672 		abort();
673 #endif
674 	}
675 
676 	if (baseptr != NULL) {
677 		error = pci_emul_alloc_resource(baseptr, limit, size, &addr);
678 		if (error != 0)
679 			return (error);
680 	}
681 
682 	pdi->pi_bar[idx].type = type;
683 	pdi->pi_bar[idx].addr = addr;
684 	pdi->pi_bar[idx].size = size;
685 
686 	/* Initialize the BAR register in config space */
687 	bar = (addr & mask) | lobits;
688 	pci_set_cfgdata32(pdi, PCIR_BAR(idx), bar);
689 
690 	if (type == PCIBAR_MEM64) {
691 		assert(idx + 1 <= PCI_BARMAX);
692 		pdi->pi_bar[idx + 1].type = PCIBAR_MEMHI64;
693 		pci_set_cfgdata32(pdi, PCIR_BAR(idx + 1), bar >> 32);
694 	}
695 
696 	cmd = pci_get_cfgdata16(pdi, PCIR_COMMAND);
697 	if ((cmd & enbit) != enbit)
698 		pci_set_cfgdata16(pdi, PCIR_COMMAND, cmd | enbit);
699 	register_bar(pdi, idx);
700 
701 	return (0);
702 }
703 
704 #define	CAP_START_OFFSET	0x40
705 static int
706 pci_emul_add_capability(struct pci_devinst *pi, u_char *capdata, int caplen)
707 {
708 	int i, capoff, reallen;
709 	uint16_t sts;
710 
711 	assert(caplen > 0);
712 
713 	reallen = roundup2(caplen, 4);		/* dword aligned */
714 
715 	sts = pci_get_cfgdata16(pi, PCIR_STATUS);
716 	if ((sts & PCIM_STATUS_CAPPRESENT) == 0)
717 		capoff = CAP_START_OFFSET;
718 	else
719 		capoff = pi->pi_capend + 1;
720 
721 	/* Check if we have enough space */
722 	if (capoff + reallen > PCI_REGMAX + 1)
723 		return (-1);
724 
725 	/* Set the previous capability pointer */
726 	if ((sts & PCIM_STATUS_CAPPRESENT) == 0) {
727 		pci_set_cfgdata8(pi, PCIR_CAP_PTR, capoff);
728 		pci_set_cfgdata16(pi, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT);
729 	} else
730 		pci_set_cfgdata8(pi, pi->pi_prevcap + 1, capoff);
731 
732 	/* Copy the capability */
733 	for (i = 0; i < caplen; i++)
734 		pci_set_cfgdata8(pi, capoff + i, capdata[i]);
735 
736 	/* Set the next capability pointer */
737 	pci_set_cfgdata8(pi, capoff + 1, 0);
738 
739 	pi->pi_prevcap = capoff;
740 	pi->pi_capend = capoff + reallen - 1;
741 	return (0);
742 }
743 
744 static struct pci_devemu *
745 pci_emul_finddev(char *name)
746 {
747 	struct pci_devemu **pdpp, *pdp;
748 
749 	SET_FOREACH(pdpp, pci_devemu_set) {
750 		pdp = *pdpp;
751 		if (!strcmp(pdp->pe_emu, name)) {
752 			return (pdp);
753 		}
754 	}
755 
756 	return (NULL);
757 }
758 
759 static int
760 pci_emul_init(struct vmctx *ctx, struct pci_devemu *pde, int bus, int slot,
761     int func, struct funcinfo *fi)
762 {
763 	struct pci_devinst *pdi;
764 	int err;
765 
766 	pdi = calloc(1, sizeof(struct pci_devinst));
767 
768 	pdi->pi_vmctx = ctx;
769 	pdi->pi_bus = bus;
770 	pdi->pi_slot = slot;
771 	pdi->pi_func = func;
772 	pthread_mutex_init(&pdi->pi_lintr.lock, NULL);
773 	pdi->pi_lintr.pin = 0;
774 	pdi->pi_lintr.state = IDLE;
775 	pdi->pi_lintr.pirq_pin = 0;
776 	pdi->pi_lintr.ioapic_irq = 0;
777 	pdi->pi_d = pde;
778 	snprintf(pdi->pi_name, PI_NAMESZ, "%s-pci-%d", pde->pe_emu, slot);
779 
780 	/* Disable legacy interrupts */
781 	pci_set_cfgdata8(pdi, PCIR_INTLINE, 255);
782 	pci_set_cfgdata8(pdi, PCIR_INTPIN, 0);
783 
784 	pci_set_cfgdata8(pdi, PCIR_COMMAND, PCIM_CMD_BUSMASTEREN);
785 
786 	err = (*pde->pe_init)(ctx, pdi, fi->fi_param);
787 	if (err == 0)
788 		fi->fi_devi = pdi;
789 	else
790 		free(pdi);
791 
792 	return (err);
793 }
794 
795 void
796 pci_populate_msicap(struct msicap *msicap, int msgnum, int nextptr)
797 {
798 	int mmc;
799 
800 	/* Number of msi messages must be a power of 2 between 1 and 32 */
801 	assert((msgnum & (msgnum - 1)) == 0 && msgnum >= 1 && msgnum <= 32);
802 	mmc = ffs(msgnum) - 1;
803 
804 	bzero(msicap, sizeof(struct msicap));
805 	msicap->capid = PCIY_MSI;
806 	msicap->nextptr = nextptr;
807 	msicap->msgctrl = PCIM_MSICTRL_64BIT | (mmc << 1);
808 }
809 
810 int
811 pci_emul_add_msicap(struct pci_devinst *pi, int msgnum)
812 {
813 	struct msicap msicap;
814 
815 	pci_populate_msicap(&msicap, msgnum, 0);
816 
817 	return (pci_emul_add_capability(pi, (u_char *)&msicap, sizeof(msicap)));
818 }
819 
820 static void
821 pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,
822 		     uint32_t msix_tab_size)
823 {
824 
825 	assert(msix_tab_size % 4096 == 0);
826 
827 	bzero(msixcap, sizeof(struct msixcap));
828 	msixcap->capid = PCIY_MSIX;
829 
830 	/*
831 	 * Message Control Register, all fields set to
832 	 * zero except for the Table Size.
833 	 * Note: Table size N is encoded as N-1
834 	 */
835 	msixcap->msgctrl = msgnum - 1;
836 
837 	/*
838 	 * MSI-X BAR setup:
839 	 * - MSI-X table start at offset 0
840 	 * - PBA table starts at a 4K aligned offset after the MSI-X table
841 	 */
842 	msixcap->table_info = barnum & PCIM_MSIX_BIR_MASK;
843 	msixcap->pba_info = msix_tab_size | (barnum & PCIM_MSIX_BIR_MASK);
844 }
845 
846 static void
847 pci_msix_table_init(struct pci_devinst *pi, int table_entries)
848 {
849 	int i, table_size;
850 
851 	assert(table_entries > 0);
852 	assert(table_entries <= MAX_MSIX_TABLE_ENTRIES);
853 
854 	table_size = table_entries * MSIX_TABLE_ENTRY_SIZE;
855 	pi->pi_msix.table = calloc(1, table_size);
856 
857 	/* set mask bit of vector control register */
858 	for (i = 0; i < table_entries; i++)
859 		pi->pi_msix.table[i].vector_control |= PCIM_MSIX_VCTRL_MASK;
860 }
861 
862 int
863 pci_emul_add_msixcap(struct pci_devinst *pi, int msgnum, int barnum)
864 {
865 	uint32_t tab_size;
866 	struct msixcap msixcap;
867 
868 	assert(msgnum >= 1 && msgnum <= MAX_MSIX_TABLE_ENTRIES);
869 	assert(barnum >= 0 && barnum <= PCIR_MAX_BAR_0);
870 
871 	tab_size = msgnum * MSIX_TABLE_ENTRY_SIZE;
872 
873 	/* Align table size to nearest 4K */
874 	tab_size = roundup2(tab_size, 4096);
875 
876 	pi->pi_msix.table_bar = barnum;
877 	pi->pi_msix.pba_bar   = barnum;
878 	pi->pi_msix.table_offset = 0;
879 	pi->pi_msix.table_count = msgnum;
880 	pi->pi_msix.pba_offset = tab_size;
881 	pi->pi_msix.pba_size = PBA_SIZE(msgnum);
882 
883 	pci_msix_table_init(pi, msgnum);
884 
885 	pci_populate_msixcap(&msixcap, msgnum, barnum, tab_size);
886 
887 	/* allocate memory for MSI-X Table and PBA */
888 	pci_emul_alloc_bar(pi, barnum, PCIBAR_MEM32,
889 				tab_size + pi->pi_msix.pba_size);
890 
891 	return (pci_emul_add_capability(pi, (u_char *)&msixcap,
892 					sizeof(msixcap)));
893 }
894 
895 void
896 msixcap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
897 		 int bytes, uint32_t val)
898 {
899 	uint16_t msgctrl, rwmask;
900 	int off;
901 
902 	off = offset - capoff;
903 	/* Message Control Register */
904 	if (off == 2 && bytes == 2) {
905 		rwmask = PCIM_MSIXCTRL_MSIX_ENABLE | PCIM_MSIXCTRL_FUNCTION_MASK;
906 		msgctrl = pci_get_cfgdata16(pi, offset);
907 		msgctrl &= ~rwmask;
908 		msgctrl |= val & rwmask;
909 		val = msgctrl;
910 
911 		pi->pi_msix.enabled = val & PCIM_MSIXCTRL_MSIX_ENABLE;
912 		pi->pi_msix.function_mask = val & PCIM_MSIXCTRL_FUNCTION_MASK;
913 		pci_lintr_update(pi);
914 	}
915 
916 	CFGWRITE(pi, offset, val, bytes);
917 }
918 
919 void
920 msicap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
921 		int bytes, uint32_t val)
922 {
923 	uint16_t msgctrl, rwmask, msgdata, mme;
924 	uint32_t addrlo;
925 
926 	/*
927 	 * If guest is writing to the message control register make sure
928 	 * we do not overwrite read-only fields.
929 	 */
930 	if ((offset - capoff) == 2 && bytes == 2) {
931 		rwmask = PCIM_MSICTRL_MME_MASK | PCIM_MSICTRL_MSI_ENABLE;
932 		msgctrl = pci_get_cfgdata16(pi, offset);
933 		msgctrl &= ~rwmask;
934 		msgctrl |= val & rwmask;
935 		val = msgctrl;
936 
937 		addrlo = pci_get_cfgdata32(pi, capoff + 4);
938 		if (msgctrl & PCIM_MSICTRL_64BIT)
939 			msgdata = pci_get_cfgdata16(pi, capoff + 12);
940 		else
941 			msgdata = pci_get_cfgdata16(pi, capoff + 8);
942 
943 		mme = msgctrl & PCIM_MSICTRL_MME_MASK;
944 		pi->pi_msi.enabled = msgctrl & PCIM_MSICTRL_MSI_ENABLE ? 1 : 0;
945 		if (pi->pi_msi.enabled) {
946 			pi->pi_msi.addr = addrlo;
947 			pi->pi_msi.msg_data = msgdata;
948 			pi->pi_msi.maxmsgnum = 1 << (mme >> 4);
949 		} else {
950 			pi->pi_msi.maxmsgnum = 0;
951 		}
952 		pci_lintr_update(pi);
953 	}
954 
955 	CFGWRITE(pi, offset, val, bytes);
956 }
957 
958 void
959 pciecap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
960 		 int bytes, uint32_t val)
961 {
962 
963 	/* XXX don't write to the readonly parts */
964 	CFGWRITE(pi, offset, val, bytes);
965 }
966 
967 #define	PCIECAP_VERSION	0x2
968 int
969 pci_emul_add_pciecap(struct pci_devinst *pi, int type)
970 {
971 	int err;
972 	struct pciecap pciecap;
973 
974 	bzero(&pciecap, sizeof(pciecap));
975 
976 	/*
977 	 * Use the integrated endpoint type for endpoints on a root complex bus.
978 	 *
979 	 * NB: bhyve currently only supports a single PCI bus that is the root
980 	 * complex bus, so all endpoints are integrated.
981 	 */
982 	if ((type == PCIEM_TYPE_ENDPOINT) && (pi->pi_bus == 0))
983 		type = PCIEM_TYPE_ROOT_INT_EP;
984 
985 	pciecap.capid = PCIY_EXPRESS;
986 	pciecap.pcie_capabilities = PCIECAP_VERSION | type;
987 	if (type != PCIEM_TYPE_ROOT_INT_EP) {
988 		pciecap.link_capabilities = 0x411;	/* gen1, x1 */
989 		pciecap.link_status = 0x11;		/* gen1, x1 */
990 	}
991 
992 	err = pci_emul_add_capability(pi, (u_char *)&pciecap, sizeof(pciecap));
993 	return (err);
994 }
995 
996 /*
997  * This function assumes that 'coff' is in the capabilities region of the
998  * config space.
999  */
1000 static void
1001 pci_emul_capwrite(struct pci_devinst *pi, int offset, int bytes, uint32_t val)
1002 {
1003 	int capid;
1004 	uint8_t capoff, nextoff;
1005 
1006 	/* Do not allow un-aligned writes */
1007 	if ((offset & (bytes - 1)) != 0)
1008 		return;
1009 
1010 	/* Find the capability that we want to update */
1011 	capoff = CAP_START_OFFSET;
1012 	while (1) {
1013 		nextoff = pci_get_cfgdata8(pi, capoff + 1);
1014 		if (nextoff == 0)
1015 			break;
1016 		if (offset >= capoff && offset < nextoff)
1017 			break;
1018 
1019 		capoff = nextoff;
1020 	}
1021 	assert(offset >= capoff);
1022 
1023 	/*
1024 	 * Capability ID and Next Capability Pointer are readonly.
1025 	 * However, some o/s's do 4-byte writes that include these.
1026 	 * For this case, trim the write back to 2 bytes and adjust
1027 	 * the data.
1028 	 */
1029 	if (offset == capoff || offset == capoff + 1) {
1030 		if (offset == capoff && bytes == 4) {
1031 			bytes = 2;
1032 			offset += 2;
1033 			val >>= 16;
1034 		} else
1035 			return;
1036 	}
1037 
1038 	capid = pci_get_cfgdata8(pi, capoff);
1039 	switch (capid) {
1040 	case PCIY_MSI:
1041 		msicap_cfgwrite(pi, capoff, offset, bytes, val);
1042 		break;
1043 	case PCIY_MSIX:
1044 		msixcap_cfgwrite(pi, capoff, offset, bytes, val);
1045 		break;
1046 	case PCIY_EXPRESS:
1047 		pciecap_cfgwrite(pi, capoff, offset, bytes, val);
1048 		break;
1049 	default:
1050 		break;
1051 	}
1052 }
1053 
1054 static int
1055 pci_emul_iscap(struct pci_devinst *pi, int offset)
1056 {
1057 	uint16_t sts;
1058 
1059 	sts = pci_get_cfgdata16(pi, PCIR_STATUS);
1060 	if ((sts & PCIM_STATUS_CAPPRESENT) != 0) {
1061 		if (offset >= CAP_START_OFFSET && offset <= pi->pi_capend)
1062 			return (1);
1063 	}
1064 	return (0);
1065 }
1066 
1067 static int
1068 pci_emul_fallback_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
1069 			  int size, uint64_t *val, void *arg1, long arg2)
1070 {
1071 	/*
1072 	 * Ignore writes; return 0xff's for reads. The mem read code
1073 	 * will take care of truncating to the correct size.
1074 	 */
1075 	if (dir == MEM_F_READ) {
1076 		*val = 0xffffffffffffffff;
1077 	}
1078 
1079 	return (0);
1080 }
1081 
1082 static int
1083 pci_emul_ecfg_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
1084     int bytes, uint64_t *val, void *arg1, long arg2)
1085 {
1086 	int bus, slot, func, coff, in;
1087 
1088 	coff = addr & 0xfff;
1089 	func = (addr >> 12) & 0x7;
1090 	slot = (addr >> 15) & 0x1f;
1091 	bus = (addr >> 20) & 0xff;
1092 	in = (dir == MEM_F_READ);
1093 	if (in)
1094 		*val = ~0UL;
1095 	pci_cfgrw(ctx, vcpu, in, bus, slot, func, coff, bytes, (uint32_t *)val);
1096 	return (0);
1097 }
1098 
1099 uint64_t
1100 pci_ecfg_base(void)
1101 {
1102 
1103 	return (PCI_EMUL_ECFG_BASE);
1104 }
1105 
1106 #define	BUSIO_ROUNDUP		32
1107 #define	BUSMEM_ROUNDUP		(1024 * 1024)
1108 
1109 int
1110 init_pci(struct vmctx *ctx)
1111 {
1112 	struct mem_range mr;
1113 	struct pci_devemu *pde;
1114 	struct businfo *bi;
1115 	struct slotinfo *si;
1116 	struct funcinfo *fi;
1117 	size_t lowmem;
1118 	int bus, slot, func;
1119 	int error;
1120 
1121 	pci_emul_iobase = PCI_EMUL_IOBASE;
1122 	pci_emul_membase32 = vm_get_lowmem_limit(ctx);
1123 	pci_emul_membase64 = PCI_EMUL_MEMBASE64;
1124 
1125 	for (bus = 0; bus < MAXBUSES; bus++) {
1126 		if ((bi = pci_businfo[bus]) == NULL)
1127 			continue;
1128 		/*
1129 		 * Keep track of the i/o and memory resources allocated to
1130 		 * this bus.
1131 		 */
1132 		bi->iobase = pci_emul_iobase;
1133 		bi->membase32 = pci_emul_membase32;
1134 		bi->membase64 = pci_emul_membase64;
1135 
1136 		for (slot = 0; slot < MAXSLOTS; slot++) {
1137 			si = &bi->slotinfo[slot];
1138 			for (func = 0; func < MAXFUNCS; func++) {
1139 				fi = &si->si_funcs[func];
1140 				if (fi->fi_name == NULL)
1141 					continue;
1142 				pde = pci_emul_finddev(fi->fi_name);
1143 				assert(pde != NULL);
1144 				error = pci_emul_init(ctx, pde, bus, slot,
1145 				    func, fi);
1146 				if (error)
1147 					return (error);
1148 			}
1149 		}
1150 
1151 		/*
1152 		 * Add some slop to the I/O and memory resources decoded by
1153 		 * this bus to give a guest some flexibility if it wants to
1154 		 * reprogram the BARs.
1155 		 */
1156 		pci_emul_iobase += BUSIO_ROUNDUP;
1157 		pci_emul_iobase = roundup2(pci_emul_iobase, BUSIO_ROUNDUP);
1158 		bi->iolimit = pci_emul_iobase;
1159 
1160 		pci_emul_membase32 += BUSMEM_ROUNDUP;
1161 		pci_emul_membase32 = roundup2(pci_emul_membase32,
1162 		    BUSMEM_ROUNDUP);
1163 		bi->memlimit32 = pci_emul_membase32;
1164 
1165 		pci_emul_membase64 += BUSMEM_ROUNDUP;
1166 		pci_emul_membase64 = roundup2(pci_emul_membase64,
1167 		    BUSMEM_ROUNDUP);
1168 		bi->memlimit64 = pci_emul_membase64;
1169 	}
1170 
1171 	/*
1172 	 * PCI backends are initialized before routing INTx interrupts
1173 	 * so that LPC devices are able to reserve ISA IRQs before
1174 	 * routing PIRQ pins.
1175 	 */
1176 	for (bus = 0; bus < MAXBUSES; bus++) {
1177 		if ((bi = pci_businfo[bus]) == NULL)
1178 			continue;
1179 
1180 		for (slot = 0; slot < MAXSLOTS; slot++) {
1181 			si = &bi->slotinfo[slot];
1182 			for (func = 0; func < MAXFUNCS; func++) {
1183 				fi = &si->si_funcs[func];
1184 				if (fi->fi_devi == NULL)
1185 					continue;
1186 				pci_lintr_route(fi->fi_devi);
1187 			}
1188 		}
1189 	}
1190 	lpc_pirq_routed();
1191 
1192 	/*
1193 	 * The guest physical memory map looks like the following:
1194 	 * [0,		    lowmem)		guest system memory
1195 	 * [lowmem,	    lowmem_limit)	memory hole (may be absent)
1196 	 * [lowmem_limit,   0xE0000000)		PCI hole (32-bit BAR allocation)
1197 	 * [0xE0000000,	    0xF0000000)		PCI extended config window
1198 	 * [0xF0000000,	    4GB)		LAPIC, IOAPIC, HPET, firmware
1199 	 * [4GB,	    4GB + highmem)
1200 	 */
1201 
1202 	/*
1203 	 * Accesses to memory addresses that are not allocated to system
1204 	 * memory or PCI devices return 0xff's.
1205 	 */
1206 	lowmem = vm_get_lowmem_size(ctx);
1207 	bzero(&mr, sizeof(struct mem_range));
1208 	mr.name = "PCI hole";
1209 	mr.flags = MEM_F_RW | MEM_F_IMMUTABLE;
1210 	mr.base = lowmem;
1211 	mr.size = (4ULL * 1024 * 1024 * 1024) - lowmem;
1212 	mr.handler = pci_emul_fallback_handler;
1213 	error = register_mem_fallback(&mr);
1214 	assert(error == 0);
1215 
1216 	/* PCI extended config space */
1217 	bzero(&mr, sizeof(struct mem_range));
1218 	mr.name = "PCI ECFG";
1219 	mr.flags = MEM_F_RW | MEM_F_IMMUTABLE;
1220 	mr.base = PCI_EMUL_ECFG_BASE;
1221 	mr.size = PCI_EMUL_ECFG_SIZE;
1222 	mr.handler = pci_emul_ecfg_handler;
1223 	error = register_mem(&mr);
1224 	assert(error == 0);
1225 
1226 	return (0);
1227 }
1228 
1229 static void
1230 pci_apic_prt_entry(int bus, int slot, int pin, int pirq_pin, int ioapic_irq,
1231     void *arg)
1232 {
1233 
1234 	dsdt_line("  Package ()");
1235 	dsdt_line("  {");
1236 	dsdt_line("    0x%X,", slot << 16 | 0xffff);
1237 	dsdt_line("    0x%02X,", pin - 1);
1238 	dsdt_line("    Zero,");
1239 	dsdt_line("    0x%X", ioapic_irq);
1240 	dsdt_line("  },");
1241 }
1242 
1243 static void
1244 pci_pirq_prt_entry(int bus, int slot, int pin, int pirq_pin, int ioapic_irq,
1245     void *arg)
1246 {
1247 	char *name;
1248 
1249 	name = lpc_pirq_name(pirq_pin);
1250 	if (name == NULL)
1251 		return;
1252 	dsdt_line("  Package ()");
1253 	dsdt_line("  {");
1254 	dsdt_line("    0x%X,", slot << 16 | 0xffff);
1255 	dsdt_line("    0x%02X,", pin - 1);
1256 	dsdt_line("    %s,", name);
1257 	dsdt_line("    0x00");
1258 	dsdt_line("  },");
1259 	free(name);
1260 }
1261 
1262 /*
1263  * A bhyve virtual machine has a flat PCI hierarchy with a root port
1264  * corresponding to each PCI bus.
1265  */
1266 static void
1267 pci_bus_write_dsdt(int bus)
1268 {
1269 	struct businfo *bi;
1270 	struct slotinfo *si;
1271 	struct pci_devinst *pi;
1272 	int count, func, slot;
1273 
1274 	/*
1275 	 * If there are no devices on this 'bus' then just return.
1276 	 */
1277 	if ((bi = pci_businfo[bus]) == NULL) {
1278 		/*
1279 		 * Bus 0 is special because it decodes the I/O ports used
1280 		 * for PCI config space access even if there are no devices
1281 		 * on it.
1282 		 */
1283 		if (bus != 0)
1284 			return;
1285 	}
1286 
1287 	dsdt_line("  Device (PC%02X)", bus);
1288 	dsdt_line("  {");
1289 	dsdt_line("    Name (_HID, EisaId (\"PNP0A03\"))");
1290 	dsdt_line("    Name (_ADR, Zero)");
1291 
1292 	dsdt_line("    Method (_BBN, 0, NotSerialized)");
1293 	dsdt_line("    {");
1294 	dsdt_line("        Return (0x%08X)", bus);
1295 	dsdt_line("    }");
1296 	dsdt_line("    Name (_CRS, ResourceTemplate ()");
1297 	dsdt_line("    {");
1298 	dsdt_line("      WordBusNumber (ResourceProducer, MinFixed, "
1299 	    "MaxFixed, PosDecode,");
1300 	dsdt_line("        0x0000,             // Granularity");
1301 	dsdt_line("        0x%04X,             // Range Minimum", bus);
1302 	dsdt_line("        0x%04X,             // Range Maximum", bus);
1303 	dsdt_line("        0x0000,             // Translation Offset");
1304 	dsdt_line("        0x0001,             // Length");
1305 	dsdt_line("        ,, )");
1306 
1307 	if (bus == 0) {
1308 		dsdt_indent(3);
1309 		dsdt_fixed_ioport(0xCF8, 8);
1310 		dsdt_unindent(3);
1311 
1312 		dsdt_line("      WordIO (ResourceProducer, MinFixed, MaxFixed, "
1313 		    "PosDecode, EntireRange,");
1314 		dsdt_line("        0x0000,             // Granularity");
1315 		dsdt_line("        0x0000,             // Range Minimum");
1316 		dsdt_line("        0x0CF7,             // Range Maximum");
1317 		dsdt_line("        0x0000,             // Translation Offset");
1318 		dsdt_line("        0x0CF8,             // Length");
1319 		dsdt_line("        ,, , TypeStatic)");
1320 
1321 		dsdt_line("      WordIO (ResourceProducer, MinFixed, MaxFixed, "
1322 		    "PosDecode, EntireRange,");
1323 		dsdt_line("        0x0000,             // Granularity");
1324 		dsdt_line("        0x0D00,             // Range Minimum");
1325 		dsdt_line("        0x%04X,             // Range Maximum",
1326 		    PCI_EMUL_IOBASE - 1);
1327 		dsdt_line("        0x0000,             // Translation Offset");
1328 		dsdt_line("        0x%04X,             // Length",
1329 		    PCI_EMUL_IOBASE - 0x0D00);
1330 		dsdt_line("        ,, , TypeStatic)");
1331 
1332 		if (bi == NULL) {
1333 			dsdt_line("    })");
1334 			goto done;
1335 		}
1336 	}
1337 	assert(bi != NULL);
1338 
1339 	/* i/o window */
1340 	dsdt_line("      WordIO (ResourceProducer, MinFixed, MaxFixed, "
1341 	    "PosDecode, EntireRange,");
1342 	dsdt_line("        0x0000,             // Granularity");
1343 	dsdt_line("        0x%04X,             // Range Minimum", bi->iobase);
1344 	dsdt_line("        0x%04X,             // Range Maximum",
1345 	    bi->iolimit - 1);
1346 	dsdt_line("        0x0000,             // Translation Offset");
1347 	dsdt_line("        0x%04X,             // Length",
1348 	    bi->iolimit - bi->iobase);
1349 	dsdt_line("        ,, , TypeStatic)");
1350 
1351 	/* mmio window (32-bit) */
1352 	dsdt_line("      DWordMemory (ResourceProducer, PosDecode, "
1353 	    "MinFixed, MaxFixed, NonCacheable, ReadWrite,");
1354 	dsdt_line("        0x00000000,         // Granularity");
1355 	dsdt_line("        0x%08X,         // Range Minimum\n", bi->membase32);
1356 	dsdt_line("        0x%08X,         // Range Maximum\n",
1357 	    bi->memlimit32 - 1);
1358 	dsdt_line("        0x00000000,         // Translation Offset");
1359 	dsdt_line("        0x%08X,         // Length\n",
1360 	    bi->memlimit32 - bi->membase32);
1361 	dsdt_line("        ,, , AddressRangeMemory, TypeStatic)");
1362 
1363 	/* mmio window (64-bit) */
1364 	dsdt_line("      QWordMemory (ResourceProducer, PosDecode, "
1365 	    "MinFixed, MaxFixed, NonCacheable, ReadWrite,");
1366 	dsdt_line("        0x0000000000000000, // Granularity");
1367 	dsdt_line("        0x%016lX, // Range Minimum\n", bi->membase64);
1368 	dsdt_line("        0x%016lX, // Range Maximum\n",
1369 	    bi->memlimit64 - 1);
1370 	dsdt_line("        0x0000000000000000, // Translation Offset");
1371 	dsdt_line("        0x%016lX, // Length\n",
1372 	    bi->memlimit64 - bi->membase64);
1373 	dsdt_line("        ,, , AddressRangeMemory, TypeStatic)");
1374 	dsdt_line("    })");
1375 
1376 	count = pci_count_lintr(bus);
1377 	if (count != 0) {
1378 		dsdt_indent(2);
1379 		dsdt_line("Name (PPRT, Package ()");
1380 		dsdt_line("{");
1381 		pci_walk_lintr(bus, pci_pirq_prt_entry, NULL);
1382 		dsdt_line("})");
1383 		dsdt_line("Name (APRT, Package ()");
1384 		dsdt_line("{");
1385 		pci_walk_lintr(bus, pci_apic_prt_entry, NULL);
1386 		dsdt_line("})");
1387 		dsdt_line("Method (_PRT, 0, NotSerialized)");
1388 		dsdt_line("{");
1389 		dsdt_line("  If (PICM)");
1390 		dsdt_line("  {");
1391 		dsdt_line("    Return (APRT)");
1392 		dsdt_line("  }");
1393 		dsdt_line("  Else");
1394 		dsdt_line("  {");
1395 		dsdt_line("    Return (PPRT)");
1396 		dsdt_line("  }");
1397 		dsdt_line("}");
1398 		dsdt_unindent(2);
1399 	}
1400 
1401 	dsdt_indent(2);
1402 	for (slot = 0; slot < MAXSLOTS; slot++) {
1403 		si = &bi->slotinfo[slot];
1404 		for (func = 0; func < MAXFUNCS; func++) {
1405 			pi = si->si_funcs[func].fi_devi;
1406 			if (pi != NULL && pi->pi_d->pe_write_dsdt != NULL)
1407 				pi->pi_d->pe_write_dsdt(pi);
1408 		}
1409 	}
1410 	dsdt_unindent(2);
1411 done:
1412 	dsdt_line("  }");
1413 }
1414 
1415 void
1416 pci_write_dsdt(void)
1417 {
1418 	int bus;
1419 
1420 	dsdt_indent(1);
1421 	dsdt_line("Name (PICM, 0x00)");
1422 	dsdt_line("Method (_PIC, 1, NotSerialized)");
1423 	dsdt_line("{");
1424 	dsdt_line("  Store (Arg0, PICM)");
1425 	dsdt_line("}");
1426 	dsdt_line("");
1427 	dsdt_line("Scope (_SB)");
1428 	dsdt_line("{");
1429 	for (bus = 0; bus < MAXBUSES; bus++)
1430 		pci_bus_write_dsdt(bus);
1431 	dsdt_line("}");
1432 	dsdt_unindent(1);
1433 }
1434 
1435 int
1436 pci_bus_configured(int bus)
1437 {
1438 	assert(bus >= 0 && bus < MAXBUSES);
1439 	return (pci_businfo[bus] != NULL);
1440 }
1441 
1442 int
1443 pci_msi_enabled(struct pci_devinst *pi)
1444 {
1445 	return (pi->pi_msi.enabled);
1446 }
1447 
1448 int
1449 pci_msi_maxmsgnum(struct pci_devinst *pi)
1450 {
1451 	if (pi->pi_msi.enabled)
1452 		return (pi->pi_msi.maxmsgnum);
1453 	else
1454 		return (0);
1455 }
1456 
1457 int
1458 pci_msix_enabled(struct pci_devinst *pi)
1459 {
1460 
1461 	return (pi->pi_msix.enabled && !pi->pi_msi.enabled);
1462 }
1463 
1464 void
1465 pci_generate_msix(struct pci_devinst *pi, int index)
1466 {
1467 	struct msix_table_entry *mte;
1468 
1469 	if (!pci_msix_enabled(pi))
1470 		return;
1471 
1472 	if (pi->pi_msix.function_mask)
1473 		return;
1474 
1475 	if (index >= pi->pi_msix.table_count)
1476 		return;
1477 
1478 	mte = &pi->pi_msix.table[index];
1479 	if ((mte->vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
1480 		/* XXX Set PBA bit if interrupt is disabled */
1481 		vm_lapic_msi(pi->pi_vmctx, mte->addr, mte->msg_data);
1482 	}
1483 }
1484 
1485 void
1486 pci_generate_msi(struct pci_devinst *pi, int index)
1487 {
1488 
1489 	if (pci_msi_enabled(pi) && index < pci_msi_maxmsgnum(pi)) {
1490 		vm_lapic_msi(pi->pi_vmctx, pi->pi_msi.addr,
1491 			     pi->pi_msi.msg_data + index);
1492 	}
1493 }
1494 
1495 static bool
1496 pci_lintr_permitted(struct pci_devinst *pi)
1497 {
1498 	uint16_t cmd;
1499 
1500 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);
1501 	return (!(pi->pi_msi.enabled || pi->pi_msix.enabled ||
1502 		(cmd & PCIM_CMD_INTxDIS)));
1503 }
1504 
1505 void
1506 pci_lintr_request(struct pci_devinst *pi)
1507 {
1508 	struct businfo *bi;
1509 	struct slotinfo *si;
1510 	int bestpin, bestcount, pin;
1511 
1512 	bi = pci_businfo[pi->pi_bus];
1513 	assert(bi != NULL);
1514 
1515 	/*
1516 	 * Just allocate a pin from our slot.  The pin will be
1517 	 * assigned IRQs later when interrupts are routed.
1518 	 */
1519 	si = &bi->slotinfo[pi->pi_slot];
1520 	bestpin = 0;
1521 	bestcount = si->si_intpins[0].ii_count;
1522 	for (pin = 1; pin < 4; pin++) {
1523 		if (si->si_intpins[pin].ii_count < bestcount) {
1524 			bestpin = pin;
1525 			bestcount = si->si_intpins[pin].ii_count;
1526 		}
1527 	}
1528 
1529 	si->si_intpins[bestpin].ii_count++;
1530 	pi->pi_lintr.pin = bestpin + 1;
1531 	pci_set_cfgdata8(pi, PCIR_INTPIN, bestpin + 1);
1532 }
1533 
1534 static void
1535 pci_lintr_route(struct pci_devinst *pi)
1536 {
1537 	struct businfo *bi;
1538 	struct intxinfo *ii;
1539 
1540 	if (pi->pi_lintr.pin == 0)
1541 		return;
1542 
1543 	bi = pci_businfo[pi->pi_bus];
1544 	assert(bi != NULL);
1545 	ii = &bi->slotinfo[pi->pi_slot].si_intpins[pi->pi_lintr.pin - 1];
1546 
1547 	/*
1548 	 * Attempt to allocate an I/O APIC pin for this intpin if one
1549 	 * is not yet assigned.
1550 	 */
1551 	if (ii->ii_ioapic_irq == 0)
1552 		ii->ii_ioapic_irq = ioapic_pci_alloc_irq(pi);
1553 	assert(ii->ii_ioapic_irq > 0);
1554 
1555 	/*
1556 	 * Attempt to allocate a PIRQ pin for this intpin if one is
1557 	 * not yet assigned.
1558 	 */
1559 	if (ii->ii_pirq_pin == 0)
1560 		ii->ii_pirq_pin = pirq_alloc_pin(pi);
1561 	assert(ii->ii_pirq_pin > 0);
1562 
1563 	pi->pi_lintr.ioapic_irq = ii->ii_ioapic_irq;
1564 	pi->pi_lintr.pirq_pin = ii->ii_pirq_pin;
1565 	pci_set_cfgdata8(pi, PCIR_INTLINE, pirq_irq(ii->ii_pirq_pin));
1566 }
1567 
1568 void
1569 pci_lintr_assert(struct pci_devinst *pi)
1570 {
1571 
1572 	assert(pi->pi_lintr.pin > 0);
1573 
1574 	pthread_mutex_lock(&pi->pi_lintr.lock);
1575 	if (pi->pi_lintr.state == IDLE) {
1576 		if (pci_lintr_permitted(pi)) {
1577 			pi->pi_lintr.state = ASSERTED;
1578 			pci_irq_assert(pi);
1579 		} else
1580 			pi->pi_lintr.state = PENDING;
1581 	}
1582 	pthread_mutex_unlock(&pi->pi_lintr.lock);
1583 }
1584 
1585 void
1586 pci_lintr_deassert(struct pci_devinst *pi)
1587 {
1588 
1589 	assert(pi->pi_lintr.pin > 0);
1590 
1591 	pthread_mutex_lock(&pi->pi_lintr.lock);
1592 	if (pi->pi_lintr.state == ASSERTED) {
1593 		pi->pi_lintr.state = IDLE;
1594 		pci_irq_deassert(pi);
1595 	} else if (pi->pi_lintr.state == PENDING)
1596 		pi->pi_lintr.state = IDLE;
1597 	pthread_mutex_unlock(&pi->pi_lintr.lock);
1598 }
1599 
1600 static void
1601 pci_lintr_update(struct pci_devinst *pi)
1602 {
1603 
1604 	pthread_mutex_lock(&pi->pi_lintr.lock);
1605 	if (pi->pi_lintr.state == ASSERTED && !pci_lintr_permitted(pi)) {
1606 		pci_irq_deassert(pi);
1607 		pi->pi_lintr.state = PENDING;
1608 	} else if (pi->pi_lintr.state == PENDING && pci_lintr_permitted(pi)) {
1609 		pi->pi_lintr.state = ASSERTED;
1610 		pci_irq_assert(pi);
1611 	}
1612 	pthread_mutex_unlock(&pi->pi_lintr.lock);
1613 #ifndef __FreeBSD__
1614 	if (pi->pi_d->pe_lintrupdate != NULL) {
1615 		pi->pi_d->pe_lintrupdate(pi);
1616 	}
1617 #endif /* __FreeBSD__ */
1618 }
1619 
1620 int
1621 pci_count_lintr(int bus)
1622 {
1623 	int count, slot, pin;
1624 	struct slotinfo *slotinfo;
1625 
1626 	count = 0;
1627 	if (pci_businfo[bus] != NULL) {
1628 		for (slot = 0; slot < MAXSLOTS; slot++) {
1629 			slotinfo = &pci_businfo[bus]->slotinfo[slot];
1630 			for (pin = 0; pin < 4; pin++) {
1631 				if (slotinfo->si_intpins[pin].ii_count != 0)
1632 					count++;
1633 			}
1634 		}
1635 	}
1636 	return (count);
1637 }
1638 
1639 void
1640 pci_walk_lintr(int bus, pci_lintr_cb cb, void *arg)
1641 {
1642 	struct businfo *bi;
1643 	struct slotinfo *si;
1644 	struct intxinfo *ii;
1645 	int slot, pin;
1646 
1647 	if ((bi = pci_businfo[bus]) == NULL)
1648 		return;
1649 
1650 	for (slot = 0; slot < MAXSLOTS; slot++) {
1651 		si = &bi->slotinfo[slot];
1652 		for (pin = 0; pin < 4; pin++) {
1653 			ii = &si->si_intpins[pin];
1654 			if (ii->ii_count != 0)
1655 				cb(bus, slot, pin + 1, ii->ii_pirq_pin,
1656 				    ii->ii_ioapic_irq, arg);
1657 		}
1658 	}
1659 }
1660 
1661 /*
1662  * Return 1 if the emulated device in 'slot' is a multi-function device.
1663  * Return 0 otherwise.
1664  */
1665 static int
1666 pci_emul_is_mfdev(int bus, int slot)
1667 {
1668 	struct businfo *bi;
1669 	struct slotinfo *si;
1670 	int f, numfuncs;
1671 
1672 	numfuncs = 0;
1673 	if ((bi = pci_businfo[bus]) != NULL) {
1674 		si = &bi->slotinfo[slot];
1675 		for (f = 0; f < MAXFUNCS; f++) {
1676 			if (si->si_funcs[f].fi_devi != NULL) {
1677 				numfuncs++;
1678 			}
1679 		}
1680 	}
1681 	return (numfuncs > 1);
1682 }
1683 
1684 /*
1685  * Ensure that the PCIM_MFDEV bit is properly set (or unset) depending on
1686  * whether or not is a multi-function being emulated in the pci 'slot'.
1687  */
1688 static void
1689 pci_emul_hdrtype_fixup(int bus, int slot, int off, int bytes, uint32_t *rv)
1690 {
1691 	int mfdev;
1692 
1693 	if (off <= PCIR_HDRTYPE && off + bytes > PCIR_HDRTYPE) {
1694 		mfdev = pci_emul_is_mfdev(bus, slot);
1695 		switch (bytes) {
1696 		case 1:
1697 		case 2:
1698 			*rv &= ~PCIM_MFDEV;
1699 			if (mfdev) {
1700 				*rv |= PCIM_MFDEV;
1701 			}
1702 			break;
1703 		case 4:
1704 			*rv &= ~(PCIM_MFDEV << 16);
1705 			if (mfdev) {
1706 				*rv |= (PCIM_MFDEV << 16);
1707 			}
1708 			break;
1709 		}
1710 	}
1711 }
1712 
1713 /*
1714  * Update device state in response to changes to the PCI command
1715  * register.
1716  */
1717 void
1718 pci_emul_cmd_changed(struct pci_devinst *pi, uint16_t old)
1719 {
1720 	int i;
1721 	uint16_t changed, new;
1722 
1723 	new = pci_get_cfgdata16(pi, PCIR_COMMAND);
1724 	changed = old ^ new;
1725 
1726 	/*
1727 	 * If the MMIO or I/O address space decoding has changed then
1728 	 * register/unregister all BARs that decode that address space.
1729 	 */
1730 	for (i = 0; i <= PCI_BARMAX; i++) {
1731 		switch (pi->pi_bar[i].type) {
1732 			case PCIBAR_NONE:
1733 			case PCIBAR_MEMHI64:
1734 				break;
1735 			case PCIBAR_IO:
1736 				/* I/O address space decoding changed? */
1737 				if (changed & PCIM_CMD_PORTEN) {
1738 					if (new & PCIM_CMD_PORTEN)
1739 						register_bar(pi, i);
1740 					else
1741 						unregister_bar(pi, i);
1742 				}
1743 				break;
1744 			case PCIBAR_MEM32:
1745 			case PCIBAR_MEM64:
1746 				/* MMIO address space decoding changed? */
1747 				if (changed & PCIM_CMD_MEMEN) {
1748 					if (new & PCIM_CMD_MEMEN)
1749 						register_bar(pi, i);
1750 					else
1751 						unregister_bar(pi, i);
1752 				}
1753 				break;
1754 			default:
1755 				assert(0);
1756 		}
1757 	}
1758 
1759 	/*
1760 	 * If INTx has been unmasked and is pending, assert the
1761 	 * interrupt.
1762 	 */
1763 	pci_lintr_update(pi);
1764 }
1765 
1766 static void
1767 pci_emul_cmdsts_write(struct pci_devinst *pi, int coff, uint32_t new, int bytes)
1768 {
1769 	int rshift;
1770 	uint32_t cmd, old, readonly;
1771 
1772 	cmd = pci_get_cfgdata16(pi, PCIR_COMMAND);	/* stash old value */
1773 
1774 	/*
1775 	 * From PCI Local Bus Specification 3.0 sections 6.2.2 and 6.2.3.
1776 	 *
1777 	 * XXX Bits 8, 11, 12, 13, 14 and 15 in the status register are
1778 	 * 'write 1 to clear'. However these bits are not set to '1' by
1779 	 * any device emulation so it is simpler to treat them as readonly.
1780 	 */
1781 	rshift = (coff & 0x3) * 8;
1782 	readonly = 0xFFFFF880 >> rshift;
1783 
1784 	old = CFGREAD(pi, coff, bytes);
1785 	new &= ~readonly;
1786 	new |= (old & readonly);
1787 	CFGWRITE(pi, coff, new, bytes);			/* update config */
1788 
1789 	pci_emul_cmd_changed(pi, cmd);
1790 }
1791 
1792 static void
1793 pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot, int func,
1794     int coff, int bytes, uint32_t *eax)
1795 {
1796 	struct businfo *bi;
1797 	struct slotinfo *si;
1798 	struct pci_devinst *pi;
1799 	struct pci_devemu *pe;
1800 	int idx, needcfg;
1801 	uint64_t addr, mask;
1802 	uint64_t bar = 0;
1803 
1804 	if ((bi = pci_businfo[bus]) != NULL) {
1805 		si = &bi->slotinfo[slot];
1806 		pi = si->si_funcs[func].fi_devi;
1807 	} else
1808 		pi = NULL;
1809 
1810 	/*
1811 	 * Just return if there is no device at this slot:func or if the
1812 	 * the guest is doing an un-aligned access.
1813 	 */
1814 	if (pi == NULL || (bytes != 1 && bytes != 2 && bytes != 4) ||
1815 	    (coff & (bytes - 1)) != 0) {
1816 		if (in)
1817 			*eax = 0xffffffff;
1818 		return;
1819 	}
1820 
1821 	/*
1822 	 * Ignore all writes beyond the standard config space and return all
1823 	 * ones on reads.
1824 	 */
1825 	if (coff >= PCI_REGMAX + 1) {
1826 		if (in) {
1827 			*eax = 0xffffffff;
1828 			/*
1829 			 * Extended capabilities begin at offset 256 in config
1830 			 * space. Absence of extended capabilities is signaled
1831 			 * with all 0s in the extended capability header at
1832 			 * offset 256.
1833 			 */
1834 			if (coff <= PCI_REGMAX + 4)
1835 				*eax = 0x00000000;
1836 		}
1837 		return;
1838 	}
1839 
1840 	pe = pi->pi_d;
1841 
1842 	/*
1843 	 * Config read
1844 	 */
1845 	if (in) {
1846 		/* Let the device emulation override the default handler */
1847 		if (pe->pe_cfgread != NULL) {
1848 			needcfg = pe->pe_cfgread(ctx, vcpu, pi, coff, bytes,
1849 			    eax);
1850 		} else {
1851 			needcfg = 1;
1852 		}
1853 
1854 		if (needcfg)
1855 			*eax = CFGREAD(pi, coff, bytes);
1856 
1857 		pci_emul_hdrtype_fixup(bus, slot, coff, bytes, eax);
1858 	} else {
1859 		/* Let the device emulation override the default handler */
1860 		if (pe->pe_cfgwrite != NULL &&
1861 		    (*pe->pe_cfgwrite)(ctx, vcpu, pi, coff, bytes, *eax) == 0)
1862 			return;
1863 
1864 		/*
1865 		 * Special handling for write to BAR registers
1866 		 */
1867 		if (coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1)) {
1868 			/*
1869 			 * Ignore writes to BAR registers that are not
1870 			 * 4-byte aligned.
1871 			 */
1872 			if (bytes != 4 || (coff & 0x3) != 0)
1873 				return;
1874 			idx = (coff - PCIR_BAR(0)) / 4;
1875 			mask = ~(pi->pi_bar[idx].size - 1);
1876 			switch (pi->pi_bar[idx].type) {
1877 			case PCIBAR_NONE:
1878 				pi->pi_bar[idx].addr = bar = 0;
1879 				break;
1880 			case PCIBAR_IO:
1881 				addr = *eax & mask;
1882 				addr &= 0xffff;
1883 				bar = addr | PCIM_BAR_IO_SPACE;
1884 				/*
1885 				 * Register the new BAR value for interception
1886 				 */
1887 				if (addr != pi->pi_bar[idx].addr) {
1888 					update_bar_address(pi, addr, idx,
1889 							   PCIBAR_IO);
1890 				}
1891 				break;
1892 			case PCIBAR_MEM32:
1893 				addr = bar = *eax & mask;
1894 				bar |= PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
1895 				if (addr != pi->pi_bar[idx].addr) {
1896 					update_bar_address(pi, addr, idx,
1897 							   PCIBAR_MEM32);
1898 				}
1899 				break;
1900 			case PCIBAR_MEM64:
1901 				addr = bar = *eax & mask;
1902 				bar |= PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
1903 				       PCIM_BAR_MEM_PREFETCH;
1904 				if (addr != (uint32_t)pi->pi_bar[idx].addr) {
1905 					update_bar_address(pi, addr, idx,
1906 							   PCIBAR_MEM64);
1907 				}
1908 				break;
1909 			case PCIBAR_MEMHI64:
1910 				mask = ~(pi->pi_bar[idx - 1].size - 1);
1911 				addr = ((uint64_t)*eax << 32) & mask;
1912 				bar = addr >> 32;
1913 				if (bar != pi->pi_bar[idx - 1].addr >> 32) {
1914 					update_bar_address(pi, addr, idx - 1,
1915 							   PCIBAR_MEMHI64);
1916 				}
1917 				break;
1918 			default:
1919 				assert(0);
1920 			}
1921 			pci_set_cfgdata32(pi, coff, bar);
1922 
1923 		} else if (pci_emul_iscap(pi, coff)) {
1924 			pci_emul_capwrite(pi, coff, bytes, *eax);
1925 		} else if (coff >= PCIR_COMMAND && coff < PCIR_REVID) {
1926 			pci_emul_cmdsts_write(pi, coff, *eax, bytes);
1927 		} else {
1928 			CFGWRITE(pi, coff, *eax, bytes);
1929 		}
1930 	}
1931 }
1932 
1933 static int cfgenable, cfgbus, cfgslot, cfgfunc, cfgoff;
1934 
1935 static int
1936 pci_emul_cfgaddr(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1937 		 uint32_t *eax, void *arg)
1938 {
1939 	uint32_t x;
1940 
1941 	if (bytes != 4) {
1942 		if (in)
1943 			*eax = (bytes == 2) ? 0xffff : 0xff;
1944 		return (0);
1945 	}
1946 
1947 	if (in) {
1948 		x = (cfgbus << 16) | (cfgslot << 11) | (cfgfunc << 8) | cfgoff;
1949 		if (cfgenable)
1950 			x |= CONF1_ENABLE;
1951 		*eax = x;
1952 	} else {
1953 		x = *eax;
1954 		cfgenable = (x & CONF1_ENABLE) == CONF1_ENABLE;
1955 		cfgoff = x & PCI_REGMAX;
1956 		cfgfunc = (x >> 8) & PCI_FUNCMAX;
1957 		cfgslot = (x >> 11) & PCI_SLOTMAX;
1958 		cfgbus = (x >> 16) & PCI_BUSMAX;
1959 	}
1960 
1961 	return (0);
1962 }
1963 INOUT_PORT(pci_cfgaddr, CONF1_ADDR_PORT, IOPORT_F_INOUT, pci_emul_cfgaddr);
1964 
1965 static int
1966 pci_emul_cfgdata(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1967 		 uint32_t *eax, void *arg)
1968 {
1969 	int coff;
1970 
1971 	assert(bytes == 1 || bytes == 2 || bytes == 4);
1972 
1973 	coff = cfgoff + (port - CONF1_DATA_PORT);
1974 	if (cfgenable) {
1975 		pci_cfgrw(ctx, vcpu, in, cfgbus, cfgslot, cfgfunc, coff, bytes,
1976 		    eax);
1977 	} else {
1978 		/* Ignore accesses to cfgdata if not enabled by cfgaddr */
1979 		if (in)
1980 			*eax = 0xffffffff;
1981 	}
1982 	return (0);
1983 }
1984 
1985 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+0, IOPORT_F_INOUT, pci_emul_cfgdata);
1986 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+1, IOPORT_F_INOUT, pci_emul_cfgdata);
1987 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+2, IOPORT_F_INOUT, pci_emul_cfgdata);
1988 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+3, IOPORT_F_INOUT, pci_emul_cfgdata);
1989 
1990 #define PCI_EMUL_TEST
1991 #ifdef PCI_EMUL_TEST
1992 /*
1993  * Define a dummy test device
1994  */
1995 #define DIOSZ	8
1996 #define DMEMSZ	4096
1997 struct pci_emul_dsoftc {
1998 	uint8_t	  ioregs[DIOSZ];
1999 	uint8_t	  memregs[2][DMEMSZ];
2000 };
2001 
2002 #define	PCI_EMUL_MSI_MSGS	 4
2003 #define	PCI_EMUL_MSIX_MSGS	16
2004 
2005 static int
2006 pci_emul_dinit(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
2007 {
2008 	int error;
2009 	struct pci_emul_dsoftc *sc;
2010 
2011 	sc = calloc(1, sizeof(struct pci_emul_dsoftc));
2012 
2013 	pi->pi_arg = sc;
2014 
2015 	pci_set_cfgdata16(pi, PCIR_DEVICE, 0x0001);
2016 	pci_set_cfgdata16(pi, PCIR_VENDOR, 0x10DD);
2017 	pci_set_cfgdata8(pi, PCIR_CLASS, 0x02);
2018 
2019 	error = pci_emul_add_msicap(pi, PCI_EMUL_MSI_MSGS);
2020 	assert(error == 0);
2021 
2022 	error = pci_emul_alloc_bar(pi, 0, PCIBAR_IO, DIOSZ);
2023 	assert(error == 0);
2024 
2025 	error = pci_emul_alloc_bar(pi, 1, PCIBAR_MEM32, DMEMSZ);
2026 	assert(error == 0);
2027 
2028 	error = pci_emul_alloc_bar(pi, 2, PCIBAR_MEM32, DMEMSZ);
2029 	assert(error == 0);
2030 
2031 	return (0);
2032 }
2033 
2034 static void
2035 pci_emul_diow(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2036 	      uint64_t offset, int size, uint64_t value)
2037 {
2038 	int i;
2039 	struct pci_emul_dsoftc *sc = pi->pi_arg;
2040 
2041 	if (baridx == 0) {
2042 		if (offset + size > DIOSZ) {
2043 			printf("diow: iow too large, offset %ld size %d\n",
2044 			       offset, size);
2045 			return;
2046 		}
2047 
2048 		if (size == 1) {
2049 			sc->ioregs[offset] = value & 0xff;
2050 		} else if (size == 2) {
2051 			*(uint16_t *)&sc->ioregs[offset] = value & 0xffff;
2052 		} else if (size == 4) {
2053 			*(uint32_t *)&sc->ioregs[offset] = value;
2054 		} else {
2055 			printf("diow: iow unknown size %d\n", size);
2056 		}
2057 
2058 		/*
2059 		 * Special magic value to generate an interrupt
2060 		 */
2061 		if (offset == 4 && size == 4 && pci_msi_enabled(pi))
2062 			pci_generate_msi(pi, value % pci_msi_maxmsgnum(pi));
2063 
2064 		if (value == 0xabcdef) {
2065 			for (i = 0; i < pci_msi_maxmsgnum(pi); i++)
2066 				pci_generate_msi(pi, i);
2067 		}
2068 	}
2069 
2070 	if (baridx == 1 || baridx == 2) {
2071 		if (offset + size > DMEMSZ) {
2072 			printf("diow: memw too large, offset %ld size %d\n",
2073 			       offset, size);
2074 			return;
2075 		}
2076 
2077 		i = baridx - 1;		/* 'memregs' index */
2078 
2079 		if (size == 1) {
2080 			sc->memregs[i][offset] = value;
2081 		} else if (size == 2) {
2082 			*(uint16_t *)&sc->memregs[i][offset] = value;
2083 		} else if (size == 4) {
2084 			*(uint32_t *)&sc->memregs[i][offset] = value;
2085 		} else if (size == 8) {
2086 			*(uint64_t *)&sc->memregs[i][offset] = value;
2087 		} else {
2088 			printf("diow: memw unknown size %d\n", size);
2089 		}
2090 
2091 		/*
2092 		 * magic interrupt ??
2093 		 */
2094 	}
2095 
2096 	if (baridx > 2 || baridx < 0) {
2097 		printf("diow: unknown bar idx %d\n", baridx);
2098 	}
2099 }
2100 
2101 static uint64_t
2102 pci_emul_dior(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2103 	      uint64_t offset, int size)
2104 {
2105 	struct pci_emul_dsoftc *sc = pi->pi_arg;
2106 	uint32_t value;
2107 	int i;
2108 
2109 	value = 0;
2110 	if (baridx == 0) {
2111 		if (offset + size > DIOSZ) {
2112 			printf("dior: ior too large, offset %ld size %d\n",
2113 			       offset, size);
2114 			return (0);
2115 		}
2116 
2117 		value = 0;
2118 		if (size == 1) {
2119 			value = sc->ioregs[offset];
2120 		} else if (size == 2) {
2121 			value = *(uint16_t *) &sc->ioregs[offset];
2122 		} else if (size == 4) {
2123 			value = *(uint32_t *) &sc->ioregs[offset];
2124 		} else {
2125 			printf("dior: ior unknown size %d\n", size);
2126 		}
2127 	}
2128 
2129 	if (baridx == 1 || baridx == 2) {
2130 		if (offset + size > DMEMSZ) {
2131 			printf("dior: memr too large, offset %ld size %d\n",
2132 			       offset, size);
2133 			return (0);
2134 		}
2135 
2136 		i = baridx - 1;		/* 'memregs' index */
2137 
2138 		if (size == 1) {
2139 			value = sc->memregs[i][offset];
2140 		} else if (size == 2) {
2141 			value = *(uint16_t *) &sc->memregs[i][offset];
2142 		} else if (size == 4) {
2143 			value = *(uint32_t *) &sc->memregs[i][offset];
2144 		} else if (size == 8) {
2145 			value = *(uint64_t *) &sc->memregs[i][offset];
2146 		} else {
2147 			printf("dior: ior unknown size %d\n", size);
2148 		}
2149 	}
2150 
2151 
2152 	if (baridx > 2 || baridx < 0) {
2153 		printf("dior: unknown bar idx %d\n", baridx);
2154 		return (0);
2155 	}
2156 
2157 	return (value);
2158 }
2159 
2160 struct pci_devemu pci_dummy = {
2161 	.pe_emu = "dummy",
2162 	.pe_init = pci_emul_dinit,
2163 	.pe_barwrite = pci_emul_diow,
2164 	.pe_barread = pci_emul_dior
2165 };
2166 PCI_EMUL_SET(pci_dummy);
2167 
2168 #endif /* PCI_EMUL_TEST */
2169