]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/pci_emul.c
Add support for MSI-X interrupts in the virtio network device and make that
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / pci_emul.c
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33 #include <sys/linker_set.h>
34
35 #include <ctype.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <strings.h>
40 #include <assert.h>
41
42 #include <machine/vmm.h>
43 #include <vmmapi.h>
44
45 #include "bhyverun.h"
46 #include "inout.h"
47 #include "mem.h"
48 #include "mptbl.h"
49 #include "pci_emul.h"
50 #include "ioapic.h"
51
52 #define CONF1_ADDR_PORT    0x0cf8
53 #define CONF1_DATA_PORT    0x0cfc
54
55 #define CFGWRITE(pi,off,val,b)                                          \
56 do {                                                                    \
57         if ((b) == 1) {                                                 \
58                 pci_set_cfgdata8((pi),(off),(val));                     \
59         } else if ((b) == 2) {                                          \
60                 pci_set_cfgdata16((pi),(off),(val));                    \
61         } else {                                                        \
62                 pci_set_cfgdata32((pi),(off),(val));                    \
63         }                                                               \
64 } while (0)
65
66 #define MAXSLOTS        (PCI_SLOTMAX + 1)
67 #define MAXFUNCS        (PCI_FUNCMAX + 1)
68
69 static struct slotinfo {
70         char    *si_name;
71         char    *si_param;
72         struct pci_devinst *si_devi;
73         int     si_legacy;
74 } pci_slotinfo[MAXSLOTS][MAXFUNCS];
75
76 /*
77  * Used to keep track of legacy interrupt owners/requestors
78  */
79 #define NLIRQ           16
80
81 static struct lirqinfo {
82         int     li_generic;
83         int     li_acount;
84         struct pci_devinst *li_owner;   /* XXX should be a list */
85 } lirq[NLIRQ];
86
87 SET_DECLARE(pci_devemu_set, struct pci_devemu);
88
89 static uint64_t pci_emul_iobase;
90 static uint64_t pci_emul_membase32;
91 static uint64_t pci_emul_membase64;
92
93 #define PCI_EMUL_IOBASE         0x2000
94 #define PCI_EMUL_IOLIMIT        0x10000
95
96 #define PCI_EMUL_MEMBASE32      (lomem_sz)
97 #define PCI_EMUL_MEMLIMIT32     0xE0000000              /* 3.5GB */
98
99 #define PCI_EMUL_MEMBASE64      0xD000000000UL
100 #define PCI_EMUL_MEMLIMIT64     0xFD00000000UL
101
102 static int pci_emul_devices;
103
104 /*
105  * I/O access
106  */
107
108 /*
109  * Slot options are in the form:
110  *
111  *  <slot>[:<func>],<emul>[,<config>]
112  *
113  *  slot is 0..31
114  *  func is 0..7
115  *  emul is a string describing the type of PCI device e.g. virtio-net
116  *  config is an optional string, depending on the device, that can be
117  *  used for configuration.
118  *   Examples are:
119  *     1,virtio-net,tap0
120  *     3:0,dummy
121  */
122 static void
123 pci_parse_slot_usage(char *aopt)
124 {
125         printf("Invalid PCI slot info field \"%s\"\n", aopt);
126         free(aopt);
127 }
128
129 void
130 pci_parse_slot(char *opt, int legacy)
131 {
132         char *slot, *func, *emul, *config;
133         char *str, *cpy;
134         int snum, fnum;
135
136         str = cpy = strdup(opt);
137
138         config = NULL;
139
140         if (strchr(str, ':') != NULL) {
141                 slot = strsep(&str, ":");
142                 func = strsep(&str, ",");
143         } else {
144                 slot = strsep(&str, ",");
145                 func = NULL;
146         }
147
148         emul = strsep(&str, ",");
149         if (str != NULL) {
150                 config = strsep(&str, ",");
151         }
152
153         if (emul == NULL) {
154                 pci_parse_slot_usage(cpy);
155                 return;
156         }
157
158         snum = atoi(slot);
159         fnum = func ? atoi(func) : 0;
160         if (snum < 0 || snum >= MAXSLOTS || fnum < 0 || fnum >= MAXFUNCS) {
161                 pci_parse_slot_usage(cpy);
162         } else {
163                 pci_slotinfo[snum][fnum].si_name = emul;
164                 pci_slotinfo[snum][fnum].si_param = config;
165                 pci_slotinfo[snum][fnum].si_legacy = legacy;
166         }
167 }
168
169 static int
170 pci_valid_pba_offset(struct pci_devinst *pi, uint64_t offset)
171 {
172
173         if (offset < pi->pi_msix.pba_offset)
174                 return (0);
175
176         if (offset >= pi->pi_msix.pba_offset + pi->pi_msix.pba_size) {
177                 return (0);
178         }
179
180         return (1);
181 }
182
183 int
184 pci_emul_msix_twrite(struct pci_devinst *pi, uint64_t offset, int size,
185                      uint64_t value)
186 {
187         int msix_entry_offset;
188         int tab_index;
189         char *dest;
190
191         /* support only 4 or 8 byte writes */
192         if (size != 4 && size != 8)
193                 return (-1);
194
195         /*
196          * Return if table index is beyond what device supports
197          */
198         tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
199         if (tab_index >= pi->pi_msix.table_count)
200                 return (-1);
201
202         msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
203
204         /* support only aligned writes */
205         if ((msix_entry_offset % size) != 0)
206                 return (-1);
207
208         dest = (char *)(pi->pi_msix.table + tab_index);
209         dest += msix_entry_offset;
210
211         if (size == 4)
212                 *((uint32_t *)dest) = value;
213         else
214                 *((uint64_t *)dest) = value;
215
216         return (0);
217 }
218
219 uint64_t
220 pci_emul_msix_tread(struct pci_devinst *pi, uint64_t offset, int size)
221 {
222         char *dest;
223         int msix_entry_offset;
224         int tab_index;
225         uint64_t retval = ~0;
226
227         /* support only 4 or 8 byte reads */
228         if (size != 4 && size != 8)
229                 return (retval);
230
231         msix_entry_offset = offset % MSIX_TABLE_ENTRY_SIZE;
232
233         /* support only aligned reads */
234         if ((msix_entry_offset % size) != 0) {
235                 return (retval);
236         }
237
238         tab_index = offset / MSIX_TABLE_ENTRY_SIZE;
239
240         if (tab_index < pi->pi_msix.table_count) {
241                 /* valid MSI-X Table access */
242                 dest = (char *)(pi->pi_msix.table + tab_index);
243                 dest += msix_entry_offset;
244
245                 if (size == 4)
246                         retval = *((uint32_t *)dest);
247                 else
248                         retval = *((uint64_t *)dest);
249         } else if (pci_valid_pba_offset(pi, offset)) {
250                 /* return 0 for PBA access */
251                 retval = 0;
252         }
253
254         return (retval);
255 }
256
257 static int
258 pci_emul_io_handler(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
259                     uint32_t *eax, void *arg)
260 {
261         struct pci_devinst *pdi = arg;
262         struct pci_devemu *pe = pdi->pi_d;
263         uint64_t offset;
264         int i;
265
266         for (i = 0; i <= PCI_BARMAX; i++) {
267                 if (pdi->pi_bar[i].type == PCIBAR_IO &&
268                     port >= pdi->pi_bar[i].addr &&
269                     port + bytes <= pdi->pi_bar[i].addr + pdi->pi_bar[i].size) {
270                         offset = port - pdi->pi_bar[i].addr;
271                         if (in)
272                                 *eax = (*pe->pe_barread)(ctx, vcpu, pdi, i,
273                                                          offset, bytes);
274                         else
275                                 (*pe->pe_barwrite)(ctx, vcpu, pdi, i, offset,
276                                                    bytes, *eax);
277                         return (0);
278                 }
279         }
280         return (-1);
281 }
282
283 static int
284 pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,
285                      int size, uint64_t *val, void *arg1, long arg2)
286 {
287         struct pci_devinst *pdi = arg1;
288         struct pci_devemu *pe = pdi->pi_d;
289         uint64_t offset;
290         int bidx = (int) arg2;
291
292         assert(bidx <= PCI_BARMAX);
293         assert(pdi->pi_bar[bidx].type == PCIBAR_MEM32 ||
294                pdi->pi_bar[bidx].type == PCIBAR_MEM64);
295         assert(addr >= pdi->pi_bar[bidx].addr &&
296                addr + size <= pdi->pi_bar[bidx].addr + pdi->pi_bar[bidx].size);
297
298         offset = addr - pdi->pi_bar[bidx].addr;
299
300         if (dir == MEM_F_WRITE)
301                 (*pe->pe_barwrite)(ctx, vcpu, pdi, bidx, offset, size, *val);
302         else
303                 *val = (*pe->pe_barread)(ctx, vcpu, pdi, bidx, offset, size);
304
305         return (0);
306 }
307
308
309 static int
310 pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,
311                         uint64_t *addr)
312 {
313         uint64_t base;
314
315         assert((size & (size - 1)) == 0);       /* must be a power of 2 */
316
317         base = roundup2(*baseptr, size);
318
319         if (base + size <= limit) {
320                 *addr = base;
321                 *baseptr = base + size;
322                 return (0);
323         } else
324                 return (-1);
325 }
326
327 int
328 pci_emul_alloc_bar(struct pci_devinst *pdi, int idx, enum pcibar_type type,
329                    uint64_t size)
330 {
331
332         return (pci_emul_alloc_pbar(pdi, idx, 0, type, size));
333 }
334
335 int
336 pci_emul_alloc_pbar(struct pci_devinst *pdi, int idx, uint64_t hostbase,
337                     enum pcibar_type type, uint64_t size)
338 {
339         int i, error;
340         uint64_t *baseptr, limit, addr, mask, lobits, bar;
341         struct inout_port iop;
342         struct mem_range memp;
343
344         assert(idx >= 0 && idx <= PCI_BARMAX);
345
346         if ((size & (size - 1)) != 0)
347                 size = 1UL << flsl(size);       /* round up to a power of 2 */
348
349         switch (type) {
350         case PCIBAR_NONE:
351                 baseptr = NULL;
352                 addr = mask = lobits = 0;
353                 break;
354         case PCIBAR_IO:
355                 if (hostbase &&
356                     pci_slotinfo[pdi->pi_slot][pdi->pi_func].si_legacy) {
357                         assert(hostbase < PCI_EMUL_IOBASE);
358                         baseptr = &hostbase;
359                 } else {
360                         baseptr = &pci_emul_iobase;
361                 }
362                 limit = PCI_EMUL_IOLIMIT;
363                 mask = PCIM_BAR_IO_BASE;
364                 lobits = PCIM_BAR_IO_SPACE;
365                 break;
366         case PCIBAR_MEM64:
367                 /*
368                  * XXX
369                  * Some drivers do not work well if the 64-bit BAR is allocated
370                  * above 4GB. Allow for this by allocating small requests under
371                  * 4GB unless then allocation size is larger than some arbitrary
372                  * number (32MB currently).
373                  */
374                 if (size > 32 * 1024 * 1024) {
375                         /*
376                          * XXX special case for device requiring peer-peer DMA
377                          */
378                         if (size == 0x100000000UL)
379                                 baseptr = &hostbase;
380                         else
381                                 baseptr = &pci_emul_membase64;
382                         limit = PCI_EMUL_MEMLIMIT64;
383                         mask = PCIM_BAR_MEM_BASE;
384                         lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
385                                  PCIM_BAR_MEM_PREFETCH;
386                         break;
387                 } else {
388                         baseptr = &pci_emul_membase32;
389                         limit = PCI_EMUL_MEMLIMIT32;
390                         mask = PCIM_BAR_MEM_BASE;
391                         lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64;
392                 }
393                 break;
394         case PCIBAR_MEM32:
395                 baseptr = &pci_emul_membase32;
396                 limit = PCI_EMUL_MEMLIMIT32;
397                 mask = PCIM_BAR_MEM_BASE;
398                 lobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
399                 break;
400         default:
401                 printf("pci_emul_alloc_base: invalid bar type %d\n", type);
402                 assert(0);
403         }
404
405         if (baseptr != NULL) {
406                 error = pci_emul_alloc_resource(baseptr, limit, size, &addr);
407                 if (error != 0)
408                         return (error);
409         }
410
411         pdi->pi_bar[idx].type = type;
412         pdi->pi_bar[idx].addr = addr;
413         pdi->pi_bar[idx].size = size;
414
415         /* Initialize the BAR register in config space */
416         bar = (addr & mask) | lobits;
417         pci_set_cfgdata32(pdi, PCIR_BAR(idx), bar);
418
419         if (type == PCIBAR_MEM64) {
420                 assert(idx + 1 <= PCI_BARMAX);
421                 pdi->pi_bar[idx + 1].type = PCIBAR_MEMHI64;
422                 pci_set_cfgdata32(pdi, PCIR_BAR(idx + 1), bar >> 32);
423         }
424         
425         /* add a handler to intercept accesses to the I/O bar */
426         if (type == PCIBAR_IO) {
427                 iop.name = pdi->pi_name;
428                 iop.flags = IOPORT_F_INOUT;
429                 iop.handler = pci_emul_io_handler;
430                 iop.arg = pdi;
431
432                 for (i = 0; i < size; i++) {
433                         iop.port = addr + i;
434                         register_inout(&iop);
435                 }
436         } else if (type == PCIBAR_MEM32 || type == PCIBAR_MEM64) {
437                 /* add memory bar intercept handler */
438                 memp.name = pdi->pi_name;
439                 memp.flags = MEM_F_RW;
440                 memp.base = addr;
441                 memp.size = size;
442                 memp.handler = pci_emul_mem_handler;
443                 memp.arg1 = pdi;
444                 memp.arg2 = idx;
445
446                 error = register_mem(&memp);
447                 assert(error == 0);
448         }
449
450         return (0);
451 }
452
453 #define CAP_START_OFFSET        0x40
454 static int
455 pci_emul_add_capability(struct pci_devinst *pi, u_char *capdata, int caplen)
456 {
457         int i, capoff, capid, reallen;
458         uint16_t sts;
459
460         static u_char endofcap[4] = {
461                 PCIY_RESERVED, 0, 0, 0
462         };
463
464         assert(caplen > 0 && capdata[0] != PCIY_RESERVED);
465
466         reallen = roundup2(caplen, 4);          /* dword aligned */
467
468         sts = pci_get_cfgdata16(pi, PCIR_STATUS);
469         if ((sts & PCIM_STATUS_CAPPRESENT) == 0) {
470                 capoff = CAP_START_OFFSET;
471                 pci_set_cfgdata8(pi, PCIR_CAP_PTR, capoff);
472                 pci_set_cfgdata16(pi, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT);
473         } else {
474                 capoff = pci_get_cfgdata8(pi, PCIR_CAP_PTR);
475                 while (1) {
476                         assert((capoff & 0x3) == 0);
477                         capid = pci_get_cfgdata8(pi, capoff);
478                         if (capid == PCIY_RESERVED)
479                                 break;
480                         capoff = pci_get_cfgdata8(pi, capoff + 1);
481                 }
482         }
483
484         /* Check if we have enough space */
485         if (capoff + reallen + sizeof(endofcap) > PCI_REGMAX + 1)
486                 return (-1);
487
488         /* Copy the capability */
489         for (i = 0; i < caplen; i++)
490                 pci_set_cfgdata8(pi, capoff + i, capdata[i]);
491
492         /* Set the next capability pointer */
493         pci_set_cfgdata8(pi, capoff + 1, capoff + reallen);
494
495         /* Copy of the reserved capability which serves as the end marker */
496         for (i = 0; i < sizeof(endofcap); i++)
497                 pci_set_cfgdata8(pi, capoff + reallen + i, endofcap[i]);
498
499         return (0);
500 }
501
502 static struct pci_devemu *
503 pci_emul_finddev(char *name)
504 {
505         struct pci_devemu **pdpp, *pdp;
506
507         SET_FOREACH(pdpp, pci_devemu_set) {
508                 pdp = *pdpp;
509                 if (!strcmp(pdp->pe_emu, name)) {
510                         return (pdp);
511                 }
512         }
513
514         return (NULL);
515 }
516
517 static void
518 pci_emul_init(struct vmctx *ctx, struct pci_devemu *pde, int slot, int func,
519               char *params)
520 {
521         struct pci_devinst *pdi;
522         pdi = malloc(sizeof(struct pci_devinst));
523         bzero(pdi, sizeof(*pdi));
524
525         pdi->pi_vmctx = ctx;
526         pdi->pi_bus = 0;
527         pdi->pi_slot = slot;
528         pdi->pi_func = func;
529         pdi->pi_d = pde;
530         snprintf(pdi->pi_name, PI_NAMESZ, "%s-pci-%d", pde->pe_emu, slot);
531
532         /* Disable legacy interrupts */
533         pci_set_cfgdata8(pdi, PCIR_INTLINE, 255);
534         pci_set_cfgdata8(pdi, PCIR_INTPIN, 0);
535
536         pci_set_cfgdata8(pdi, PCIR_COMMAND,
537                     PCIM_CMD_PORTEN | PCIM_CMD_MEMEN | PCIM_CMD_BUSMASTEREN);
538
539         if ((*pde->pe_init)(ctx, pdi, params) != 0) {
540                 free(pdi);
541         } else {
542                 pci_emul_devices++;
543                 pci_slotinfo[slot][func].si_devi = pdi;
544         }       
545 }
546
547 void
548 pci_populate_msicap(struct msicap *msicap, int msgnum, int nextptr)
549 {
550         int mmc;
551
552         CTASSERT(sizeof(struct msicap) == 14);
553
554         /* Number of msi messages must be a power of 2 between 1 and 32 */
555         assert((msgnum & (msgnum - 1)) == 0 && msgnum >= 1 && msgnum <= 32);
556         mmc = ffs(msgnum) - 1;
557
558         bzero(msicap, sizeof(struct msicap));
559         msicap->capid = PCIY_MSI;
560         msicap->nextptr = nextptr;
561         msicap->msgctrl = PCIM_MSICTRL_64BIT | (mmc << 1);
562 }
563
564 int
565 pci_emul_add_msicap(struct pci_devinst *pi, int msgnum)
566 {
567         struct msicap msicap;
568
569         pci_populate_msicap(&msicap, msgnum, 0);
570
571         return (pci_emul_add_capability(pi, (u_char *)&msicap, sizeof(msicap)));
572 }
573
574 static void
575 pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,
576                      uint32_t msix_tab_size, int nextptr)
577 {
578         CTASSERT(sizeof(struct msixcap) == 12);
579
580         assert(msix_tab_size % 4096 == 0);
581
582         bzero(msixcap, sizeof(struct msixcap));
583         msixcap->capid = PCIY_MSIX;
584         msixcap->nextptr = nextptr;
585
586         /*
587          * Message Control Register, all fields set to
588          * zero except for the Table Size.
589          * Note: Table size N is encoded as N-1
590          */
591         msixcap->msgctrl = msgnum - 1;
592
593         /*
594          * MSI-X BAR setup:
595          * - MSI-X table start at offset 0
596          * - PBA table starts at a 4K aligned offset after the MSI-X table
597          */
598         msixcap->table_info = barnum & PCIM_MSIX_BIR_MASK;
599         msixcap->pba_info = msix_tab_size | (barnum & PCIM_MSIX_BIR_MASK);
600 }
601
602 static void
603 pci_msix_table_init(struct pci_devinst *pi, int table_entries)
604 {
605         int i, table_size;
606
607         assert(table_entries > 0);
608         assert(table_entries <= MAX_MSIX_TABLE_ENTRIES);
609
610         table_size = table_entries * MSIX_TABLE_ENTRY_SIZE;
611         pi->pi_msix.table = malloc(table_size);
612         bzero(pi->pi_msix.table, table_size);
613
614         /* set mask bit of vector control register */
615         for (i = 0; i < table_entries; i++)
616                 pi->pi_msix.table[i].vector_control |= PCIM_MSIX_VCTRL_MASK;
617 }
618
619 int
620 pci_emul_add_msixcap(struct pci_devinst *pi, int msgnum, int barnum)
621 {
622         uint16_t pba_index;
623         uint32_t tab_size;
624         struct msixcap msixcap;
625
626         assert(msgnum >= 1 && msgnum <= MAX_MSIX_TABLE_ENTRIES);
627         assert(barnum >= 0 && barnum <= PCIR_MAX_BAR_0);
628         
629         tab_size = msgnum * MSIX_TABLE_ENTRY_SIZE;
630
631         /* Align table size to nearest 4K */
632         tab_size = roundup2(tab_size, 4096);
633
634         pi->pi_msix.table_bar = barnum;
635         pi->pi_msix.pba_bar   = barnum;
636         pi->pi_msix.table_offset = 0;
637         pi->pi_msix.table_count = msgnum;
638         pi->pi_msix.pba_offset = tab_size;
639
640         /* calculate the MMIO size required for MSI-X PBA */
641         pba_index = (msgnum - 1) / (PBA_TABLE_ENTRY_SIZE * 8);
642         pi->pi_msix.pba_size = (pba_index + 1) * PBA_TABLE_ENTRY_SIZE;
643
644         pci_msix_table_init(pi, msgnum);
645
646         pci_populate_msixcap(&msixcap, msgnum, barnum, tab_size, 0);
647
648         /* allocate memory for MSI-X Table and PBA */
649         pci_emul_alloc_bar(pi, barnum, PCIBAR_MEM32,
650                                 tab_size + pi->pi_msix.pba_size);
651
652         return (pci_emul_add_capability(pi, (u_char *)&msixcap,
653                                         sizeof(msixcap)));
654 }
655
656 void
657 msixcap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
658                  int bytes, uint32_t val)
659 {
660         uint16_t msgctrl, rwmask;
661         int off, table_bar;
662         
663         off = offset - capoff;
664         table_bar = pi->pi_msix.table_bar;
665         /* Message Control Register */
666         if (off == 2 && bytes == 2) {
667                 rwmask = PCIM_MSIXCTRL_MSIX_ENABLE | PCIM_MSIXCTRL_FUNCTION_MASK;
668                 msgctrl = pci_get_cfgdata16(pi, offset);
669                 msgctrl &= ~rwmask;
670                 msgctrl |= val & rwmask;
671                 val = msgctrl;
672
673                 pi->pi_msix.enabled = val & PCIM_MSIXCTRL_MSIX_ENABLE;
674                 pi->pi_msix.function_mask = val & PCIM_MSIXCTRL_FUNCTION_MASK;
675         } 
676         
677         CFGWRITE(pi, offset, val, bytes);
678 }
679
680 void
681 msicap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
682                 int bytes, uint32_t val)
683 {
684         uint16_t msgctrl, rwmask, msgdata, mme;
685         uint32_t addrlo;
686
687         /*
688          * If guest is writing to the message control register make sure
689          * we do not overwrite read-only fields.
690          */
691         if ((offset - capoff) == 2 && bytes == 2) {
692                 rwmask = PCIM_MSICTRL_MME_MASK | PCIM_MSICTRL_MSI_ENABLE;
693                 msgctrl = pci_get_cfgdata16(pi, offset);
694                 msgctrl &= ~rwmask;
695                 msgctrl |= val & rwmask;
696                 val = msgctrl;
697
698                 addrlo = pci_get_cfgdata32(pi, capoff + 4);
699                 if (msgctrl & PCIM_MSICTRL_64BIT)
700                         msgdata = pci_get_cfgdata16(pi, capoff + 12);
701                 else
702                         msgdata = pci_get_cfgdata16(pi, capoff + 8);
703
704                 /*
705                  * XXX check delivery mode, destination mode etc
706                  */
707                 mme = msgctrl & PCIM_MSICTRL_MME_MASK;
708                 pi->pi_msi.enabled = msgctrl & PCIM_MSICTRL_MSI_ENABLE ? 1 : 0;
709                 if (pi->pi_msi.enabled) {
710                         pi->pi_msi.cpu = (addrlo >> 12) & 0xff;
711                         pi->pi_msi.vector = msgdata & 0xff;
712                         pi->pi_msi.msgnum = 1 << (mme >> 4);
713                 } else {
714                         pi->pi_msi.cpu = 0;
715                         pi->pi_msi.vector = 0;
716                         pi->pi_msi.msgnum = 0;
717                 }
718         }
719
720         CFGWRITE(pi, offset, val, bytes);
721 }
722
723 /*
724  * This function assumes that 'coff' is in the capabilities region of the
725  * config space.
726  */
727 static void
728 pci_emul_capwrite(struct pci_devinst *pi, int offset, int bytes, uint32_t val)
729 {
730         int capid;
731         uint8_t capoff, nextoff;
732
733         /* Do not allow un-aligned writes */
734         if ((offset & (bytes - 1)) != 0)
735                 return;
736
737         /* Find the capability that we want to update */
738         capoff = CAP_START_OFFSET;
739         while (1) {
740                 capid = pci_get_cfgdata8(pi, capoff);
741                 if (capid == PCIY_RESERVED)
742                         break;
743
744                 nextoff = pci_get_cfgdata8(pi, capoff + 1);
745                 if (offset >= capoff && offset < nextoff)
746                         break;
747
748                 capoff = nextoff;
749         }
750         assert(offset >= capoff);
751
752         /*
753          * Capability ID and Next Capability Pointer are readonly
754          */
755         if (offset == capoff || offset == capoff + 1)
756                 return;
757
758         switch (capid) {
759         case PCIY_MSI:
760                 msicap_cfgwrite(pi, capoff, offset, bytes, val);
761                 break;
762         case PCIY_MSIX:
763                 msixcap_cfgwrite(pi, capoff, offset, bytes, val);
764                 break;
765         default:
766                 break;
767         }
768 }
769
770 static int
771 pci_emul_iscap(struct pci_devinst *pi, int offset)
772 {
773         int found;
774         uint16_t sts;
775         uint8_t capid, lastoff;
776
777         found = 0;
778         sts = pci_get_cfgdata16(pi, PCIR_STATUS);
779         if ((sts & PCIM_STATUS_CAPPRESENT) != 0) {
780                 lastoff = pci_get_cfgdata8(pi, PCIR_CAP_PTR);
781                 while (1) {
782                         assert((lastoff & 0x3) == 0);
783                         capid = pci_get_cfgdata8(pi, lastoff);
784                         if (capid == PCIY_RESERVED)
785                                 break;
786                         lastoff = pci_get_cfgdata8(pi, lastoff + 1);
787                 }
788                 if (offset >= CAP_START_OFFSET && offset <= lastoff)
789                         found = 1;
790         }
791         return (found);
792 }
793
794 void
795 init_pci(struct vmctx *ctx)
796 {
797         struct pci_devemu *pde;
798         struct slotinfo *si;
799         int slot, func;
800
801         pci_emul_iobase = PCI_EMUL_IOBASE;
802         pci_emul_membase32 = PCI_EMUL_MEMBASE32;
803         pci_emul_membase64 = PCI_EMUL_MEMBASE64;
804
805         for (slot = 0; slot < MAXSLOTS; slot++) {
806                 for (func = 0; func < MAXFUNCS; func++) {
807                         si = &pci_slotinfo[slot][func];
808                         if (si->si_name != NULL) {
809                                 pde = pci_emul_finddev(si->si_name);
810                                 if (pde != NULL) {
811                                         pci_emul_init(ctx, pde, slot, func,
812                                                       si->si_param);
813                                 }
814                         }
815                 }
816         }
817
818         /*
819          * Allow ISA IRQs 5,10,11,12, and 15 to be available for
820          * generic use
821          */
822         lirq[5].li_generic = 1;
823         lirq[10].li_generic = 1;
824         lirq[11].li_generic = 1;
825         lirq[12].li_generic = 1;
826         lirq[15].li_generic = 1;
827 }
828
829 int
830 pci_msi_enabled(struct pci_devinst *pi)
831 {
832         return (pi->pi_msi.enabled);
833 }
834
835 int
836 pci_msi_msgnum(struct pci_devinst *pi)
837 {
838         if (pi->pi_msi.enabled)
839                 return (pi->pi_msi.msgnum);
840         else
841                 return (0);
842 }
843
844 int
845 pci_msix_enabled(struct pci_devinst *pi)
846 {
847
848         return (pi->pi_msix.enabled && !pi->pi_msi.enabled);
849 }
850
851 void
852 pci_generate_msix(struct pci_devinst *pi, int index)
853 {
854         struct msix_table_entry *mte;
855
856         if (!pci_msix_enabled(pi))
857                 return;
858
859         if (pi->pi_msix.function_mask)
860                 return;
861
862         if (index >= pi->pi_msix.table_count)
863                 return;
864
865         mte = &pi->pi_msix.table[index];
866         if ((mte->vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
867                 /* XXX Set PBA bit if interrupt is disabled */
868                 vm_lapic_irq(pi->pi_vmctx,
869                              (mte->addr >> 12) & 0xff, mte->msg_data & 0xff);
870         }
871 }
872
873 void
874 pci_generate_msi(struct pci_devinst *pi, int msg)
875 {
876
877         if (pci_msi_enabled(pi) && msg < pci_msi_msgnum(pi)) {
878                 vm_lapic_irq(pi->pi_vmctx,
879                              pi->pi_msi.cpu,
880                              pi->pi_msi.vector + msg);
881         }
882 }
883
884 int
885 pci_is_legacy(struct pci_devinst *pi)
886 {
887
888         return (pci_slotinfo[pi->pi_slot][pi->pi_func].si_legacy);
889 }
890
891 static int
892 pci_lintr_alloc(struct pci_devinst *pi, int vec)
893 {
894         int i;
895
896         assert(vec < NLIRQ);
897
898         if (vec == -1) {
899                 for (i = 0; i < NLIRQ; i++) {
900                         if (lirq[i].li_generic &&
901                             lirq[i].li_owner == NULL) {
902                                 vec = i;
903                                 break;
904                         }
905                 }
906         } else {
907                 if (lirq[vec].li_owner != NULL) {
908                         vec = -1;
909                 }
910         }
911         assert(vec != -1);
912
913         lirq[vec].li_owner = pi;
914         pi->pi_lintr_pin = vec;
915
916         return (vec);
917 }
918
919 int
920 pci_lintr_request(struct pci_devinst *pi, int vec)
921 {
922
923         vec = pci_lintr_alloc(pi, vec);
924         pci_set_cfgdata8(pi, PCIR_INTLINE, vec);
925         pci_set_cfgdata8(pi, PCIR_INTPIN, 1);
926         return (0);
927 }
928
929 void
930 pci_lintr_assert(struct pci_devinst *pi)
931 {
932
933         assert(pi->pi_lintr_pin);
934         ioapic_assert_pin(pi->pi_vmctx, pi->pi_lintr_pin);
935 }
936
937 void
938 pci_lintr_deassert(struct pci_devinst *pi)
939 {
940
941         assert(pi->pi_lintr_pin);
942         ioapic_deassert_pin(pi->pi_vmctx, pi->pi_lintr_pin);
943 }
944
945 /*
946  * Return 1 if the emulated device in 'slot' is a multi-function device.
947  * Return 0 otherwise.
948  */
949 static int
950 pci_emul_is_mfdev(int slot)
951 {
952         int f, numfuncs;
953
954         numfuncs = 0;
955         for (f = 0; f < MAXFUNCS; f++) {
956                 if (pci_slotinfo[slot][f].si_devi != NULL) {
957                         numfuncs++;
958                 }
959         }
960         return (numfuncs > 1);
961 }
962
963 /*
964  * Ensure that the PCIM_MFDEV bit is properly set (or unset) depending on
965  * whether or not is a multi-function being emulated in the pci 'slot'.
966  */
967 static void
968 pci_emul_hdrtype_fixup(int slot, int off, int bytes, uint32_t *rv)
969 {
970         int mfdev;
971
972         if (off <= PCIR_HDRTYPE && off + bytes > PCIR_HDRTYPE) {
973                 mfdev = pci_emul_is_mfdev(slot);
974                 switch (bytes) {
975                 case 1:
976                 case 2:
977                         *rv &= ~PCIM_MFDEV;
978                         if (mfdev) {
979                                 *rv |= PCIM_MFDEV;
980                         }
981                         break;
982                 case 4:
983                         *rv &= ~(PCIM_MFDEV << 16);
984                         if (mfdev) {
985                                 *rv |= (PCIM_MFDEV << 16);
986                         }
987                         break;
988                 }
989         }
990 }
991
992 static int cfgbus, cfgslot, cfgfunc, cfgoff;
993
994 static int
995 pci_emul_cfgaddr(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
996                  uint32_t *eax, void *arg)
997 {
998         uint32_t x;
999
1000         assert(!in);
1001
1002         if (bytes != 4)
1003                 return (-1);
1004
1005         x = *eax;
1006         cfgoff = x & PCI_REGMAX;
1007         cfgfunc = (x >> 8) & PCI_FUNCMAX;
1008         cfgslot = (x >> 11) & PCI_SLOTMAX;
1009         cfgbus = (x >> 16) & PCI_BUSMAX;
1010
1011         return (0);
1012 }
1013 INOUT_PORT(pci_cfgaddr, CONF1_ADDR_PORT, IOPORT_F_OUT, pci_emul_cfgaddr);
1014
1015 static int
1016 pci_emul_cfgdata(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1017                  uint32_t *eax, void *arg)
1018 {
1019         struct pci_devinst *pi;
1020         struct pci_devemu *pe;
1021         int coff, idx, needcfg;
1022         uint64_t mask, bar;
1023
1024         assert(bytes == 1 || bytes == 2 || bytes == 4);
1025         
1026         if (cfgbus == 0)
1027                 pi = pci_slotinfo[cfgslot][cfgfunc].si_devi;
1028         else
1029                 pi = NULL;
1030
1031         coff = cfgoff + (port - CONF1_DATA_PORT);
1032
1033 #if 0
1034         printf("pcicfg-%s from 0x%0x of %d bytes (%d/%d/%d)\n\r",
1035                 in ? "read" : "write", coff, bytes, cfgbus, cfgslot, cfgfunc);
1036 #endif
1037
1038         /*
1039          * Just return if there is no device at this cfgslot:cfgfunc or
1040          * if the guest is doing an un-aligned access
1041          */
1042         if (pi == NULL || (coff & (bytes - 1)) != 0) {
1043                 if (in)
1044                         *eax = 0xffffffff;
1045                 return (0);
1046         }
1047
1048         pe = pi->pi_d;
1049
1050         /*
1051          * Config read
1052          */
1053         if (in) {
1054                 /* Let the device emulation override the default handler */
1055                 if (pe->pe_cfgread != NULL) {
1056                         needcfg = pe->pe_cfgread(ctx, vcpu, pi,
1057                                                     coff, bytes, eax);
1058                 } else {
1059                         needcfg = 1;
1060                 }
1061
1062                 if (needcfg) {
1063                         if (bytes == 1)
1064                                 *eax = pci_get_cfgdata8(pi, coff);
1065                         else if (bytes == 2)
1066                                 *eax = pci_get_cfgdata16(pi, coff);
1067                         else
1068                                 *eax = pci_get_cfgdata32(pi, coff);
1069                 }
1070
1071                 pci_emul_hdrtype_fixup(cfgslot, coff, bytes, eax);
1072         } else {
1073                 /* Let the device emulation override the default handler */
1074                 if (pe->pe_cfgwrite != NULL &&
1075                     (*pe->pe_cfgwrite)(ctx, vcpu, pi, coff, bytes, *eax) == 0)
1076                         return (0);
1077
1078                 /*
1079                  * Special handling for write to BAR registers
1080                  */
1081                 if (coff >= PCIR_BAR(0) && coff < PCIR_BAR(PCI_BARMAX + 1)) {
1082                         /*
1083                          * Ignore writes to BAR registers that are not
1084                          * 4-byte aligned.
1085                          */
1086                         if (bytes != 4 || (coff & 0x3) != 0)
1087                                 return (0);
1088                         idx = (coff - PCIR_BAR(0)) / 4;
1089                         switch (pi->pi_bar[idx].type) {
1090                         case PCIBAR_NONE:
1091                                 bar = 0;
1092                                 break;
1093                         case PCIBAR_IO:
1094                                 mask = ~(pi->pi_bar[idx].size - 1);
1095                                 mask &= PCIM_BAR_IO_BASE;
1096                                 bar = (*eax & mask) | PCIM_BAR_IO_SPACE;
1097                                 break;
1098                         case PCIBAR_MEM32:
1099                                 mask = ~(pi->pi_bar[idx].size - 1);
1100                                 mask &= PCIM_BAR_MEM_BASE;
1101                                 bar = *eax & mask;
1102                                 bar |= PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;
1103                                 break;
1104                         case PCIBAR_MEM64:
1105                                 mask = ~(pi->pi_bar[idx].size - 1);
1106                                 mask &= PCIM_BAR_MEM_BASE;
1107                                 bar = *eax & mask;
1108                                 bar |= PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_64 |
1109                                        PCIM_BAR_MEM_PREFETCH;
1110                                 break;
1111                         case PCIBAR_MEMHI64:
1112                                 mask = ~(pi->pi_bar[idx - 1].size - 1);
1113                                 mask &= PCIM_BAR_MEM_BASE;
1114                                 bar = ((uint64_t)*eax << 32) & mask;
1115                                 bar = bar >> 32;
1116                                 break;
1117                         default:
1118                                 assert(0);
1119                         }
1120                         pci_set_cfgdata32(pi, coff, bar);
1121
1122                 } else if (pci_emul_iscap(pi, coff)) {
1123                         pci_emul_capwrite(pi, coff, bytes, *eax);
1124                 } else {
1125                         CFGWRITE(pi, coff, *eax, bytes);
1126                 }
1127         }
1128
1129         return (0);
1130 }
1131
1132 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+0, IOPORT_F_INOUT, pci_emul_cfgdata);
1133 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+1, IOPORT_F_INOUT, pci_emul_cfgdata);
1134 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+2, IOPORT_F_INOUT, pci_emul_cfgdata);
1135 INOUT_PORT(pci_cfgdata, CONF1_DATA_PORT+3, IOPORT_F_INOUT, pci_emul_cfgdata);
1136
1137 /*
1138  * I/O ports to configure PCI IRQ routing. We ignore all writes to it.
1139  */
1140 static int
1141 pci_irq_port_handler(struct vmctx *ctx, int vcpu, int in, int port, int bytes,
1142                      uint32_t *eax, void *arg)
1143 {
1144         assert(in == 0);
1145         return (0);
1146 }
1147 INOUT_PORT(pci_irq, 0xC00, IOPORT_F_OUT, pci_irq_port_handler);
1148 INOUT_PORT(pci_irq, 0xC01, IOPORT_F_OUT, pci_irq_port_handler);
1149
1150 #define PCI_EMUL_TEST
1151 #ifdef PCI_EMUL_TEST
1152 /*
1153  * Define a dummy test device
1154  */
1155 #define DIOSZ   20
1156 #define DMEMSZ  4096
1157 struct pci_emul_dsoftc {
1158         uint8_t   ioregs[DIOSZ];
1159         uint8_t   memregs[DMEMSZ];
1160 };
1161
1162 #define PCI_EMUL_MSI_MSGS        4
1163 #define PCI_EMUL_MSIX_MSGS      16
1164
1165 static int
1166 pci_emul_dinit(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
1167 {
1168         int error;
1169         struct pci_emul_dsoftc *sc;
1170
1171         sc = malloc(sizeof(struct pci_emul_dsoftc));
1172         memset(sc, 0, sizeof(struct pci_emul_dsoftc));
1173
1174         pi->pi_arg = sc;
1175
1176         pci_set_cfgdata16(pi, PCIR_DEVICE, 0x0001);
1177         pci_set_cfgdata16(pi, PCIR_VENDOR, 0x10DD);
1178         pci_set_cfgdata8(pi, PCIR_CLASS, 0x02);
1179
1180         error = pci_emul_add_msicap(pi, PCI_EMUL_MSI_MSGS);
1181         assert(error == 0);
1182
1183         error = pci_emul_alloc_bar(pi, 0, PCIBAR_IO, DIOSZ);
1184         assert(error == 0);
1185
1186         error = pci_emul_alloc_bar(pi, 1, PCIBAR_MEM32, DMEMSZ);
1187         assert(error == 0);
1188
1189         return (0);
1190 }
1191
1192 static void
1193 pci_emul_diow(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
1194               uint64_t offset, int size, uint64_t value)
1195 {
1196         int i;
1197         struct pci_emul_dsoftc *sc = pi->pi_arg;
1198
1199         if (baridx == 0) {
1200                 if (offset + size > DIOSZ) {
1201                         printf("diow: iow too large, offset %ld size %d\n",
1202                                offset, size);
1203                         return;
1204                 }
1205
1206                 if (size == 1) {
1207                         sc->ioregs[offset] = value & 0xff;
1208                 } else if (size == 2) {
1209                         *(uint16_t *)&sc->ioregs[offset] = value & 0xffff;
1210                 } else if (size == 4) {
1211                         *(uint32_t *)&sc->ioregs[offset] = value;
1212                 } else {
1213                         printf("diow: iow unknown size %d\n", size);
1214                 }
1215
1216                 /*
1217                  * Special magic value to generate an interrupt
1218                  */
1219                 if (offset == 4 && size == 4 && pci_msi_enabled(pi))
1220                         pci_generate_msi(pi, value % pci_msi_msgnum(pi));
1221
1222                 if (value == 0xabcdef) {
1223                         for (i = 0; i < pci_msi_msgnum(pi); i++)
1224                                 pci_generate_msi(pi, i);
1225                 }
1226         }
1227
1228         if (baridx == 1) {
1229                 if (offset + size > DMEMSZ) {
1230                         printf("diow: memw too large, offset %ld size %d\n",
1231                                offset, size);
1232                         return;
1233                 }
1234
1235                 if (size == 1) {
1236                         sc->memregs[offset] = value;
1237                 } else if (size == 2) {
1238                         *(uint16_t *)&sc->memregs[offset] = value;
1239                 } else if (size == 4) {
1240                         *(uint32_t *)&sc->memregs[offset] = value;
1241                 } else if (size == 8) {
1242                         *(uint64_t *)&sc->memregs[offset] = value;
1243                 } else {
1244                         printf("diow: memw unknown size %d\n", size);
1245                 }
1246                 
1247                 /*
1248                  * magic interrupt ??
1249                  */
1250         }
1251
1252         if (baridx > 1) {
1253                 printf("diow: unknown bar idx %d\n", baridx);
1254         }
1255 }
1256
1257 static uint64_t
1258 pci_emul_dior(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
1259               uint64_t offset, int size)
1260 {
1261         struct pci_emul_dsoftc *sc = pi->pi_arg;
1262         uint32_t value;
1263
1264         if (baridx == 0) {
1265                 if (offset + size > DIOSZ) {
1266                         printf("dior: ior too large, offset %ld size %d\n",
1267                                offset, size);
1268                         return (0);
1269                 }
1270         
1271                 if (size == 1) {
1272                         value = sc->ioregs[offset];
1273                 } else if (size == 2) {
1274                         value = *(uint16_t *) &sc->ioregs[offset];
1275                 } else if (size == 4) {
1276                         value = *(uint32_t *) &sc->ioregs[offset];
1277                 } else {
1278                         printf("dior: ior unknown size %d\n", size);
1279                 }
1280         }
1281         
1282         if (baridx == 1) {
1283                 if (offset + size > DMEMSZ) {
1284                         printf("dior: memr too large, offset %ld size %d\n",
1285                                offset, size);
1286                         return (0);
1287                 }
1288         
1289                 if (size == 1) {
1290                         value = sc->memregs[offset];
1291                 } else if (size == 2) {
1292                         value = *(uint16_t *) &sc->memregs[offset];
1293                 } else if (size == 4) {
1294                         value = *(uint32_t *) &sc->memregs[offset];
1295                 } else if (size == 8) {
1296                         value = *(uint64_t *) &sc->memregs[offset];
1297                 } else {
1298                         printf("dior: ior unknown size %d\n", size);
1299                 }
1300         }
1301
1302
1303         if (baridx > 1) {
1304                 printf("dior: unknown bar idx %d\n", baridx);
1305                 return (0);
1306         }
1307
1308         return (value);
1309 }
1310
1311 struct pci_devemu pci_dummy = {
1312         .pe_emu = "dummy",
1313         .pe_init = pci_emul_dinit,
1314         .pe_barwrite = pci_emul_diow,
1315         .pe_barread = pci_emul_dior
1316 };
1317 PCI_EMUL_SET(pci_dummy);
1318
1319 #endif /* PCI_EMUL_TEST */