Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / seabios / src / fw / pciinit.c
1 // Initialize PCI devices (on emulators)
2 //
3 // Copyright (C) 2008  Kevin O'Connor <kevin@koconnor.net>
4 // Copyright (C) 2006 Fabrice Bellard
5 //
6 // This file may be distributed under the terms of the GNU LGPLv3 license.
7
8 #include "byteorder.h" // le64_to_cpu
9 #include "config.h" // CONFIG_*
10 #include "dev-q35.h" // Q35_HOST_BRIDGE_PCIEXBAR_ADDR
11 #include "dev-piix.h" // PIIX_*
12 #include "hw/ata.h" // PORT_ATA1_CMD_BASE
13 #include "hw/pci.h" // pci_config_readl
14 #include "hw/pci_ids.h" // PCI_VENDOR_ID_INTEL
15 #include "hw/pci_regs.h" // PCI_COMMAND
16 #include "list.h" // struct hlist_node
17 #include "malloc.h" // free
18 #include "memmap.h" // add_e820
19 #include "output.h" // dprintf
20 #include "paravirt.h" // RamSize
21 #include "romfile.h" // romfile_loadint
22 #include "string.h" // memset
23 #include "util.h" // pci_setup
24 #include "x86.h" // outb
25
26 #define PCI_DEVICE_MEM_MIN    (1<<12)  // 4k == page size
27 #define PCI_BRIDGE_MEM_MIN    (1<<21)  // 2M == hugepage size
28 #define PCI_BRIDGE_IO_MIN      0x1000  // mandated by pci bridge spec
29
30 static const char *region_type_name[] = {
31     [ PCI_REGION_TYPE_IO ]      = "io",
32     [ PCI_REGION_TYPE_MEM ]     = "mem",
33     [ PCI_REGION_TYPE_PREFMEM ] = "prefmem",
34 };
35
36 u64 pcimem_start   = BUILD_PCIMEM_START;
37 u64 pcimem_end     = BUILD_PCIMEM_END;
38 u64 pcimem64_start = BUILD_PCIMEM64_START;
39 u64 pcimem64_end   = BUILD_PCIMEM64_END;
40 u64 pci_io_low_end = 0xa000;
41
42 struct pci_region_entry {
43     struct pci_device *dev;
44     int bar;
45     u64 size;
46     u64 align;
47     int is64;
48     enum pci_region_type type;
49     struct hlist_node node;
50 };
51
52 struct pci_region {
53     /* pci region assignments */
54     u64 base;
55     struct hlist_head list;
56 };
57
58 struct pci_bus {
59     struct pci_region r[PCI_REGION_TYPE_COUNT];
60     struct pci_device *bus_dev;
61 };
62
63 static u32 pci_bar(struct pci_device *pci, int region_num)
64 {
65     if (region_num != PCI_ROM_SLOT) {
66         return PCI_BASE_ADDRESS_0 + region_num * 4;
67     }
68
69 #define PCI_HEADER_TYPE_MULTI_FUNCTION 0x80
70     u8 type = pci->header_type & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
71     return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
72 }
73
74 static void
75 pci_set_io_region_addr(struct pci_device *pci, int bar, u64 addr, int is64)
76 {
77     u32 ofs = pci_bar(pci, bar);
78     pci_config_writel(pci->bdf, ofs, addr);
79     if (is64)
80         pci_config_writel(pci->bdf, ofs + 4, addr >> 32);
81 }
82
83
84 /****************************************************************
85  * Misc. device init
86  ****************************************************************/
87
88 /* host irqs corresponding to PCI irqs A-D */
89 const u8 pci_irqs[4] = {
90     10, 10, 11, 11
91 };
92
93 static int dummy_pci_slot_get_irq(struct pci_device *pci, int pin)
94 {
95     dprintf(1, "pci_slot_get_irq called with unknown routing\n");
96
97     return 0xff; /* PCI defined "unknown" or "no connection" for x86 */
98 }
99
100 static int (*pci_slot_get_irq)(struct pci_device *pci, int pin) =
101     dummy_pci_slot_get_irq;
102
103 // Return the global irq number corresponding to a host bus device irq pin.
104 static int piix_pci_slot_get_irq(struct pci_device *pci, int pin)
105 {
106     int slot_addend = 0;
107
108     while (pci->parent != NULL) {
109         slot_addend += pci_bdf_to_dev(pci->bdf);
110         pci = pci->parent;
111     }
112     slot_addend += pci_bdf_to_dev(pci->bdf) - 1;
113     return pci_irqs[(pin - 1 + slot_addend) & 3];
114 }
115
116 static int mch_pci_slot_get_irq(struct pci_device *pci, int pin)
117 {
118     int pin_addend = 0;
119     while (pci->parent != NULL) {
120         pin_addend += pci_bdf_to_dev(pci->bdf);
121         pci = pci->parent;
122     }
123     u8 slot = pci_bdf_to_dev(pci->bdf);
124     if (slot <= 24)
125         /* Slots 0-24 rotate slot:pin mapping similar to piix above, but
126            with a different starting index - see q35-acpi-dsdt.dsl */
127         return pci_irqs[(pin - 1 + pin_addend + slot) & 3];
128     /* Slots 25-31 all use LNKA mapping (or LNKE, but A:D = E:H) */
129     return pci_irqs[(pin - 1 + pin_addend) & 3];
130 }
131
132 /* PIIX3/PIIX4 PCI to ISA bridge */
133 static void piix_isa_bridge_setup(struct pci_device *pci, void *arg)
134 {
135     int i, irq;
136     u8 elcr[2];
137
138     elcr[0] = 0x00;
139     elcr[1] = 0x00;
140     for (i = 0; i < 4; i++) {
141         irq = pci_irqs[i];
142         /* set to trigger level */
143         elcr[irq >> 3] |= (1 << (irq & 7));
144         /* activate irq remapping in PIIX */
145         pci_config_writeb(pci->bdf, 0x60 + i, irq);
146     }
147     outb(elcr[0], PIIX_PORT_ELCR1);
148     outb(elcr[1], PIIX_PORT_ELCR2);
149     dprintf(1, "PIIX3/PIIX4 init: elcr=%02x %02x\n", elcr[0], elcr[1]);
150 }
151
152 /* ICH9 LPC PCI to ISA bridge */
153 /* PCI_VENDOR_ID_INTEL && PCI_DEVICE_ID_INTEL_ICH9_LPC */
154 static void mch_isa_bridge_setup(struct pci_device *dev, void *arg)
155 {
156     u16 bdf = dev->bdf;
157     int i, irq;
158     u8 elcr[2];
159
160     elcr[0] = 0x00;
161     elcr[1] = 0x00;
162
163     for (i = 0; i < 4; i++) {
164         irq = pci_irqs[i];
165         /* set to trigger level */
166         elcr[irq >> 3] |= (1 << (irq & 7));
167
168         /* activate irq remapping in LPC */
169
170         /* PIRQ[A-D] routing */
171         pci_config_writeb(bdf, ICH9_LPC_PIRQA_ROUT + i, irq);
172         /* PIRQ[E-H] routing */
173         pci_config_writeb(bdf, ICH9_LPC_PIRQE_ROUT + i, irq);
174     }
175     outb(elcr[0], ICH9_LPC_PORT_ELCR1);
176     outb(elcr[1], ICH9_LPC_PORT_ELCR2);
177     dprintf(1, "Q35 LPC init: elcr=%02x %02x\n", elcr[0], elcr[1]);
178
179     /* pm io base */
180     pci_config_writel(bdf, ICH9_LPC_PMBASE,
181                       acpi_pm_base | ICH9_LPC_PMBASE_RTE);
182
183     /* acpi enable, SCI: IRQ9 000b = irq9*/
184     pci_config_writeb(bdf, ICH9_LPC_ACPI_CTRL, ICH9_LPC_ACPI_CTRL_ACPI_EN);
185
186     acpi_pm1a_cnt = acpi_pm_base + 0x04;
187     pmtimer_setup(acpi_pm_base + 0x08);
188 }
189
190 static void storage_ide_setup(struct pci_device *pci, void *arg)
191 {
192     /* IDE: we map it as in ISA mode */
193     pci_set_io_region_addr(pci, 0, PORT_ATA1_CMD_BASE, 0);
194     pci_set_io_region_addr(pci, 1, PORT_ATA1_CTRL_BASE, 0);
195     pci_set_io_region_addr(pci, 2, PORT_ATA2_CMD_BASE, 0);
196     pci_set_io_region_addr(pci, 3, PORT_ATA2_CTRL_BASE, 0);
197 }
198
199 /* PIIX3/PIIX4 IDE */
200 static void piix_ide_setup(struct pci_device *pci, void *arg)
201 {
202     u16 bdf = pci->bdf;
203     pci_config_writew(bdf, 0x40, 0x8000); // enable IDE0
204     pci_config_writew(bdf, 0x42, 0x8000); // enable IDE1
205 }
206
207 static void pic_ibm_setup(struct pci_device *pci, void *arg)
208 {
209     /* PIC, IBM, MPIC & MPIC2 */
210     pci_set_io_region_addr(pci, 0, 0x80800000 + 0x00040000, 0);
211 }
212
213 static void apple_macio_setup(struct pci_device *pci, void *arg)
214 {
215     /* macio bridge */
216     pci_set_io_region_addr(pci, 0, 0x80800000, 0);
217 }
218
219 static void piix4_pm_config_setup(u16 bdf)
220 {
221     // acpi sci is hardwired to 9
222     pci_config_writeb(bdf, PCI_INTERRUPT_LINE, 9);
223
224     pci_config_writel(bdf, PIIX_PMBASE, acpi_pm_base | 1);
225     pci_config_writeb(bdf, PIIX_PMREGMISC, 0x01); /* enable PM io space */
226     pci_config_writel(bdf, PIIX_SMBHSTBASE, (acpi_pm_base + 0x100) | 1);
227     pci_config_writeb(bdf, PIIX_SMBHSTCFG, 0x09); /* enable SMBus io space */
228 }
229
230 static int PiixPmBDF = -1;
231
232 /* PIIX4 Power Management device (for ACPI) */
233 static void piix4_pm_setup(struct pci_device *pci, void *arg)
234 {
235     PiixPmBDF = pci->bdf;
236     piix4_pm_config_setup(pci->bdf);
237
238     acpi_pm1a_cnt = acpi_pm_base + 0x04;
239     pmtimer_setup(acpi_pm_base + 0x08);
240 }
241
242 /* ICH9 SMBUS */
243 /* PCI_VENDOR_ID_INTEL && PCI_DEVICE_ID_INTEL_ICH9_SMBUS */
244 static void ich9_smbus_setup(struct pci_device *dev, void *arg)
245 {
246     u16 bdf = dev->bdf;
247     /* map smbus into io space */
248     pci_config_writel(bdf, ICH9_SMB_SMB_BASE,
249                       (acpi_pm_base + 0x100) | PCI_BASE_ADDRESS_SPACE_IO);
250
251     /* enable SMBus */
252     pci_config_writeb(bdf, ICH9_SMB_HOSTC, ICH9_SMB_HOSTC_HST_EN);
253 }
254
255 static const struct pci_device_id pci_device_tbl[] = {
256     /* PIIX3/PIIX4 PCI to ISA bridge */
257     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371SB_0,
258                piix_isa_bridge_setup),
259     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_0,
260                piix_isa_bridge_setup),
261     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_LPC,
262                mch_isa_bridge_setup),
263
264     /* STORAGE IDE */
265     PCI_DEVICE_CLASS(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371SB_1,
266                      PCI_CLASS_STORAGE_IDE, piix_ide_setup),
267     PCI_DEVICE_CLASS(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB,
268                      PCI_CLASS_STORAGE_IDE, piix_ide_setup),
269     PCI_DEVICE_CLASS(PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE,
270                      storage_ide_setup),
271
272     /* PIC, IBM, MIPC & MPIC2 */
273     PCI_DEVICE_CLASS(PCI_VENDOR_ID_IBM, 0x0046, PCI_CLASS_SYSTEM_PIC,
274                      pic_ibm_setup),
275     PCI_DEVICE_CLASS(PCI_VENDOR_ID_IBM, 0xFFFF, PCI_CLASS_SYSTEM_PIC,
276                      pic_ibm_setup),
277
278     /* PIIX4 Power Management device (for ACPI) */
279     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3,
280                piix4_pm_setup),
281     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_SMBUS,
282                ich9_smbus_setup),
283
284     /* 0xff00 */
285     PCI_DEVICE_CLASS(PCI_VENDOR_ID_APPLE, 0x0017, 0xff00, apple_macio_setup),
286     PCI_DEVICE_CLASS(PCI_VENDOR_ID_APPLE, 0x0022, 0xff00, apple_macio_setup),
287
288     PCI_DEVICE_END,
289 };
290
291 void pci_resume(void)
292 {
293     if (!CONFIG_QEMU) {
294         return;
295     }
296
297     if (PiixPmBDF >= 0) {
298         piix4_pm_config_setup(PiixPmBDF);
299     }
300 }
301
302 static void pci_bios_init_device(struct pci_device *pci)
303 {
304     u16 bdf = pci->bdf;
305     dprintf(1, "PCI: init bdf=%02x:%02x.%x id=%04x:%04x\n"
306             , pci_bdf_to_bus(bdf), pci_bdf_to_dev(bdf), pci_bdf_to_fn(bdf)
307             , pci->vendor, pci->device);
308
309     /* map the interrupt */
310     int pin = pci_config_readb(bdf, PCI_INTERRUPT_PIN);
311     if (pin != 0)
312         pci_config_writeb(bdf, PCI_INTERRUPT_LINE, pci_slot_get_irq(pci, pin));
313
314     pci_init_device(pci_device_tbl, pci, NULL);
315
316     /* enable memory mappings */
317     pci_config_maskw(bdf, PCI_COMMAND, 0,
318                      PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_SERR);
319 }
320
321 static void pci_bios_init_devices(void)
322 {
323     struct pci_device *pci;
324     foreachpci(pci) {
325         pci_bios_init_device(pci);
326     }
327 }
328
329 static void pci_enable_default_vga(void)
330 {
331     struct pci_device *pci;
332
333     foreachpci(pci) {
334         if (is_pci_vga(pci)) {
335             dprintf(1, "PCI: Using %02x:%02x.%x for primary VGA\n",
336                     pci_bdf_to_bus(pci->bdf), pci_bdf_to_dev(pci->bdf),
337                     pci_bdf_to_fn(pci->bdf));
338             return;
339         }
340     }
341
342     pci = pci_find_class(PCI_CLASS_DISPLAY_VGA);
343     if (!pci) {
344         dprintf(1, "PCI: No VGA devices found\n");
345         return;
346     }
347
348     dprintf(1, "PCI: Enabling %02x:%02x.%x for primary VGA\n",
349             pci_bdf_to_bus(pci->bdf), pci_bdf_to_dev(pci->bdf),
350             pci_bdf_to_fn(pci->bdf));
351
352     pci_config_maskw(pci->bdf, PCI_COMMAND, 0,
353                      PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
354
355     while (pci->parent) {
356         pci = pci->parent;
357
358         dprintf(1, "PCI: Setting VGA enable on bridge %02x:%02x.%x\n",
359                 pci_bdf_to_bus(pci->bdf), pci_bdf_to_dev(pci->bdf),
360                 pci_bdf_to_fn(pci->bdf));
361
362         pci_config_maskw(pci->bdf, PCI_BRIDGE_CONTROL, 0, PCI_BRIDGE_CTL_VGA);
363         pci_config_maskw(pci->bdf, PCI_COMMAND, 0,
364                          PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
365     }
366 }
367
368 /****************************************************************
369  * Platform device initialization
370  ****************************************************************/
371
372 static void i440fx_mem_addr_setup(struct pci_device *dev, void *arg)
373 {
374     if (RamSize <= 0x80000000)
375         pcimem_start = 0x80000000;
376     else if (RamSize <= 0xc0000000)
377         pcimem_start = 0xc0000000;
378
379     pci_slot_get_irq = piix_pci_slot_get_irq;
380 }
381
382 static void mch_mem_addr_setup(struct pci_device *dev, void *arg)
383 {
384     u64 addr = Q35_HOST_BRIDGE_PCIEXBAR_ADDR;
385     u32 size = Q35_HOST_BRIDGE_PCIEXBAR_SIZE;
386
387     /* setup mmconfig */
388     u16 bdf = dev->bdf;
389     u32 upper = addr >> 32;
390     u32 lower = (addr & 0xffffffff) | Q35_HOST_BRIDGE_PCIEXBAREN;
391     pci_config_writel(bdf, Q35_HOST_BRIDGE_PCIEXBAR, 0);
392     pci_config_writel(bdf, Q35_HOST_BRIDGE_PCIEXBAR + 4, upper);
393     pci_config_writel(bdf, Q35_HOST_BRIDGE_PCIEXBAR, lower);
394     add_e820(addr, size, E820_RESERVED);
395
396     /* setup pci i/o window (above mmconfig) */
397     pcimem_start = addr + size;
398
399     pci_slot_get_irq = mch_pci_slot_get_irq;
400
401     /* setup io address space */
402     if (acpi_pm_base < 0x1000)
403         pci_io_low_end = 0x10000;
404     else
405         pci_io_low_end = acpi_pm_base;
406 }
407
408 static const struct pci_device_id pci_platform_tbl[] = {
409     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441,
410                i440fx_mem_addr_setup),
411     PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_Q35_MCH,
412                mch_mem_addr_setup),
413     PCI_DEVICE_END
414 };
415
416 static void pci_bios_init_platform(void)
417 {
418     struct pci_device *pci;
419     foreachpci(pci) {
420         pci_init_device(pci_platform_tbl, pci, NULL);
421     }
422 }
423
424
425 /****************************************************************
426  * Bus initialization
427  ****************************************************************/
428
429 static void
430 pci_bios_init_bus_rec(int bus, u8 *pci_bus)
431 {
432     int bdf;
433     u16 class;
434
435     dprintf(1, "PCI: %s bus = 0x%x\n", __func__, bus);
436
437     /* prevent accidental access to unintended devices */
438     foreachbdf(bdf, bus) {
439         class = pci_config_readw(bdf, PCI_CLASS_DEVICE);
440         if (class == PCI_CLASS_BRIDGE_PCI) {
441             pci_config_writeb(bdf, PCI_SECONDARY_BUS, 255);
442             pci_config_writeb(bdf, PCI_SUBORDINATE_BUS, 0);
443         }
444     }
445
446     foreachbdf(bdf, bus) {
447         class = pci_config_readw(bdf, PCI_CLASS_DEVICE);
448         if (class != PCI_CLASS_BRIDGE_PCI) {
449             continue;
450         }
451         dprintf(1, "PCI: %s bdf = 0x%x\n", __func__, bdf);
452
453         u8 pribus = pci_config_readb(bdf, PCI_PRIMARY_BUS);
454         if (pribus != bus) {
455             dprintf(1, "PCI: primary bus = 0x%x -> 0x%x\n", pribus, bus);
456             pci_config_writeb(bdf, PCI_PRIMARY_BUS, bus);
457         } else {
458             dprintf(1, "PCI: primary bus = 0x%x\n", pribus);
459         }
460
461         u8 secbus = pci_config_readb(bdf, PCI_SECONDARY_BUS);
462         (*pci_bus)++;
463         if (*pci_bus != secbus) {
464             dprintf(1, "PCI: secondary bus = 0x%x -> 0x%x\n",
465                     secbus, *pci_bus);
466             secbus = *pci_bus;
467             pci_config_writeb(bdf, PCI_SECONDARY_BUS, secbus);
468         } else {
469             dprintf(1, "PCI: secondary bus = 0x%x\n", secbus);
470         }
471
472         /* set to max for access to all subordinate buses.
473            later set it to accurate value */
474         u8 subbus = pci_config_readb(bdf, PCI_SUBORDINATE_BUS);
475         pci_config_writeb(bdf, PCI_SUBORDINATE_BUS, 255);
476
477         pci_bios_init_bus_rec(secbus, pci_bus);
478
479         if (subbus != *pci_bus) {
480             dprintf(1, "PCI: subordinate bus = 0x%x -> 0x%x\n",
481                     subbus, *pci_bus);
482             subbus = *pci_bus;
483         } else {
484             dprintf(1, "PCI: subordinate bus = 0x%x\n", subbus);
485         }
486         pci_config_writeb(bdf, PCI_SUBORDINATE_BUS, subbus);
487     }
488 }
489
490 static void
491 pci_bios_init_bus(void)
492 {
493     u8 extraroots = romfile_loadint("etc/extra-pci-roots", 0);
494     u8 pci_bus = 0;
495
496     pci_bios_init_bus_rec(0 /* host bus */, &pci_bus);
497
498     if (extraroots) {
499         while (pci_bus < 0xff) {
500             pci_bus++;
501             pci_bios_init_bus_rec(pci_bus, &pci_bus);
502         }
503     }
504 }
505
506
507 /****************************************************************
508  * Bus sizing
509  ****************************************************************/
510
511 static void
512 pci_bios_get_bar(struct pci_device *pci, int bar,
513                  int *ptype, u64 *psize, int *pis64)
514 {
515     u32 ofs = pci_bar(pci, bar);
516     u16 bdf = pci->bdf;
517     u32 old = pci_config_readl(bdf, ofs);
518     int is64 = 0, type = PCI_REGION_TYPE_MEM;
519     u64 mask;
520
521     if (bar == PCI_ROM_SLOT) {
522         mask = PCI_ROM_ADDRESS_MASK;
523         pci_config_writel(bdf, ofs, mask);
524     } else {
525         if (old & PCI_BASE_ADDRESS_SPACE_IO) {
526             mask = PCI_BASE_ADDRESS_IO_MASK;
527             type = PCI_REGION_TYPE_IO;
528         } else {
529             mask = PCI_BASE_ADDRESS_MEM_MASK;
530             if (old & PCI_BASE_ADDRESS_MEM_PREFETCH)
531                 type = PCI_REGION_TYPE_PREFMEM;
532             is64 = ((old & PCI_BASE_ADDRESS_MEM_TYPE_MASK)
533                     == PCI_BASE_ADDRESS_MEM_TYPE_64);
534         }
535         pci_config_writel(bdf, ofs, ~0);
536     }
537     u64 val = pci_config_readl(bdf, ofs);
538     pci_config_writel(bdf, ofs, old);
539     if (is64) {
540         u32 hold = pci_config_readl(bdf, ofs + 4);
541         pci_config_writel(bdf, ofs + 4, ~0);
542         u32 high = pci_config_readl(bdf, ofs + 4);
543         pci_config_writel(bdf, ofs + 4, hold);
544         val |= ((u64)high << 32);
545         mask |= ((u64)0xffffffff << 32);
546         *psize = (~(val & mask)) + 1;
547     } else {
548         *psize = ((~(val & mask)) + 1) & 0xffffffff;
549     }
550     *ptype = type;
551     *pis64 = is64;
552 }
553
554 static int pci_bios_bridge_region_is64(struct pci_region *r,
555                                  struct pci_device *pci, int type)
556 {
557     if (type != PCI_REGION_TYPE_PREFMEM)
558         return 0;
559     u32 pmem = pci_config_readl(pci->bdf, PCI_PREF_MEMORY_BASE);
560     if (!pmem) {
561         pci_config_writel(pci->bdf, PCI_PREF_MEMORY_BASE, 0xfff0fff0);
562         pmem = pci_config_readl(pci->bdf, PCI_PREF_MEMORY_BASE);
563         pci_config_writel(pci->bdf, PCI_PREF_MEMORY_BASE, 0x0);
564     }
565     if ((pmem & PCI_PREF_RANGE_TYPE_MASK) != PCI_PREF_RANGE_TYPE_64)
566        return 0;
567     struct pci_region_entry *entry;
568     hlist_for_each_entry(entry, &r->list, node) {
569         if (!entry->is64)
570             return 0;
571     }
572     return 1;
573 }
574
575 static u64 pci_region_align(struct pci_region *r)
576 {
577     struct pci_region_entry *entry;
578     hlist_for_each_entry(entry, &r->list, node) {
579         // The first entry in the sorted list has the largest alignment
580         return entry->align;
581     }
582     return 1;
583 }
584
585 static u64 pci_region_sum(struct pci_region *r)
586 {
587     u64 sum = 0;
588     struct pci_region_entry *entry;
589     hlist_for_each_entry(entry, &r->list, node) {
590         sum += entry->size;
591     }
592     return sum;
593 }
594
595 static void pci_region_migrate_64bit_entries(struct pci_region *from,
596                                              struct pci_region *to)
597 {
598     struct hlist_node *n, **last = &to->list.first;
599     struct pci_region_entry *entry;
600     hlist_for_each_entry_safe(entry, n, &from->list, node) {
601         if (!entry->is64)
602             continue;
603         if (entry->dev->class == PCI_CLASS_SERIAL_USB)
604             continue;
605         // Move from source list to destination list.
606         hlist_del(&entry->node);
607         hlist_add(&entry->node, last);
608         last = &entry->node.next;
609     }
610 }
611
612 static struct pci_region_entry *
613 pci_region_create_entry(struct pci_bus *bus, struct pci_device *dev,
614                         int bar, u64 size, u64 align, int type, int is64)
615 {
616     struct pci_region_entry *entry = malloc_tmp(sizeof(*entry));
617     if (!entry) {
618         warn_noalloc();
619         return NULL;
620     }
621     memset(entry, 0, sizeof(*entry));
622     entry->dev = dev;
623     entry->bar = bar;
624     entry->size = size;
625     entry->align = align;
626     entry->is64 = is64;
627     entry->type = type;
628     // Insert into list in sorted order.
629     struct hlist_node **pprev;
630     struct pci_region_entry *pos;
631     hlist_for_each_entry_pprev(pos, pprev, &bus->r[type].list, node) {
632         if (pos->align < align || (pos->align == align && pos->size < size))
633             break;
634     }
635     hlist_add(&entry->node, pprev);
636     return entry;
637 }
638
639 static int pci_bus_hotplug_support(struct pci_bus *bus)
640 {
641     u8 pcie_cap = pci_find_capability(bus->bus_dev, PCI_CAP_ID_EXP);
642     u8 shpc_cap;
643
644     if (pcie_cap) {
645         u16 pcie_flags = pci_config_readw(bus->bus_dev->bdf,
646                                           pcie_cap + PCI_EXP_FLAGS);
647         u8 port_type = ((pcie_flags & PCI_EXP_FLAGS_TYPE) >>
648                        (__builtin_ffs(PCI_EXP_FLAGS_TYPE) - 1));
649         u8 downstream_port = (port_type == PCI_EXP_TYPE_DOWNSTREAM) ||
650                              (port_type == PCI_EXP_TYPE_ROOT_PORT);
651         /*
652          * PCI Express SPEC, 7.8.2:
653          *   Slot Implemented â€“ When Set, this bit indicates that the Link
654          *   HwInit associated with this Port is connected to a slot (as
655          *   compared to being connected to a system-integrated device or
656          *   being disabled).
657          *   This bit is valid for Downstream Ports. This bit is undefined
658          *   for Upstream Ports.
659          */
660         u16 slot_implemented = pcie_flags & PCI_EXP_FLAGS_SLOT;
661
662         return downstream_port && slot_implemented;
663     }
664
665     shpc_cap = pci_find_capability(bus->bus_dev, PCI_CAP_ID_SHPC);
666     return !!shpc_cap;
667 }
668
669 static int pci_bios_check_devices(struct pci_bus *busses)
670 {
671     dprintf(1, "PCI: check devices\n");
672
673     // Calculate resources needed for regular (non-bus) devices.
674     struct pci_device *pci;
675     foreachpci(pci) {
676         if (pci->class == PCI_CLASS_BRIDGE_PCI)
677             busses[pci->secondary_bus].bus_dev = pci;
678
679         struct pci_bus *bus = &busses[pci_bdf_to_bus(pci->bdf)];
680         if (!bus->bus_dev)
681             /*
682              * Resources for all root busses go in busses[0]
683              */
684             bus = &busses[0];
685         int i;
686         for (i = 0; i < PCI_NUM_REGIONS; i++) {
687             if ((pci->class == PCI_CLASS_BRIDGE_PCI) &&
688                 (i >= PCI_BRIDGE_NUM_REGIONS && i < PCI_ROM_SLOT))
689                 continue;
690             int type, is64;
691             u64 size;
692             pci_bios_get_bar(pci, i, &type, &size, &is64);
693             if (size == 0)
694                 continue;
695
696             if (type != PCI_REGION_TYPE_IO && size < PCI_DEVICE_MEM_MIN)
697                 size = PCI_DEVICE_MEM_MIN;
698             struct pci_region_entry *entry = pci_region_create_entry(
699                 bus, pci, i, size, size, type, is64);
700             if (!entry)
701                 return -1;
702
703             if (is64)
704                 i++;
705         }
706     }
707
708     // Propagate required bus resources to parent busses.
709     int secondary_bus;
710     for (secondary_bus=MaxPCIBus; secondary_bus>0; secondary_bus--) {
711         struct pci_bus *s = &busses[secondary_bus];
712         if (!s->bus_dev)
713             continue;
714         struct pci_bus *parent = &busses[pci_bdf_to_bus(s->bus_dev->bdf)];
715         if (!parent->bus_dev)
716             /*
717              * Resources for all root busses go in busses[0]
718              */
719             parent = &busses[0];
720         int type;
721         int hotplug_support = pci_bus_hotplug_support(s);
722         for (type = 0; type < PCI_REGION_TYPE_COUNT; type++) {
723             u64 align = (type == PCI_REGION_TYPE_IO) ?
724                 PCI_BRIDGE_IO_MIN : PCI_BRIDGE_MEM_MIN;
725             if (!pci_bridge_has_region(s->bus_dev, type))
726                 continue;
727             if (pci_region_align(&s->r[type]) > align)
728                  align = pci_region_align(&s->r[type]);
729             u64 sum = pci_region_sum(&s->r[type]);
730             if (!sum && hotplug_support)
731                 sum = align; /* reserve min size for hot-plug */
732             u64 size = ALIGN(sum, align);
733             int is64 = pci_bios_bridge_region_is64(&s->r[type],
734                                             s->bus_dev, type);
735             // entry->bar is -1 if the entry represents a bridge region
736             struct pci_region_entry *entry = pci_region_create_entry(
737                 parent, s->bus_dev, -1, size, align, type, is64);
738             if (!entry)
739                 return -1;
740             dprintf(1, "PCI: secondary bus %d size %08llx type %s\n",
741                       entry->dev->secondary_bus, size,
742                       region_type_name[entry->type]);
743         }
744     }
745     return 0;
746 }
747
748
749 /****************************************************************
750  * BAR assignment
751  ****************************************************************/
752
753 // Setup region bases (given the regions' size and alignment)
754 static int pci_bios_init_root_regions_io(struct pci_bus *bus)
755 {
756     /*
757      * QEMU I/O address space usage:
758      *   0000 - 0fff    legacy isa, pci config, pci root bus, ...
759      *   1000 - 9fff    free
760      *   a000 - afff    hotplug (cpu, pci via acpi, i440fx/piix only)
761      *   b000 - bfff    power management (PORT_ACPI_PM_BASE)
762      *                  [ qemu 1.4+ implements pci config registers
763      *                    properly so guests can place the registers
764      *                    where they want, on older versions its fixed ]
765      *   c000 - ffff    free, traditionally used for pci io
766      */
767     struct pci_region *r_io = &bus->r[PCI_REGION_TYPE_IO];
768     u64 sum = pci_region_sum(r_io);
769     if (sum < 0x4000) {
770         /* traditional region is big enougth, use it */
771         r_io->base = 0xc000;
772     } else if (sum < pci_io_low_end - 0x1000) {
773         /* use the larger region at 0x1000 */
774         r_io->base = 0x1000;
775     } else {
776         /* not enouth io address space -> error out */
777         return -1;
778     }
779     dprintf(1, "PCI: IO: %4llx - %4llx\n", r_io->base, r_io->base + sum - 1);
780     return 0;
781 }
782
783 static int pci_bios_init_root_regions_mem(struct pci_bus *bus)
784 {
785     struct pci_region *r_end = &bus->r[PCI_REGION_TYPE_PREFMEM];
786     struct pci_region *r_start = &bus->r[PCI_REGION_TYPE_MEM];
787
788     if (pci_region_align(r_start) < pci_region_align(r_end)) {
789         // Swap regions to improve alignment.
790         r_end = r_start;
791         r_start = &bus->r[PCI_REGION_TYPE_PREFMEM];
792     }
793     u64 sum = pci_region_sum(r_end);
794     u64 align = pci_region_align(r_end);
795     r_end->base = ALIGN_DOWN((pcimem_end - sum), align);
796     sum = pci_region_sum(r_start);
797     align = pci_region_align(r_start);
798     r_start->base = ALIGN_DOWN((r_end->base - sum), align);
799
800     if ((r_start->base < pcimem_start) ||
801          (r_start->base > pcimem_end))
802         // Memory range requested is larger than available.
803         return -1;
804     return 0;
805 }
806
807 #define PCI_IO_SHIFT            8
808 #define PCI_MEMORY_SHIFT        16
809 #define PCI_PREF_MEMORY_SHIFT   16
810
811 static void
812 pci_region_map_one_entry(struct pci_region_entry *entry, u64 addr)
813 {
814     u16 bdf = entry->dev->bdf;
815     if (entry->bar >= 0) {
816         dprintf(1, "PCI: map device bdf=%02x:%02x.%x"
817                 "  bar %d, addr %08llx, size %08llx [%s]\n",
818                 pci_bdf_to_bus(bdf), pci_bdf_to_dev(bdf), pci_bdf_to_fn(bdf),
819                 entry->bar, addr, entry->size, region_type_name[entry->type]);
820
821         pci_set_io_region_addr(entry->dev, entry->bar, addr, entry->is64);
822         return;
823     }
824
825     u64 limit = addr + entry->size - 1;
826     if (entry->type == PCI_REGION_TYPE_IO) {
827         pci_config_writeb(bdf, PCI_IO_BASE, addr >> PCI_IO_SHIFT);
828         pci_config_writew(bdf, PCI_IO_BASE_UPPER16, 0);
829         pci_config_writeb(bdf, PCI_IO_LIMIT, limit >> PCI_IO_SHIFT);
830         pci_config_writew(bdf, PCI_IO_LIMIT_UPPER16, 0);
831     }
832     if (entry->type == PCI_REGION_TYPE_MEM) {
833         pci_config_writew(bdf, PCI_MEMORY_BASE, addr >> PCI_MEMORY_SHIFT);
834         pci_config_writew(bdf, PCI_MEMORY_LIMIT, limit >> PCI_MEMORY_SHIFT);
835     }
836     if (entry->type == PCI_REGION_TYPE_PREFMEM) {
837         pci_config_writew(bdf, PCI_PREF_MEMORY_BASE, addr >> PCI_PREF_MEMORY_SHIFT);
838         pci_config_writew(bdf, PCI_PREF_MEMORY_LIMIT, limit >> PCI_PREF_MEMORY_SHIFT);
839         pci_config_writel(bdf, PCI_PREF_BASE_UPPER32, addr >> 32);
840         pci_config_writel(bdf, PCI_PREF_LIMIT_UPPER32, limit >> 32);
841     }
842 }
843
844 static void pci_region_map_entries(struct pci_bus *busses, struct pci_region *r)
845 {
846     struct hlist_node *n;
847     struct pci_region_entry *entry;
848     hlist_for_each_entry_safe(entry, n, &r->list, node) {
849         u64 addr = r->base;
850         r->base += entry->size;
851         if (entry->bar == -1)
852             // Update bus base address if entry is a bridge region
853             busses[entry->dev->secondary_bus].r[entry->type].base = addr;
854         pci_region_map_one_entry(entry, addr);
855         hlist_del(&entry->node);
856         free(entry);
857     }
858 }
859
860 static void pci_bios_map_devices(struct pci_bus *busses)
861 {
862     if (pci_bios_init_root_regions_io(busses))
863         panic("PCI: out of I/O address space\n");
864
865     dprintf(1, "PCI: 32: %016llx - %016llx\n", pcimem_start, pcimem_end);
866     if (pci_bios_init_root_regions_mem(busses)) {
867         struct pci_region r64_mem, r64_pref;
868         r64_mem.list.first = NULL;
869         r64_pref.list.first = NULL;
870         pci_region_migrate_64bit_entries(&busses[0].r[PCI_REGION_TYPE_MEM],
871                                          &r64_mem);
872         pci_region_migrate_64bit_entries(&busses[0].r[PCI_REGION_TYPE_PREFMEM],
873                                          &r64_pref);
874
875         if (pci_bios_init_root_regions_mem(busses))
876             panic("PCI: out of 32bit address space\n");
877
878         u64 sum_mem = pci_region_sum(&r64_mem);
879         u64 sum_pref = pci_region_sum(&r64_pref);
880         u64 align_mem = pci_region_align(&r64_mem);
881         u64 align_pref = pci_region_align(&r64_pref);
882
883         r64_mem.base = le64_to_cpu(romfile_loadint("etc/reserved-memory-end", 0));
884         if (r64_mem.base < 0x100000000LL + RamSizeOver4G)
885             r64_mem.base = 0x100000000LL + RamSizeOver4G;
886         r64_mem.base = ALIGN(r64_mem.base, align_mem);
887         r64_mem.base = ALIGN(r64_mem.base, (1LL<<30));    // 1G hugepage
888         r64_pref.base = r64_mem.base + sum_mem;
889         r64_pref.base = ALIGN(r64_pref.base, align_pref);
890         r64_pref.base = ALIGN(r64_pref.base, (1LL<<30));  // 1G hugepage
891         pcimem64_start = r64_mem.base;
892         pcimem64_end = r64_pref.base + sum_pref;
893         pcimem64_end = ALIGN(pcimem64_end, (1LL<<30));    // 1G hugepage
894         dprintf(1, "PCI: 64: %016llx - %016llx\n", pcimem64_start, pcimem64_end);
895
896         pci_region_map_entries(busses, &r64_mem);
897         pci_region_map_entries(busses, &r64_pref);
898     } else {
899         // no bars mapped high -> drop 64bit window (see dsdt)
900         pcimem64_start = 0;
901     }
902     // Map regions on each device.
903     int bus;
904     for (bus = 0; bus<=MaxPCIBus; bus++) {
905         int type;
906         for (type = 0; type < PCI_REGION_TYPE_COUNT; type++)
907             pci_region_map_entries(busses, &busses[bus].r[type]);
908     }
909 }
910
911
912 /****************************************************************
913  * Main setup code
914  ****************************************************************/
915
916 void
917 pci_setup(void)
918 {
919     if (!CONFIG_QEMU)
920         return;
921
922     dprintf(3, "pci setup\n");
923
924     dprintf(1, "=== PCI bus & bridge init ===\n");
925     if (pci_probe_host() != 0) {
926         return;
927     }
928     pci_bios_init_bus();
929
930     dprintf(1, "=== PCI device probing ===\n");
931     pci_probe_devices();
932
933     pcimem_start = RamSize;
934     pci_bios_init_platform();
935
936     dprintf(1, "=== PCI new allocation pass #1 ===\n");
937     struct pci_bus *busses = malloc_tmp(sizeof(*busses) * (MaxPCIBus + 1));
938     if (!busses) {
939         warn_noalloc();
940         return;
941     }
942     memset(busses, 0, sizeof(*busses) * (MaxPCIBus + 1));
943     if (pci_bios_check_devices(busses))
944         return;
945
946     dprintf(1, "=== PCI new allocation pass #2 ===\n");
947     pci_bios_map_devices(busses);
948
949     pci_bios_init_devices();
950
951     free(busses);
952
953     pci_enable_default_vga();
954 }