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