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