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