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