xref: /openbmc/qemu/hw/pci/pci.c (revision e6c03989)
1315a1350SMichael S. Tsirkin /*
2315a1350SMichael S. Tsirkin  * QEMU PCI bus manager
3315a1350SMichael S. Tsirkin  *
4315a1350SMichael S. Tsirkin  * Copyright (c) 2004 Fabrice Bellard
5315a1350SMichael S. Tsirkin  *
6315a1350SMichael S. Tsirkin  * Permission is hereby granted, free of charge, to any person obtaining a copy
7315a1350SMichael S. Tsirkin  * of this software and associated documentation files (the "Software"), to deal
8315a1350SMichael S. Tsirkin  * in the Software without restriction, including without limitation the rights
9315a1350SMichael S. Tsirkin  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10315a1350SMichael S. Tsirkin  * copies of the Software, and to permit persons to whom the Software is
11315a1350SMichael S. Tsirkin  * furnished to do so, subject to the following conditions:
12315a1350SMichael S. Tsirkin  *
13315a1350SMichael S. Tsirkin  * The above copyright notice and this permission notice shall be included in
14315a1350SMichael S. Tsirkin  * all copies or substantial portions of the Software.
15315a1350SMichael S. Tsirkin  *
16315a1350SMichael S. Tsirkin  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17315a1350SMichael S. Tsirkin  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18315a1350SMichael S. Tsirkin  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19315a1350SMichael S. Tsirkin  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20315a1350SMichael S. Tsirkin  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21315a1350SMichael S. Tsirkin  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22315a1350SMichael S. Tsirkin  * THE SOFTWARE.
23315a1350SMichael S. Tsirkin  */
24e688df6bSMarkus Armbruster 
2597d5408fSPeter Maydell #include "qemu/osdep.h"
262c65db5eSPaolo Bonzini #include "qemu/datadir.h"
277c16b5bbSPaolo Bonzini #include "qemu/units.h"
2864552b6bSMarkus Armbruster #include "hw/irq.h"
29c759b24fSMichael S. Tsirkin #include "hw/pci/pci.h"
30c759b24fSMichael S. Tsirkin #include "hw/pci/pci_bridge.h"
3106aac7bdSMichael S. Tsirkin #include "hw/pci/pci_bus.h"
32568f0690SDavid Gibson #include "hw/pci/pci_host.h"
33a27bd6c7SMarkus Armbruster #include "hw/qdev-properties.h"
34ce35e229SEduardo Habkost #include "hw/qdev-properties-system.h"
35ca77ee28SMarkus Armbruster #include "migration/qemu-file-types.h"
36d6454270SMarkus Armbruster #include "migration/vmstate.h"
371422e32dSPaolo Bonzini #include "net/net.h"
38b58c5c2dSMarkus Armbruster #include "sysemu/numa.h"
398eb85fb5SVladimir Sementsov-Ogievskiy #include "sysemu/runstate.h"
4046517dd4SMarkus Armbruster #include "sysemu/sysemu.h"
41c759b24fSMichael S. Tsirkin #include "hw/loader.h"
42d49b6836SMarkus Armbruster #include "qemu/error-report.h"
431de7afc9SPaolo Bonzini #include "qemu/range.h"
447828d750SDon Koch #include "trace.h"
45c759b24fSMichael S. Tsirkin #include "hw/pci/msi.h"
46c759b24fSMichael S. Tsirkin #include "hw/pci/msix.h"
475e954943SIgor Mammedov #include "hw/hotplug.h"
48e4024630SLaurent Vivier #include "hw/boards.h"
49e688df6bSMarkus Armbruster #include "qapi/error.h"
50f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
51987b73b3SMarkus Armbruster #include "pci-internal.h"
52315a1350SMichael S. Tsirkin 
536096cf78SDavid Woodhouse #include "hw/xen/xen.h"
546096cf78SDavid Woodhouse #include "hw/i386/kvm/xen_evtchn.h"
556096cf78SDavid Woodhouse 
56315a1350SMichael S. Tsirkin //#define DEBUG_PCI
57315a1350SMichael S. Tsirkin #ifdef DEBUG_PCI
58315a1350SMichael S. Tsirkin # define PCI_DPRINTF(format, ...)       printf(format, ## __VA_ARGS__)
59315a1350SMichael S. Tsirkin #else
60315a1350SMichael S. Tsirkin # define PCI_DPRINTF(format, ...)       do { } while (0)
61315a1350SMichael S. Tsirkin #endif
62315a1350SMichael S. Tsirkin 
6388c725c7SCornelia Huck bool pci_available = true;
6488c725c7SCornelia Huck 
65315a1350SMichael S. Tsirkin static char *pcibus_get_dev_path(DeviceState *dev);
66315a1350SMichael S. Tsirkin static char *pcibus_get_fw_dev_path(DeviceState *dev);
67*e6c03989SPeter Maydell static void pcibus_reset_hold(Object *obj);
68ca92eb5dSAni Sinha static bool pcie_has_upstream_port(PCIDevice *dev);
69315a1350SMichael S. Tsirkin 
70315a1350SMichael S. Tsirkin static Property pci_props[] = {
71315a1350SMichael S. Tsirkin     DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
72315a1350SMichael S. Tsirkin     DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
7308b1df8fSPaolo Bonzini     DEFINE_PROP_UINT32("romsize", PCIDevice, romsize, -1),
74315a1350SMichael S. Tsirkin     DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
75315a1350SMichael S. Tsirkin     DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
76315a1350SMichael S. Tsirkin                     QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
776b449540SMichael S. Tsirkin     DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
786b449540SMichael S. Tsirkin                     QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
79f03d8ea3SMarcel Apfelbaum     DEFINE_PROP_BIT("x-pcie-extcap-init", PCIDevice, cap_present,
80f03d8ea3SMarcel Apfelbaum                     QEMU_PCIE_EXTCAP_INIT_BITNR, true),
814f5b6a05SJens Freimann     DEFINE_PROP_STRING("failover_pair_id", PCIDevice,
824f5b6a05SJens Freimann                        failover_pair_id),
83b32bd763SIgor Mammedov     DEFINE_PROP_UINT32("acpi-index",  PCIDevice, acpi_index, 0),
845ed3dabeSLeonardo Bras     DEFINE_PROP_BIT("x-pcie-err-unc-mask", PCIDevice, cap_present,
855ed3dabeSLeonardo Bras                     QEMU_PCIE_ERR_UNC_MASK_BITNR, true),
867c228c5fSAkihiko Odaki     DEFINE_PROP_BIT("x-pcie-ari-nextfn-1", PCIDevice, cap_present,
877c228c5fSAkihiko Odaki                     QEMU_PCIE_ARI_NEXTFN_1_BITNR, false),
88315a1350SMichael S. Tsirkin     DEFINE_PROP_END_OF_LIST()
89315a1350SMichael S. Tsirkin };
90315a1350SMichael S. Tsirkin 
91d2f69df7SBandan Das static const VMStateDescription vmstate_pcibus = {
92d2f69df7SBandan Das     .name = "PCIBUS",
93d2f69df7SBandan Das     .version_id = 1,
94d2f69df7SBandan Das     .minimum_version_id = 1,
958e5e0890SRichard Henderson     .fields = (const VMStateField[]) {
96d2164ad3SHalil Pasic         VMSTATE_INT32_EQUAL(nirq, PCIBus, NULL),
97d2f69df7SBandan Das         VMSTATE_VARRAY_INT32(irq_count, PCIBus,
98d2f69df7SBandan Das                              nirq, 0, vmstate_info_int32,
99d2f69df7SBandan Das                              int32_t),
100d2f69df7SBandan Das         VMSTATE_END_OF_LIST()
101d2f69df7SBandan Das     }
102d2f69df7SBandan Das };
103d2f69df7SBandan Das 
104041b1c40SIgor Mammedov static gint g_cmp_uint32(gconstpointer a, gconstpointer b, gpointer user_data)
105041b1c40SIgor Mammedov {
106041b1c40SIgor Mammedov     return a - b;
107041b1c40SIgor Mammedov }
108041b1c40SIgor Mammedov 
109041b1c40SIgor Mammedov static GSequence *pci_acpi_index_list(void)
110041b1c40SIgor Mammedov {
111041b1c40SIgor Mammedov     static GSequence *used_acpi_index_list;
112041b1c40SIgor Mammedov 
113041b1c40SIgor Mammedov     if (!used_acpi_index_list) {
114041b1c40SIgor Mammedov         used_acpi_index_list = g_sequence_new(NULL);
115041b1c40SIgor Mammedov     }
116041b1c40SIgor Mammedov     return used_acpi_index_list;
117041b1c40SIgor Mammedov }
118041b1c40SIgor Mammedov 
119b86eacb8SMarcel Apfelbaum static void pci_init_bus_master(PCIDevice *pci_dev)
120b86eacb8SMarcel Apfelbaum {
121b86eacb8SMarcel Apfelbaum     AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
122b86eacb8SMarcel Apfelbaum 
123b86eacb8SMarcel Apfelbaum     memory_region_init_alias(&pci_dev->bus_master_enable_region,
124b86eacb8SMarcel Apfelbaum                              OBJECT(pci_dev), "bus master",
125b86eacb8SMarcel Apfelbaum                              dma_as->root, 0, memory_region_size(dma_as->root));
126b86eacb8SMarcel Apfelbaum     memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
1273716d590SJason Wang     memory_region_add_subregion(&pci_dev->bus_master_container_region, 0,
1283716d590SJason Wang                                 &pci_dev->bus_master_enable_region);
129b86eacb8SMarcel Apfelbaum }
130b86eacb8SMarcel Apfelbaum 
131b86eacb8SMarcel Apfelbaum static void pcibus_machine_done(Notifier *notifier, void *data)
132b86eacb8SMarcel Apfelbaum {
133b86eacb8SMarcel Apfelbaum     PCIBus *bus = container_of(notifier, PCIBus, machine_done);
134b86eacb8SMarcel Apfelbaum     int i;
135b86eacb8SMarcel Apfelbaum 
136b86eacb8SMarcel Apfelbaum     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
137b86eacb8SMarcel Apfelbaum         if (bus->devices[i]) {
138b86eacb8SMarcel Apfelbaum             pci_init_bus_master(bus->devices[i]);
139b86eacb8SMarcel Apfelbaum         }
140b86eacb8SMarcel Apfelbaum     }
141b86eacb8SMarcel Apfelbaum }
142b86eacb8SMarcel Apfelbaum 
143d2f69df7SBandan Das static void pci_bus_realize(BusState *qbus, Error **errp)
144d2f69df7SBandan Das {
145d2f69df7SBandan Das     PCIBus *bus = PCI_BUS(qbus);
146d2f69df7SBandan Das 
147b86eacb8SMarcel Apfelbaum     bus->machine_done.notify = pcibus_machine_done;
148b86eacb8SMarcel Apfelbaum     qemu_add_machine_init_done_notifier(&bus->machine_done);
149b86eacb8SMarcel Apfelbaum 
15099b16e8eSJuan Quintela     vmstate_register_any(NULL, &vmstate_pcibus, bus);
151d2f69df7SBandan Das }
152d2f69df7SBandan Das 
1532f57db8aSDavid Gibson static void pcie_bus_realize(BusState *qbus, Error **errp)
1542f57db8aSDavid Gibson {
1552f57db8aSDavid Gibson     PCIBus *bus = PCI_BUS(qbus);
156b52fa0eaSPhilippe Mathieu-Daudé     Error *local_err = NULL;
1572f57db8aSDavid Gibson 
158b52fa0eaSPhilippe Mathieu-Daudé     pci_bus_realize(qbus, &local_err);
159b52fa0eaSPhilippe Mathieu-Daudé     if (local_err) {
160b52fa0eaSPhilippe Mathieu-Daudé         error_propagate(errp, local_err);
161b52fa0eaSPhilippe Mathieu-Daudé         return;
162b52fa0eaSPhilippe Mathieu-Daudé     }
1632f57db8aSDavid Gibson 
1642f57db8aSDavid Gibson     /*
1652f57db8aSDavid Gibson      * A PCI-E bus can support extended config space if it's the root
1662f57db8aSDavid Gibson      * bus, or if the bus/bridge above it does as well
1672f57db8aSDavid Gibson      */
1682f57db8aSDavid Gibson     if (pci_bus_is_root(bus)) {
1692f57db8aSDavid Gibson         bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
1702f57db8aSDavid Gibson     } else {
1712f57db8aSDavid Gibson         PCIBus *parent_bus = pci_get_bus(bus->parent_dev);
1722f57db8aSDavid Gibson 
1732f57db8aSDavid Gibson         if (pci_bus_allows_extended_config_space(parent_bus)) {
1742f57db8aSDavid Gibson             bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
1752f57db8aSDavid Gibson         }
1762f57db8aSDavid Gibson     }
1772f57db8aSDavid Gibson }
1782f57db8aSDavid Gibson 
179b69c3c21SMarkus Armbruster static void pci_bus_unrealize(BusState *qbus)
180d2f69df7SBandan Das {
181d2f69df7SBandan Das     PCIBus *bus = PCI_BUS(qbus);
182d2f69df7SBandan Das 
183b86eacb8SMarcel Apfelbaum     qemu_remove_machine_init_done_notifier(&bus->machine_done);
184b86eacb8SMarcel Apfelbaum 
185d2f69df7SBandan Das     vmstate_unregister(NULL, &vmstate_pcibus, bus);
186d2f69df7SBandan Das }
187d2f69df7SBandan Das 
188602141d9SMarcel Apfelbaum static int pcibus_num(PCIBus *bus)
189602141d9SMarcel Apfelbaum {
190b0e5196aSDavid Gibson     if (pci_bus_is_root(bus)) {
191602141d9SMarcel Apfelbaum         return 0; /* pci host bridge */
192602141d9SMarcel Apfelbaum     }
193602141d9SMarcel Apfelbaum     return bus->parent_dev->config[PCI_SECONDARY_BUS];
194602141d9SMarcel Apfelbaum }
195602141d9SMarcel Apfelbaum 
1966a3042b2SMarcel Apfelbaum static uint16_t pcibus_numa_node(PCIBus *bus)
1976a3042b2SMarcel Apfelbaum {
1986a3042b2SMarcel Apfelbaum     return NUMA_NODE_UNASSIGNED;
1996a3042b2SMarcel Apfelbaum }
2006a3042b2SMarcel Apfelbaum 
201315a1350SMichael S. Tsirkin static void pci_bus_class_init(ObjectClass *klass, void *data)
202315a1350SMichael S. Tsirkin {
203315a1350SMichael S. Tsirkin     BusClass *k = BUS_CLASS(klass);
204ce6a28eeSMarcel Apfelbaum     PCIBusClass *pbc = PCI_BUS_CLASS(klass);
205*e6c03989SPeter Maydell     ResettableClass *rc = RESETTABLE_CLASS(klass);
206315a1350SMichael S. Tsirkin 
207315a1350SMichael S. Tsirkin     k->print_dev = pcibus_dev_print;
208315a1350SMichael S. Tsirkin     k->get_dev_path = pcibus_get_dev_path;
209315a1350SMichael S. Tsirkin     k->get_fw_dev_path = pcibus_get_fw_dev_path;
210d2f69df7SBandan Das     k->realize = pci_bus_realize;
211d2f69df7SBandan Das     k->unrealize = pci_bus_unrealize;
212*e6c03989SPeter Maydell 
213*e6c03989SPeter Maydell     rc->phases.hold = pcibus_reset_hold;
214ce6a28eeSMarcel Apfelbaum 
215602141d9SMarcel Apfelbaum     pbc->bus_num = pcibus_num;
2166a3042b2SMarcel Apfelbaum     pbc->numa_node = pcibus_numa_node;
217315a1350SMichael S. Tsirkin }
218315a1350SMichael S. Tsirkin 
219315a1350SMichael S. Tsirkin static const TypeInfo pci_bus_info = {
220315a1350SMichael S. Tsirkin     .name = TYPE_PCI_BUS,
221315a1350SMichael S. Tsirkin     .parent = TYPE_BUS,
222315a1350SMichael S. Tsirkin     .instance_size = sizeof(PCIBus),
223ce6a28eeSMarcel Apfelbaum     .class_size = sizeof(PCIBusClass),
224315a1350SMichael S. Tsirkin     .class_init = pci_bus_class_init,
225315a1350SMichael S. Tsirkin };
226315a1350SMichael S. Tsirkin 
227cf04aba2SBen Widawsky static const TypeInfo cxl_interface_info = {
228cf04aba2SBen Widawsky     .name          = INTERFACE_CXL_DEVICE,
229cf04aba2SBen Widawsky     .parent        = TYPE_INTERFACE,
230cf04aba2SBen Widawsky };
231cf04aba2SBen Widawsky 
232619f02aeSEduardo Habkost static const TypeInfo pcie_interface_info = {
233619f02aeSEduardo Habkost     .name          = INTERFACE_PCIE_DEVICE,
234619f02aeSEduardo Habkost     .parent        = TYPE_INTERFACE,
235619f02aeSEduardo Habkost };
236619f02aeSEduardo Habkost 
237619f02aeSEduardo Habkost static const TypeInfo conventional_pci_interface_info = {
238619f02aeSEduardo Habkost     .name          = INTERFACE_CONVENTIONAL_PCI_DEVICE,
239619f02aeSEduardo Habkost     .parent        = TYPE_INTERFACE,
240619f02aeSEduardo Habkost };
241619f02aeSEduardo Habkost 
2421c685a90SGreg Kurz static void pcie_bus_class_init(ObjectClass *klass, void *data)
2431c685a90SGreg Kurz {
2442f57db8aSDavid Gibson     BusClass *k = BUS_CLASS(klass);
2451c685a90SGreg Kurz 
2462f57db8aSDavid Gibson     k->realize = pcie_bus_realize;
2471c685a90SGreg Kurz }
2481c685a90SGreg Kurz 
2493a861c46SAlex Williamson static const TypeInfo pcie_bus_info = {
2503a861c46SAlex Williamson     .name = TYPE_PCIE_BUS,
2513a861c46SAlex Williamson     .parent = TYPE_PCI_BUS,
2521c685a90SGreg Kurz     .class_init = pcie_bus_class_init,
2533a861c46SAlex Williamson };
2543a861c46SAlex Williamson 
2554f8db871SBen Widawsky static const TypeInfo cxl_bus_info = {
2564f8db871SBen Widawsky     .name       = TYPE_CXL_BUS,
2574f8db871SBen Widawsky     .parent     = TYPE_PCIE_BUS,
2584f8db871SBen Widawsky     .class_init = pcie_bus_class_init,
2594f8db871SBen Widawsky };
2604f8db871SBen Widawsky 
261315a1350SMichael S. Tsirkin static void pci_update_mappings(PCIDevice *d);
262d98f08f5SMarcel Apfelbaum static void pci_irq_handler(void *opaque, int irq_num, int level);
263133e9b22SMarkus Armbruster static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
264315a1350SMichael S. Tsirkin static void pci_del_option_rom(PCIDevice *pdev);
265315a1350SMichael S. Tsirkin 
266315a1350SMichael S. Tsirkin static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
267315a1350SMichael S. Tsirkin static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
268315a1350SMichael S. Tsirkin 
269987b73b3SMarkus Armbruster PCIHostStateList pci_host_bridges;
270315a1350SMichael S. Tsirkin 
271cf8c704dSMichael Roth int pci_bar(PCIDevice *d, int reg)
272315a1350SMichael S. Tsirkin {
273315a1350SMichael S. Tsirkin     uint8_t type;
274315a1350SMichael S. Tsirkin 
2757c0fa8dfSKnut Omang     /* PCIe virtual functions do not have their own BARs */
2767c0fa8dfSKnut Omang     assert(!pci_is_vf(d));
2777c0fa8dfSKnut Omang 
278315a1350SMichael S. Tsirkin     if (reg != PCI_ROM_SLOT)
279315a1350SMichael S. Tsirkin         return PCI_BASE_ADDRESS_0 + reg * 4;
280315a1350SMichael S. Tsirkin 
281315a1350SMichael S. Tsirkin     type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
282315a1350SMichael S. Tsirkin     return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
283315a1350SMichael S. Tsirkin }
284315a1350SMichael S. Tsirkin 
285315a1350SMichael S. Tsirkin static inline int pci_irq_state(PCIDevice *d, int irq_num)
286315a1350SMichael S. Tsirkin {
287315a1350SMichael S. Tsirkin         return (d->irq_state >> irq_num) & 0x1;
288315a1350SMichael S. Tsirkin }
289315a1350SMichael S. Tsirkin 
290315a1350SMichael S. Tsirkin static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
291315a1350SMichael S. Tsirkin {
292315a1350SMichael S. Tsirkin         d->irq_state &= ~(0x1 << irq_num);
293315a1350SMichael S. Tsirkin         d->irq_state |= level << irq_num;
294315a1350SMichael S. Tsirkin }
295315a1350SMichael S. Tsirkin 
296b06fe3e7SPhilippe Mathieu-Daudé static void pci_bus_change_irq_level(PCIBus *bus, int irq_num, int change)
297b06fe3e7SPhilippe Mathieu-Daudé {
298459ca8bfSMark Cave-Ayland     assert(irq_num >= 0);
299459ca8bfSMark Cave-Ayland     assert(irq_num < bus->nirq);
300b06fe3e7SPhilippe Mathieu-Daudé     bus->irq_count[irq_num] += change;
301b06fe3e7SPhilippe Mathieu-Daudé     bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
302b06fe3e7SPhilippe Mathieu-Daudé }
303b06fe3e7SPhilippe Mathieu-Daudé 
304315a1350SMichael S. Tsirkin static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
305315a1350SMichael S. Tsirkin {
306315a1350SMichael S. Tsirkin     PCIBus *bus;
307315a1350SMichael S. Tsirkin     for (;;) {
30828566eabSPhilippe Mathieu-Daudé         int dev_irq = irq_num;
309fd56e061SDavid Gibson         bus = pci_get_bus(pci_dev);
310f021f4e9SBernhard Beschow         assert(bus->map_irq);
311315a1350SMichael S. Tsirkin         irq_num = bus->map_irq(pci_dev, irq_num);
31228566eabSPhilippe Mathieu-Daudé         trace_pci_route_irq(dev_irq, DEVICE(pci_dev)->canonical_path, irq_num,
31328566eabSPhilippe Mathieu-Daudé                             pci_bus_is_root(bus) ? "root-complex"
31428566eabSPhilippe Mathieu-Daudé                                     : DEVICE(bus->parent_dev)->canonical_path);
315315a1350SMichael S. Tsirkin         if (bus->set_irq)
316315a1350SMichael S. Tsirkin             break;
317315a1350SMichael S. Tsirkin         pci_dev = bus->parent_dev;
318315a1350SMichael S. Tsirkin     }
319b06fe3e7SPhilippe Mathieu-Daudé     pci_bus_change_irq_level(bus, irq_num, change);
320315a1350SMichael S. Tsirkin }
321315a1350SMichael S. Tsirkin 
322315a1350SMichael S. Tsirkin int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
323315a1350SMichael S. Tsirkin {
324315a1350SMichael S. Tsirkin     assert(irq_num >= 0);
325315a1350SMichael S. Tsirkin     assert(irq_num < bus->nirq);
326315a1350SMichael S. Tsirkin     return !!bus->irq_count[irq_num];
327315a1350SMichael S. Tsirkin }
328315a1350SMichael S. Tsirkin 
329315a1350SMichael S. Tsirkin /* Update interrupt status bit in config space on interrupt
330315a1350SMichael S. Tsirkin  * state change. */
331315a1350SMichael S. Tsirkin static void pci_update_irq_status(PCIDevice *dev)
332315a1350SMichael S. Tsirkin {
333315a1350SMichael S. Tsirkin     if (dev->irq_state) {
334315a1350SMichael S. Tsirkin         dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
335315a1350SMichael S. Tsirkin     } else {
336315a1350SMichael S. Tsirkin         dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
337315a1350SMichael S. Tsirkin     }
338315a1350SMichael S. Tsirkin }
339315a1350SMichael S. Tsirkin 
340315a1350SMichael S. Tsirkin void pci_device_deassert_intx(PCIDevice *dev)
341315a1350SMichael S. Tsirkin {
342315a1350SMichael S. Tsirkin     int i;
343315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
344d98f08f5SMarcel Apfelbaum         pci_irq_handler(dev, i, 0);
345315a1350SMichael S. Tsirkin     }
346315a1350SMichael S. Tsirkin }
347315a1350SMichael S. Tsirkin 
34808cf3dc6SJagannathan Raman static void pci_msi_trigger(PCIDevice *dev, MSIMessage msg)
34908cf3dc6SJagannathan Raman {
35008cf3dc6SJagannathan Raman     MemTxAttrs attrs = {};
35108cf3dc6SJagannathan Raman 
3526096cf78SDavid Woodhouse     /*
3536096cf78SDavid Woodhouse      * Xen uses the high bits of the address to contain some of the bits
3546096cf78SDavid Woodhouse      * of the PIRQ#. Therefore we can't just send the write cycle and
3556096cf78SDavid Woodhouse      * trust that it's caught by the APIC at 0xfee00000 because the
3566096cf78SDavid Woodhouse      * target of the write might be e.g. 0x0x1000fee46000 for PIRQ#4166.
3576096cf78SDavid Woodhouse      * So we intercept the delivery here instead of in kvm_send_msi().
3586096cf78SDavid Woodhouse      */
3596096cf78SDavid Woodhouse     if (xen_mode == XEN_EMULATE &&
3606096cf78SDavid Woodhouse         xen_evtchn_deliver_pirq_msi(msg.address, msg.data)) {
3616096cf78SDavid Woodhouse         return;
3626096cf78SDavid Woodhouse     }
36308cf3dc6SJagannathan Raman     attrs.requester_id = pci_requester_id(dev);
36408cf3dc6SJagannathan Raman     address_space_stl_le(&dev->bus_master_as, msg.address, msg.data,
36508cf3dc6SJagannathan Raman                          attrs, NULL);
36608cf3dc6SJagannathan Raman }
36708cf3dc6SJagannathan Raman 
3687c0fa8dfSKnut Omang static void pci_reset_regions(PCIDevice *dev)
369315a1350SMichael S. Tsirkin {
370315a1350SMichael S. Tsirkin     int r;
3717c0fa8dfSKnut Omang     if (pci_is_vf(dev)) {
3727c0fa8dfSKnut Omang         return;
3737c0fa8dfSKnut Omang     }
374315a1350SMichael S. Tsirkin 
3757c0fa8dfSKnut Omang     for (r = 0; r < PCI_NUM_REGIONS; ++r) {
3767c0fa8dfSKnut Omang         PCIIORegion *region = &dev->io_regions[r];
3777c0fa8dfSKnut Omang         if (!region->size) {
3787c0fa8dfSKnut Omang             continue;
3797c0fa8dfSKnut Omang         }
3807c0fa8dfSKnut Omang 
3817c0fa8dfSKnut Omang         if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
3827c0fa8dfSKnut Omang             region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
3837c0fa8dfSKnut Omang             pci_set_quad(dev->config + pci_bar(dev, r), region->type);
3847c0fa8dfSKnut Omang         } else {
3857c0fa8dfSKnut Omang             pci_set_long(dev->config + pci_bar(dev, r), region->type);
3867c0fa8dfSKnut Omang         }
3877c0fa8dfSKnut Omang     }
3887c0fa8dfSKnut Omang }
3897c0fa8dfSKnut Omang 
3907c0fa8dfSKnut Omang static void pci_do_device_reset(PCIDevice *dev)
3917c0fa8dfSKnut Omang {
392315a1350SMichael S. Tsirkin     pci_device_deassert_intx(dev);
39358b59014SCole Robinson     assert(dev->irq_state == 0);
39458b59014SCole Robinson 
395315a1350SMichael S. Tsirkin     /* Clear all writable bits */
396315a1350SMichael S. Tsirkin     pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
397315a1350SMichael S. Tsirkin                                  pci_get_word(dev->wmask + PCI_COMMAND) |
398315a1350SMichael S. Tsirkin                                  pci_get_word(dev->w1cmask + PCI_COMMAND));
399315a1350SMichael S. Tsirkin     pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
400315a1350SMichael S. Tsirkin                                  pci_get_word(dev->wmask + PCI_STATUS) |
401315a1350SMichael S. Tsirkin                                  pci_get_word(dev->w1cmask + PCI_STATUS));
4027ff81d63SBALATON Zoltan     /* Some devices make bits of PCI_INTERRUPT_LINE read only */
4037ff81d63SBALATON Zoltan     pci_byte_test_and_clear_mask(dev->config + PCI_INTERRUPT_LINE,
4047ff81d63SBALATON Zoltan                               pci_get_word(dev->wmask + PCI_INTERRUPT_LINE) |
4057ff81d63SBALATON Zoltan                               pci_get_word(dev->w1cmask + PCI_INTERRUPT_LINE));
406315a1350SMichael S. Tsirkin     dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
4077c0fa8dfSKnut Omang     pci_reset_regions(dev);
408315a1350SMichael S. Tsirkin     pci_update_mappings(dev);
409315a1350SMichael S. Tsirkin 
410315a1350SMichael S. Tsirkin     msi_reset(dev);
411315a1350SMichael S. Tsirkin     msix_reset(dev);
412315a1350SMichael S. Tsirkin }
413315a1350SMichael S. Tsirkin 
414315a1350SMichael S. Tsirkin /*
415dcc20931SPaolo Bonzini  * This function is called on #RST and FLR.
416dcc20931SPaolo Bonzini  * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
417315a1350SMichael S. Tsirkin  */
418dcc20931SPaolo Bonzini void pci_device_reset(PCIDevice *dev)
419dcc20931SPaolo Bonzini {
42078e4d5cbSPeter Maydell     device_cold_reset(&dev->qdev);
421dcc20931SPaolo Bonzini     pci_do_device_reset(dev);
422dcc20931SPaolo Bonzini }
423dcc20931SPaolo Bonzini 
424dcc20931SPaolo Bonzini /*
425dcc20931SPaolo Bonzini  * Trigger pci bus reset under a given bus.
42678e4d5cbSPeter Maydell  * Called via bus_cold_reset on RST# assert, after the devices
42778e4d5cbSPeter Maydell  * have been reset device_cold_reset-ed already.
428dcc20931SPaolo Bonzini  */
429*e6c03989SPeter Maydell static void pcibus_reset_hold(Object *obj)
430315a1350SMichael S. Tsirkin {
431*e6c03989SPeter Maydell     PCIBus *bus = PCI_BUS(obj);
432315a1350SMichael S. Tsirkin     int i;
433315a1350SMichael S. Tsirkin 
434315a1350SMichael S. Tsirkin     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
435315a1350SMichael S. Tsirkin         if (bus->devices[i]) {
436dcc20931SPaolo Bonzini             pci_do_device_reset(bus->devices[i]);
437315a1350SMichael S. Tsirkin         }
438315a1350SMichael S. Tsirkin     }
439315a1350SMichael S. Tsirkin 
4409bdbbfc3SPaolo Bonzini     for (i = 0; i < bus->nirq; i++) {
4419bdbbfc3SPaolo Bonzini         assert(bus->irq_count[i] == 0);
4429bdbbfc3SPaolo Bonzini     }
443315a1350SMichael S. Tsirkin }
444315a1350SMichael S. Tsirkin 
4453dbc01aeSCao jin static void pci_host_bus_register(DeviceState *host)
446315a1350SMichael S. Tsirkin {
4473dbc01aeSCao jin     PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
4487588e2b0SDavid Gibson 
4497588e2b0SDavid Gibson     QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
450315a1350SMichael S. Tsirkin }
451315a1350SMichael S. Tsirkin 
452c13ee169SMichael Roth static void pci_host_bus_unregister(DeviceState *host)
453c13ee169SMichael Roth {
454c13ee169SMichael Roth     PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
455c13ee169SMichael Roth 
456c13ee169SMichael Roth     QLIST_REMOVE(host_bridge, next);
457c13ee169SMichael Roth }
458c13ee169SMichael Roth 
459c473d18dSDavid Gibson PCIBus *pci_device_root_bus(const PCIDevice *d)
460315a1350SMichael S. Tsirkin {
461fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(d);
462315a1350SMichael S. Tsirkin 
463ce6a28eeSMarcel Apfelbaum     while (!pci_bus_is_root(bus)) {
464ce6a28eeSMarcel Apfelbaum         d = bus->parent_dev;
465ce6a28eeSMarcel Apfelbaum         assert(d != NULL);
466ce6a28eeSMarcel Apfelbaum 
467fd56e061SDavid Gibson         bus = pci_get_bus(d);
468315a1350SMichael S. Tsirkin     }
469315a1350SMichael S. Tsirkin 
470c473d18dSDavid Gibson     return bus;
471315a1350SMichael S. Tsirkin }
472315a1350SMichael S. Tsirkin 
473568f0690SDavid Gibson const char *pci_root_bus_path(PCIDevice *dev)
474c473d18dSDavid Gibson {
475568f0690SDavid Gibson     PCIBus *rootbus = pci_device_root_bus(dev);
476568f0690SDavid Gibson     PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
477568f0690SDavid Gibson     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
478c473d18dSDavid Gibson 
479568f0690SDavid Gibson     assert(host_bridge->bus == rootbus);
480568f0690SDavid Gibson 
481568f0690SDavid Gibson     if (hc->root_bus_path) {
482568f0690SDavid Gibson         return (*hc->root_bus_path)(host_bridge, rootbus);
483315a1350SMichael S. Tsirkin     }
484315a1350SMichael S. Tsirkin 
485568f0690SDavid Gibson     return rootbus->qbus.name;
486315a1350SMichael S. Tsirkin }
487315a1350SMichael S. Tsirkin 
4882d64b7bbSXingang Wang bool pci_bus_bypass_iommu(PCIBus *bus)
4892d64b7bbSXingang Wang {
4902d64b7bbSXingang Wang     PCIBus *rootbus = bus;
4912d64b7bbSXingang Wang     PCIHostState *host_bridge;
4922d64b7bbSXingang Wang 
4932d64b7bbSXingang Wang     if (!pci_bus_is_root(bus)) {
4942d64b7bbSXingang Wang         rootbus = pci_device_root_bus(bus->parent_dev);
4952d64b7bbSXingang Wang     }
4962d64b7bbSXingang Wang 
4972d64b7bbSXingang Wang     host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
4982d64b7bbSXingang Wang 
4992d64b7bbSXingang Wang     assert(host_bridge->bus == rootbus);
5002d64b7bbSXingang Wang 
5012d64b7bbSXingang Wang     return host_bridge->bypass_iommu;
5022d64b7bbSXingang Wang }
5032d64b7bbSXingang Wang 
5048d4cdf01SPeter Maydell static void pci_root_bus_internal_init(PCIBus *bus, DeviceState *parent,
50549909a0dSPhilippe Mathieu-Daudé                                        MemoryRegion *mem, MemoryRegion *io,
506315a1350SMichael S. Tsirkin                                        uint8_t devfn_min)
507315a1350SMichael S. Tsirkin {
508315a1350SMichael S. Tsirkin     assert(PCI_FUNC(devfn_min) == 0);
509315a1350SMichael S. Tsirkin     bus->devfn_min = devfn_min;
5108b884984SMark Cave-Ayland     bus->slot_reserved_mask = 0x0;
51149909a0dSPhilippe Mathieu-Daudé     bus->address_space_mem = mem;
51249909a0dSPhilippe Mathieu-Daudé     bus->address_space_io = io;
513b0e5196aSDavid Gibson     bus->flags |= PCI_BUS_IS_ROOT;
514315a1350SMichael S. Tsirkin 
515315a1350SMichael S. Tsirkin     /* host bridge */
516315a1350SMichael S. Tsirkin     QLIST_INIT(&bus->child);
5172b8cc89aSDavid Gibson 
5183dbc01aeSCao jin     pci_host_bus_register(parent);
519315a1350SMichael S. Tsirkin }
520315a1350SMichael S. Tsirkin 
521c13ee169SMichael Roth static void pci_bus_uninit(PCIBus *bus)
522c13ee169SMichael Roth {
523c13ee169SMichael Roth     pci_host_bus_unregister(BUS(bus)->parent);
524c13ee169SMichael Roth }
525c13ee169SMichael Roth 
526c6f16471SIgor Mammedov bool pci_bus_is_express(const PCIBus *bus)
5278c0bf9e2SAlex Williamson {
5288c0bf9e2SAlex Williamson     return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
5298c0bf9e2SAlex Williamson }
5308c0bf9e2SAlex Williamson 
5318d4cdf01SPeter Maydell void pci_root_bus_init(PCIBus *bus, size_t bus_size, DeviceState *parent,
5324fec6404SPaolo Bonzini                        const char *name,
53349909a0dSPhilippe Mathieu-Daudé                        MemoryRegion *mem, MemoryRegion *io,
53460a0e443SAlex Williamson                        uint8_t devfn_min, const char *typename)
5354fec6404SPaolo Bonzini {
536d637e1dcSPeter Maydell     qbus_init(bus, bus_size, typename, parent, name);
53749909a0dSPhilippe Mathieu-Daudé     pci_root_bus_internal_init(bus, parent, mem, io, devfn_min);
5384fec6404SPaolo Bonzini }
5394fec6404SPaolo Bonzini 
5401115ff6dSDavid Gibson PCIBus *pci_root_bus_new(DeviceState *parent, const char *name,
54149909a0dSPhilippe Mathieu-Daudé                          MemoryRegion *mem, MemoryRegion *io,
54260a0e443SAlex Williamson                          uint8_t devfn_min, const char *typename)
543315a1350SMichael S. Tsirkin {
544315a1350SMichael S. Tsirkin     PCIBus *bus;
545315a1350SMichael S. Tsirkin 
5469388d170SPeter Maydell     bus = PCI_BUS(qbus_new(typename, parent, name));
54749909a0dSPhilippe Mathieu-Daudé     pci_root_bus_internal_init(bus, parent, mem, io, devfn_min);
548315a1350SMichael S. Tsirkin     return bus;
549315a1350SMichael S. Tsirkin }
550315a1350SMichael S. Tsirkin 
551c13ee169SMichael Roth void pci_root_bus_cleanup(PCIBus *bus)
552c13ee169SMichael Roth {
553c13ee169SMichael Roth     pci_bus_uninit(bus);
55407578b0aSDavid Hildenbrand     /* the caller of the unplug hotplug handler will delete this device */
555f1483b46SMarkus Armbruster     qbus_unrealize(BUS(bus));
556c13ee169SMichael Roth }
557c13ee169SMichael Roth 
558f021f4e9SBernhard Beschow void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq,
559315a1350SMichael S. Tsirkin                   void *irq_opaque, int nirq)
560315a1350SMichael S. Tsirkin {
561315a1350SMichael S. Tsirkin     bus->set_irq = set_irq;
562315a1350SMichael S. Tsirkin     bus->irq_opaque = irq_opaque;
563315a1350SMichael S. Tsirkin     bus->nirq = nirq;
564c0b59416SBernhard Beschow     g_free(bus->irq_count);
565315a1350SMichael S. Tsirkin     bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
566315a1350SMichael S. Tsirkin }
567315a1350SMichael S. Tsirkin 
568f021f4e9SBernhard Beschow void pci_bus_map_irqs(PCIBus *bus, pci_map_irq_fn map_irq)
569f021f4e9SBernhard Beschow {
570f021f4e9SBernhard Beschow     bus->map_irq = map_irq;
571f021f4e9SBernhard Beschow }
572f021f4e9SBernhard Beschow 
573c13ee169SMichael Roth void pci_bus_irqs_cleanup(PCIBus *bus)
574c13ee169SMichael Roth {
575c13ee169SMichael Roth     bus->set_irq = NULL;
576c13ee169SMichael Roth     bus->map_irq = NULL;
577c13ee169SMichael Roth     bus->irq_opaque = NULL;
578c13ee169SMichael Roth     bus->nirq = 0;
579c13ee169SMichael Roth     g_free(bus->irq_count);
580c0b59416SBernhard Beschow     bus->irq_count = NULL;
581c13ee169SMichael Roth }
582c13ee169SMichael Roth 
5831115ff6dSDavid Gibson PCIBus *pci_register_root_bus(DeviceState *parent, const char *name,
584315a1350SMichael S. Tsirkin                               pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
585315a1350SMichael S. Tsirkin                               void *irq_opaque,
58649909a0dSPhilippe Mathieu-Daudé                               MemoryRegion *mem, MemoryRegion *io,
5871115ff6dSDavid Gibson                               uint8_t devfn_min, int nirq,
5881115ff6dSDavid Gibson                               const char *typename)
589315a1350SMichael S. Tsirkin {
590315a1350SMichael S. Tsirkin     PCIBus *bus;
591315a1350SMichael S. Tsirkin 
59249909a0dSPhilippe Mathieu-Daudé     bus = pci_root_bus_new(parent, name, mem, io, devfn_min, typename);
593f021f4e9SBernhard Beschow     pci_bus_irqs(bus, set_irq, irq_opaque, nirq);
594f021f4e9SBernhard Beschow     pci_bus_map_irqs(bus, map_irq);
595315a1350SMichael S. Tsirkin     return bus;
596315a1350SMichael S. Tsirkin }
597315a1350SMichael S. Tsirkin 
598c13ee169SMichael Roth void pci_unregister_root_bus(PCIBus *bus)
599c13ee169SMichael Roth {
600c13ee169SMichael Roth     pci_bus_irqs_cleanup(bus);
601c13ee169SMichael Roth     pci_root_bus_cleanup(bus);
602c13ee169SMichael Roth }
603c13ee169SMichael Roth 
604315a1350SMichael S. Tsirkin int pci_bus_num(PCIBus *s)
605315a1350SMichael S. Tsirkin {
606602141d9SMarcel Apfelbaum     return PCI_BUS_GET_CLASS(s)->bus_num(s);
607315a1350SMichael S. Tsirkin }
608315a1350SMichael S. Tsirkin 
609500db1daSXingang Wang /* Returns the min and max bus numbers of a PCI bus hierarchy */
610500db1daSXingang Wang void pci_bus_range(PCIBus *bus, int *min_bus, int *max_bus)
611500db1daSXingang Wang {
612500db1daSXingang Wang     int i;
613500db1daSXingang Wang     *min_bus = *max_bus = pci_bus_num(bus);
614500db1daSXingang Wang 
615500db1daSXingang Wang     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
616500db1daSXingang Wang         PCIDevice *dev = bus->devices[i];
617500db1daSXingang Wang 
618ad494274SIgor Mammedov         if (dev && IS_PCI_BRIDGE(dev)) {
619500db1daSXingang Wang             *min_bus = MIN(*min_bus, dev->config[PCI_SECONDARY_BUS]);
620500db1daSXingang Wang             *max_bus = MAX(*max_bus, dev->config[PCI_SUBORDINATE_BUS]);
621500db1daSXingang Wang         }
622500db1daSXingang Wang     }
623500db1daSXingang Wang }
624500db1daSXingang Wang 
6256a3042b2SMarcel Apfelbaum int pci_bus_numa_node(PCIBus *bus)
6266a3042b2SMarcel Apfelbaum {
6276a3042b2SMarcel Apfelbaum     return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
628315a1350SMichael S. Tsirkin }
629315a1350SMichael S. Tsirkin 
6302c21ee76SJianjun Duan static int get_pci_config_device(QEMUFile *f, void *pv, size_t size,
63103fee66fSMarc-André Lureau                                  const VMStateField *field)
632315a1350SMichael S. Tsirkin {
633315a1350SMichael S. Tsirkin     PCIDevice *s = container_of(pv, PCIDevice, config);
634315a1350SMichael S. Tsirkin     uint8_t *config;
635315a1350SMichael S. Tsirkin     int i;
636315a1350SMichael S. Tsirkin 
637315a1350SMichael S. Tsirkin     assert(size == pci_config_size(s));
638315a1350SMichael S. Tsirkin     config = g_malloc(size);
639315a1350SMichael S. Tsirkin 
640315a1350SMichael S. Tsirkin     qemu_get_buffer(f, config, size);
641315a1350SMichael S. Tsirkin     for (i = 0; i < size; ++i) {
642315a1350SMichael S. Tsirkin         if ((config[i] ^ s->config[i]) &
643315a1350SMichael S. Tsirkin             s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
6447c59364dSDr. David Alan Gilbert             error_report("%s: Bad config data: i=0x%x read: %x device: %x "
6457c59364dSDr. David Alan Gilbert                          "cmask: %x wmask: %x w1cmask:%x", __func__,
6467c59364dSDr. David Alan Gilbert                          i, config[i], s->config[i],
6477c59364dSDr. David Alan Gilbert                          s->cmask[i], s->wmask[i], s->w1cmask[i]);
648315a1350SMichael S. Tsirkin             g_free(config);
649315a1350SMichael S. Tsirkin             return -EINVAL;
650315a1350SMichael S. Tsirkin         }
651315a1350SMichael S. Tsirkin     }
652315a1350SMichael S. Tsirkin     memcpy(s->config, config, size);
653315a1350SMichael S. Tsirkin 
654315a1350SMichael S. Tsirkin     pci_update_mappings(s);
655ad494274SIgor Mammedov     if (IS_PCI_BRIDGE(s)) {
656ad494274SIgor Mammedov         pci_bridge_update_mappings(PCI_BRIDGE(s));
657e78e9ae4SDon Koch     }
658315a1350SMichael S. Tsirkin 
659315a1350SMichael S. Tsirkin     memory_region_set_enabled(&s->bus_master_enable_region,
660315a1350SMichael S. Tsirkin                               pci_get_word(s->config + PCI_COMMAND)
661315a1350SMichael S. Tsirkin                               & PCI_COMMAND_MASTER);
662315a1350SMichael S. Tsirkin 
663315a1350SMichael S. Tsirkin     g_free(config);
664315a1350SMichael S. Tsirkin     return 0;
665315a1350SMichael S. Tsirkin }
666315a1350SMichael S. Tsirkin 
667315a1350SMichael S. Tsirkin /* just put buffer */
6682c21ee76SJianjun Duan static int put_pci_config_device(QEMUFile *f, void *pv, size_t size,
6693ddba9a9SMarkus Armbruster                                  const VMStateField *field, JSONWriter *vmdesc)
670315a1350SMichael S. Tsirkin {
671315a1350SMichael S. Tsirkin     const uint8_t **v = pv;
672315a1350SMichael S. Tsirkin     assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
673315a1350SMichael S. Tsirkin     qemu_put_buffer(f, *v, size);
6742c21ee76SJianjun Duan 
6752c21ee76SJianjun Duan     return 0;
676315a1350SMichael S. Tsirkin }
677315a1350SMichael S. Tsirkin 
6788e5e0890SRichard Henderson static const VMStateInfo vmstate_info_pci_config = {
679315a1350SMichael S. Tsirkin     .name = "pci config",
680315a1350SMichael S. Tsirkin     .get  = get_pci_config_device,
681315a1350SMichael S. Tsirkin     .put  = put_pci_config_device,
682315a1350SMichael S. Tsirkin };
683315a1350SMichael S. Tsirkin 
6842c21ee76SJianjun Duan static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size,
68503fee66fSMarc-André Lureau                              const VMStateField *field)
686315a1350SMichael S. Tsirkin {
687315a1350SMichael S. Tsirkin     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
688315a1350SMichael S. Tsirkin     uint32_t irq_state[PCI_NUM_PINS];
689315a1350SMichael S. Tsirkin     int i;
690315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
691315a1350SMichael S. Tsirkin         irq_state[i] = qemu_get_be32(f);
692315a1350SMichael S. Tsirkin         if (irq_state[i] != 0x1 && irq_state[i] != 0) {
693315a1350SMichael S. Tsirkin             fprintf(stderr, "irq state %d: must be 0 or 1.\n",
694315a1350SMichael S. Tsirkin                     irq_state[i]);
695315a1350SMichael S. Tsirkin             return -EINVAL;
696315a1350SMichael S. Tsirkin         }
697315a1350SMichael S. Tsirkin     }
698315a1350SMichael S. Tsirkin 
699315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
700315a1350SMichael S. Tsirkin         pci_set_irq_state(s, i, irq_state[i]);
701315a1350SMichael S. Tsirkin     }
702315a1350SMichael S. Tsirkin 
703315a1350SMichael S. Tsirkin     return 0;
704315a1350SMichael S. Tsirkin }
705315a1350SMichael S. Tsirkin 
7062c21ee76SJianjun Duan static int put_pci_irq_state(QEMUFile *f, void *pv, size_t size,
7073ddba9a9SMarkus Armbruster                              const VMStateField *field, JSONWriter *vmdesc)
708315a1350SMichael S. Tsirkin {
709315a1350SMichael S. Tsirkin     int i;
710315a1350SMichael S. Tsirkin     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
711315a1350SMichael S. Tsirkin 
712315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
713315a1350SMichael S. Tsirkin         qemu_put_be32(f, pci_irq_state(s, i));
714315a1350SMichael S. Tsirkin     }
7152c21ee76SJianjun Duan 
7162c21ee76SJianjun Duan     return 0;
717315a1350SMichael S. Tsirkin }
718315a1350SMichael S. Tsirkin 
7198e5e0890SRichard Henderson static const VMStateInfo vmstate_info_pci_irq_state = {
720315a1350SMichael S. Tsirkin     .name = "pci irq state",
721315a1350SMichael S. Tsirkin     .get  = get_pci_irq_state,
722315a1350SMichael S. Tsirkin     .put  = put_pci_irq_state,
723315a1350SMichael S. Tsirkin };
724315a1350SMichael S. Tsirkin 
72520daa90aSDr. David Alan Gilbert static bool migrate_is_pcie(void *opaque, int version_id)
72620daa90aSDr. David Alan Gilbert {
72720daa90aSDr. David Alan Gilbert     return pci_is_express((PCIDevice *)opaque);
72820daa90aSDr. David Alan Gilbert }
72920daa90aSDr. David Alan Gilbert 
73020daa90aSDr. David Alan Gilbert static bool migrate_is_not_pcie(void *opaque, int version_id)
73120daa90aSDr. David Alan Gilbert {
73220daa90aSDr. David Alan Gilbert     return !pci_is_express((PCIDevice *)opaque);
73320daa90aSDr. David Alan Gilbert }
73420daa90aSDr. David Alan Gilbert 
735315a1350SMichael S. Tsirkin const VMStateDescription vmstate_pci_device = {
736315a1350SMichael S. Tsirkin     .name = "PCIDevice",
737315a1350SMichael S. Tsirkin     .version_id = 2,
738315a1350SMichael S. Tsirkin     .minimum_version_id = 1,
7398e5e0890SRichard Henderson     .fields = (const VMStateField[]) {
7403476436aSMichael S. Tsirkin         VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
74120daa90aSDr. David Alan Gilbert         VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
74220daa90aSDr. David Alan Gilbert                                    migrate_is_not_pcie,
74320daa90aSDr. David Alan Gilbert                                    0, vmstate_info_pci_config,
744315a1350SMichael S. Tsirkin                                    PCI_CONFIG_SPACE_SIZE),
74520daa90aSDr. David Alan Gilbert         VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
74620daa90aSDr. David Alan Gilbert                                    migrate_is_pcie,
74720daa90aSDr. David Alan Gilbert                                    0, vmstate_info_pci_config,
748315a1350SMichael S. Tsirkin                                    PCIE_CONFIG_SPACE_SIZE),
749315a1350SMichael S. Tsirkin         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
750315a1350SMichael S. Tsirkin                                    vmstate_info_pci_irq_state,
751315a1350SMichael S. Tsirkin                                    PCI_NUM_PINS * sizeof(int32_t)),
752315a1350SMichael S. Tsirkin         VMSTATE_END_OF_LIST()
753315a1350SMichael S. Tsirkin     }
754315a1350SMichael S. Tsirkin };
755315a1350SMichael S. Tsirkin 
756315a1350SMichael S. Tsirkin 
757315a1350SMichael S. Tsirkin void pci_device_save(PCIDevice *s, QEMUFile *f)
758315a1350SMichael S. Tsirkin {
759315a1350SMichael S. Tsirkin     /* Clear interrupt status bit: it is implicit
760315a1350SMichael S. Tsirkin      * in irq_state which we are saving.
761315a1350SMichael S. Tsirkin      * This makes us compatible with old devices
762315a1350SMichael S. Tsirkin      * which never set or clear this bit. */
763315a1350SMichael S. Tsirkin     s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
76420daa90aSDr. David Alan Gilbert     vmstate_save_state(f, &vmstate_pci_device, s, NULL);
765315a1350SMichael S. Tsirkin     /* Restore the interrupt status bit. */
766315a1350SMichael S. Tsirkin     pci_update_irq_status(s);
767315a1350SMichael S. Tsirkin }
768315a1350SMichael S. Tsirkin 
769315a1350SMichael S. Tsirkin int pci_device_load(PCIDevice *s, QEMUFile *f)
770315a1350SMichael S. Tsirkin {
771315a1350SMichael S. Tsirkin     int ret;
77220daa90aSDr. David Alan Gilbert     ret = vmstate_load_state(f, &vmstate_pci_device, s, s->version_id);
773315a1350SMichael S. Tsirkin     /* Restore the interrupt status bit. */
774315a1350SMichael S. Tsirkin     pci_update_irq_status(s);
775315a1350SMichael S. Tsirkin     return ret;
776315a1350SMichael S. Tsirkin }
777315a1350SMichael S. Tsirkin 
778315a1350SMichael S. Tsirkin static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
779315a1350SMichael S. Tsirkin {
780315a1350SMichael S. Tsirkin     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
781315a1350SMichael S. Tsirkin                  pci_default_sub_vendor_id);
782315a1350SMichael S. Tsirkin     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
783315a1350SMichael S. Tsirkin                  pci_default_sub_device_id);
784315a1350SMichael S. Tsirkin }
785315a1350SMichael S. Tsirkin 
786315a1350SMichael S. Tsirkin /*
787315a1350SMichael S. Tsirkin  * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
788315a1350SMichael S. Tsirkin  *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
789315a1350SMichael S. Tsirkin  */
7906dbcb819SMarkus Armbruster static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
791315a1350SMichael S. Tsirkin                              unsigned int *slotp, unsigned int *funcp)
792315a1350SMichael S. Tsirkin {
793315a1350SMichael S. Tsirkin     const char *p;
794315a1350SMichael S. Tsirkin     char *e;
795315a1350SMichael S. Tsirkin     unsigned long val;
796315a1350SMichael S. Tsirkin     unsigned long dom = 0, bus = 0;
797315a1350SMichael S. Tsirkin     unsigned int slot = 0;
798315a1350SMichael S. Tsirkin     unsigned int func = 0;
799315a1350SMichael S. Tsirkin 
800315a1350SMichael S. Tsirkin     p = addr;
801315a1350SMichael S. Tsirkin     val = strtoul(p, &e, 16);
802315a1350SMichael S. Tsirkin     if (e == p)
803315a1350SMichael S. Tsirkin         return -1;
804315a1350SMichael S. Tsirkin     if (*e == ':') {
805315a1350SMichael S. Tsirkin         bus = val;
806315a1350SMichael S. Tsirkin         p = e + 1;
807315a1350SMichael S. Tsirkin         val = strtoul(p, &e, 16);
808315a1350SMichael S. Tsirkin         if (e == p)
809315a1350SMichael S. Tsirkin             return -1;
810315a1350SMichael S. Tsirkin         if (*e == ':') {
811315a1350SMichael S. Tsirkin             dom = bus;
812315a1350SMichael S. Tsirkin             bus = val;
813315a1350SMichael S. Tsirkin             p = e + 1;
814315a1350SMichael S. Tsirkin             val = strtoul(p, &e, 16);
815315a1350SMichael S. Tsirkin             if (e == p)
816315a1350SMichael S. Tsirkin                 return -1;
817315a1350SMichael S. Tsirkin         }
818315a1350SMichael S. Tsirkin     }
819315a1350SMichael S. Tsirkin 
820315a1350SMichael S. Tsirkin     slot = val;
821315a1350SMichael S. Tsirkin 
822315a1350SMichael S. Tsirkin     if (funcp != NULL) {
823315a1350SMichael S. Tsirkin         if (*e != '.')
824315a1350SMichael S. Tsirkin             return -1;
825315a1350SMichael S. Tsirkin 
826315a1350SMichael S. Tsirkin         p = e + 1;
827315a1350SMichael S. Tsirkin         val = strtoul(p, &e, 16);
828315a1350SMichael S. Tsirkin         if (e == p)
829315a1350SMichael S. Tsirkin             return -1;
830315a1350SMichael S. Tsirkin 
831315a1350SMichael S. Tsirkin         func = val;
832315a1350SMichael S. Tsirkin     }
833315a1350SMichael S. Tsirkin 
834315a1350SMichael S. Tsirkin     /* if funcp == NULL func is 0 */
835315a1350SMichael S. Tsirkin     if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
836315a1350SMichael S. Tsirkin         return -1;
837315a1350SMichael S. Tsirkin 
838315a1350SMichael S. Tsirkin     if (*e)
839315a1350SMichael S. Tsirkin         return -1;
840315a1350SMichael S. Tsirkin 
841315a1350SMichael S. Tsirkin     *domp = dom;
842315a1350SMichael S. Tsirkin     *busp = bus;
843315a1350SMichael S. Tsirkin     *slotp = slot;
844315a1350SMichael S. Tsirkin     if (funcp != NULL)
845315a1350SMichael S. Tsirkin         *funcp = func;
846315a1350SMichael S. Tsirkin     return 0;
847315a1350SMichael S. Tsirkin }
848315a1350SMichael S. Tsirkin 
849315a1350SMichael S. Tsirkin static void pci_init_cmask(PCIDevice *dev)
850315a1350SMichael S. Tsirkin {
851315a1350SMichael S. Tsirkin     pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
852315a1350SMichael S. Tsirkin     pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
853315a1350SMichael S. Tsirkin     dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
854315a1350SMichael S. Tsirkin     dev->cmask[PCI_REVISION_ID] = 0xff;
855315a1350SMichael S. Tsirkin     dev->cmask[PCI_CLASS_PROG] = 0xff;
856315a1350SMichael S. Tsirkin     pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
857315a1350SMichael S. Tsirkin     dev->cmask[PCI_HEADER_TYPE] = 0xff;
858315a1350SMichael S. Tsirkin     dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
859315a1350SMichael S. Tsirkin }
860315a1350SMichael S. Tsirkin 
861315a1350SMichael S. Tsirkin static void pci_init_wmask(PCIDevice *dev)
862315a1350SMichael S. Tsirkin {
863315a1350SMichael S. Tsirkin     int config_size = pci_config_size(dev);
864315a1350SMichael S. Tsirkin 
865315a1350SMichael S. Tsirkin     dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
866315a1350SMichael S. Tsirkin     dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
867315a1350SMichael S. Tsirkin     pci_set_word(dev->wmask + PCI_COMMAND,
868315a1350SMichael S. Tsirkin                  PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
869315a1350SMichael S. Tsirkin                  PCI_COMMAND_INTX_DISABLE);
870315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
871315a1350SMichael S. Tsirkin 
872315a1350SMichael S. Tsirkin     memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
873315a1350SMichael S. Tsirkin            config_size - PCI_CONFIG_HEADER_SIZE);
874315a1350SMichael S. Tsirkin }
875315a1350SMichael S. Tsirkin 
876315a1350SMichael S. Tsirkin static void pci_init_w1cmask(PCIDevice *dev)
877315a1350SMichael S. Tsirkin {
878315a1350SMichael S. Tsirkin     /*
879315a1350SMichael S. Tsirkin      * Note: It's okay to set w1cmask even for readonly bits as
880315a1350SMichael S. Tsirkin      * long as their value is hardwired to 0.
881315a1350SMichael S. Tsirkin      */
882315a1350SMichael S. Tsirkin     pci_set_word(dev->w1cmask + PCI_STATUS,
883315a1350SMichael S. Tsirkin                  PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
884315a1350SMichael S. Tsirkin                  PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
885315a1350SMichael S. Tsirkin                  PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
886315a1350SMichael S. Tsirkin }
887315a1350SMichael S. Tsirkin 
888315a1350SMichael S. Tsirkin static void pci_init_mask_bridge(PCIDevice *d)
889315a1350SMichael S. Tsirkin {
890315a1350SMichael S. Tsirkin     /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
8914565917bSMichael S. Tsirkin        PCI_SEC_LATENCY_TIMER */
892315a1350SMichael S. Tsirkin     memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
893315a1350SMichael S. Tsirkin 
894315a1350SMichael S. Tsirkin     /* base and limit */
895315a1350SMichael S. Tsirkin     d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
896315a1350SMichael S. Tsirkin     d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
897315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_MEMORY_BASE,
898315a1350SMichael S. Tsirkin                  PCI_MEMORY_RANGE_MASK & 0xffff);
899315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
900315a1350SMichael S. Tsirkin                  PCI_MEMORY_RANGE_MASK & 0xffff);
901315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
902315a1350SMichael S. Tsirkin                  PCI_PREF_RANGE_MASK & 0xffff);
903315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
904315a1350SMichael S. Tsirkin                  PCI_PREF_RANGE_MASK & 0xffff);
905315a1350SMichael S. Tsirkin 
906315a1350SMichael S. Tsirkin     /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
907315a1350SMichael S. Tsirkin     memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
908315a1350SMichael S. Tsirkin 
909315a1350SMichael S. Tsirkin     /* Supported memory and i/o types */
910315a1350SMichael S. Tsirkin     d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
911315a1350SMichael S. Tsirkin     d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
912315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
913315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_64);
914315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
915315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_64);
916315a1350SMichael S. Tsirkin 
917ba7d8515SAlex Williamson     /*
918ba7d8515SAlex Williamson      * TODO: Bridges default to 10-bit VGA decoding but we currently only
919ba7d8515SAlex Williamson      * implement 16-bit decoding (no alias support).
920ba7d8515SAlex Williamson      */
921315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
922315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_PARITY |
923315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_SERR |
924315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_ISA |
925315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_VGA |
926315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_VGA_16BIT |
927315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_MASTER_ABORT |
928315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_BUS_RESET |
929315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_FAST_BACK |
930315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_DISCARD |
931315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_SEC_DISCARD |
932315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_DISCARD_SERR);
933315a1350SMichael S. Tsirkin     /* Below does not do anything as we never set this bit, put here for
934315a1350SMichael S. Tsirkin      * completeness. */
935315a1350SMichael S. Tsirkin     pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
936315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_DISCARD_STATUS);
937315a1350SMichael S. Tsirkin     d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
938315a1350SMichael S. Tsirkin     d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
939315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
940315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_MASK);
941315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
942315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_MASK);
943315a1350SMichael S. Tsirkin }
944315a1350SMichael S. Tsirkin 
945133e9b22SMarkus Armbruster static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
946315a1350SMichael S. Tsirkin {
947315a1350SMichael S. Tsirkin     uint8_t slot = PCI_SLOT(dev->devfn);
948315a1350SMichael S. Tsirkin     uint8_t func;
949315a1350SMichael S. Tsirkin 
950315a1350SMichael S. Tsirkin     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
951315a1350SMichael S. Tsirkin         dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
952315a1350SMichael S. Tsirkin     }
953315a1350SMichael S. Tsirkin 
954315a1350SMichael S. Tsirkin     /*
9557c0fa8dfSKnut Omang      * With SR/IOV and ARI, a device at function 0 need not be a multifunction
9567c0fa8dfSKnut Omang      * device, as it may just be a VF that ended up with function 0 in
9577c0fa8dfSKnut Omang      * the legacy PCI interpretation. Avoid failing in such cases:
9587c0fa8dfSKnut Omang      */
9597c0fa8dfSKnut Omang     if (pci_is_vf(dev) &&
9607c0fa8dfSKnut Omang         dev->exp.sriov_vf.pf->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
9617c0fa8dfSKnut Omang         return;
9627c0fa8dfSKnut Omang     }
9637c0fa8dfSKnut Omang 
9647c0fa8dfSKnut Omang     /*
965315a1350SMichael S. Tsirkin      * multifunction bit is interpreted in two ways as follows.
966315a1350SMichael S. Tsirkin      *   - all functions must set the bit to 1.
967315a1350SMichael S. Tsirkin      *     Example: Intel X53
968315a1350SMichael S. Tsirkin      *   - function 0 must set the bit, but the rest function (> 0)
969315a1350SMichael S. Tsirkin      *     is allowed to leave the bit to 0.
970315a1350SMichael S. Tsirkin      *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
971315a1350SMichael S. Tsirkin      *
972315a1350SMichael S. Tsirkin      * So OS (at least Linux) checks the bit of only function 0,
973315a1350SMichael S. Tsirkin      * and doesn't see the bit of function > 0.
974315a1350SMichael S. Tsirkin      *
975315a1350SMichael S. Tsirkin      * The below check allows both interpretation.
976315a1350SMichael S. Tsirkin      */
977315a1350SMichael S. Tsirkin     if (PCI_FUNC(dev->devfn)) {
978315a1350SMichael S. Tsirkin         PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
979315a1350SMichael S. Tsirkin         if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
980315a1350SMichael S. Tsirkin             /* function 0 should set multifunction bit */
981133e9b22SMarkus Armbruster             error_setg(errp, "PCI: single function device can't be populated "
982315a1350SMichael S. Tsirkin                        "in function %x.%x", slot, PCI_FUNC(dev->devfn));
983133e9b22SMarkus Armbruster             return;
984315a1350SMichael S. Tsirkin         }
985133e9b22SMarkus Armbruster         return;
986315a1350SMichael S. Tsirkin     }
987315a1350SMichael S. Tsirkin 
988315a1350SMichael S. Tsirkin     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
989133e9b22SMarkus Armbruster         return;
990315a1350SMichael S. Tsirkin     }
991315a1350SMichael S. Tsirkin     /* function 0 indicates single function, so function > 0 must be NULL */
992315a1350SMichael S. Tsirkin     for (func = 1; func < PCI_FUNC_MAX; ++func) {
993315a1350SMichael S. Tsirkin         if (bus->devices[PCI_DEVFN(slot, func)]) {
994133e9b22SMarkus Armbruster             error_setg(errp, "PCI: %x.0 indicates single function, "
995315a1350SMichael S. Tsirkin                        "but %x.%x is already populated.",
996315a1350SMichael S. Tsirkin                        slot, slot, func);
997133e9b22SMarkus Armbruster             return;
998315a1350SMichael S. Tsirkin         }
999315a1350SMichael S. Tsirkin     }
1000315a1350SMichael S. Tsirkin }
1001315a1350SMichael S. Tsirkin 
1002315a1350SMichael S. Tsirkin static void pci_config_alloc(PCIDevice *pci_dev)
1003315a1350SMichael S. Tsirkin {
1004315a1350SMichael S. Tsirkin     int config_size = pci_config_size(pci_dev);
1005315a1350SMichael S. Tsirkin 
1006315a1350SMichael S. Tsirkin     pci_dev->config = g_malloc0(config_size);
1007315a1350SMichael S. Tsirkin     pci_dev->cmask = g_malloc0(config_size);
1008315a1350SMichael S. Tsirkin     pci_dev->wmask = g_malloc0(config_size);
1009315a1350SMichael S. Tsirkin     pci_dev->w1cmask = g_malloc0(config_size);
1010315a1350SMichael S. Tsirkin     pci_dev->used = g_malloc0(config_size);
1011315a1350SMichael S. Tsirkin }
1012315a1350SMichael S. Tsirkin 
1013315a1350SMichael S. Tsirkin static void pci_config_free(PCIDevice *pci_dev)
1014315a1350SMichael S. Tsirkin {
1015315a1350SMichael S. Tsirkin     g_free(pci_dev->config);
1016315a1350SMichael S. Tsirkin     g_free(pci_dev->cmask);
1017315a1350SMichael S. Tsirkin     g_free(pci_dev->wmask);
1018315a1350SMichael S. Tsirkin     g_free(pci_dev->w1cmask);
1019315a1350SMichael S. Tsirkin     g_free(pci_dev->used);
1020315a1350SMichael S. Tsirkin }
1021315a1350SMichael S. Tsirkin 
102230607764SMarcel Apfelbaum static void do_pci_unregister_device(PCIDevice *pci_dev)
102330607764SMarcel Apfelbaum {
1024fd56e061SDavid Gibson     pci_get_bus(pci_dev)->devices[pci_dev->devfn] = NULL;
102530607764SMarcel Apfelbaum     pci_config_free(pci_dev);
102630607764SMarcel Apfelbaum 
10276096cf78SDavid Woodhouse     if (xen_mode == XEN_EMULATE) {
10286096cf78SDavid Woodhouse         xen_evtchn_remove_pci_device(pci_dev);
10296096cf78SDavid Woodhouse     }
1030193982c6SAlexey Kardashevskiy     if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {
1031c53598edSAlexey Kardashevskiy         memory_region_del_subregion(&pci_dev->bus_master_container_region,
1032c53598edSAlexey Kardashevskiy                                     &pci_dev->bus_master_enable_region);
1033193982c6SAlexey Kardashevskiy     }
103430607764SMarcel Apfelbaum     address_space_destroy(&pci_dev->bus_master_as);
103530607764SMarcel Apfelbaum }
103630607764SMarcel Apfelbaum 
10374a94b3aaSPeter Xu /* Extract PCIReqIDCache into BDF format */
10384a94b3aaSPeter Xu static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
10394a94b3aaSPeter Xu {
10404a94b3aaSPeter Xu     uint8_t bus_n;
10414a94b3aaSPeter Xu     uint16_t result;
10424a94b3aaSPeter Xu 
10434a94b3aaSPeter Xu     switch (cache->type) {
10444a94b3aaSPeter Xu     case PCI_REQ_ID_BDF:
10454a94b3aaSPeter Xu         result = pci_get_bdf(cache->dev);
10464a94b3aaSPeter Xu         break;
10474a94b3aaSPeter Xu     case PCI_REQ_ID_SECONDARY_BUS:
1048fd56e061SDavid Gibson         bus_n = pci_dev_bus_num(cache->dev);
10494a94b3aaSPeter Xu         result = PCI_BUILD_BDF(bus_n, 0);
10504a94b3aaSPeter Xu         break;
10514a94b3aaSPeter Xu     default:
1052eaf27fabSMarkus Armbruster         error_report("Invalid PCI requester ID cache type: %d",
10534a94b3aaSPeter Xu                      cache->type);
10544a94b3aaSPeter Xu         exit(1);
10554a94b3aaSPeter Xu         break;
10564a94b3aaSPeter Xu     }
10574a94b3aaSPeter Xu 
10584a94b3aaSPeter Xu     return result;
10594a94b3aaSPeter Xu }
10604a94b3aaSPeter Xu 
10614a94b3aaSPeter Xu /* Parse bridges up to the root complex and return requester ID
10624a94b3aaSPeter Xu  * cache for specific device.  For full PCIe topology, the cache
10634a94b3aaSPeter Xu  * result would be exactly the same as getting BDF of the device.
10644a94b3aaSPeter Xu  * However, several tricks are required when system mixed up with
10654a94b3aaSPeter Xu  * legacy PCI devices and PCIe-to-PCI bridges.
10664a94b3aaSPeter Xu  *
10674a94b3aaSPeter Xu  * Here we cache the proxy device (and type) not requester ID since
10684a94b3aaSPeter Xu  * bus number might change from time to time.
10694a94b3aaSPeter Xu  */
10704a94b3aaSPeter Xu static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
10714a94b3aaSPeter Xu {
10724a94b3aaSPeter Xu     PCIDevice *parent;
10734a94b3aaSPeter Xu     PCIReqIDCache cache = {
10744a94b3aaSPeter Xu         .dev = dev,
10754a94b3aaSPeter Xu         .type = PCI_REQ_ID_BDF,
10764a94b3aaSPeter Xu     };
10774a94b3aaSPeter Xu 
1078fd56e061SDavid Gibson     while (!pci_bus_is_root(pci_get_bus(dev))) {
10794a94b3aaSPeter Xu         /* We are under PCI/PCIe bridges */
1080fd56e061SDavid Gibson         parent = pci_get_bus(dev)->parent_dev;
10814a94b3aaSPeter Xu         if (pci_is_express(parent)) {
10824a94b3aaSPeter Xu             if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
10834a94b3aaSPeter Xu                 /* When we pass through PCIe-to-PCI/PCIX bridges, we
10844a94b3aaSPeter Xu                  * override the requester ID using secondary bus
10854a94b3aaSPeter Xu                  * number of parent bridge with zeroed devfn
10864a94b3aaSPeter Xu                  * (pcie-to-pci bridge spec chap 2.3). */
10874a94b3aaSPeter Xu                 cache.type = PCI_REQ_ID_SECONDARY_BUS;
10884a94b3aaSPeter Xu                 cache.dev = dev;
10894a94b3aaSPeter Xu             }
10904a94b3aaSPeter Xu         } else {
10914a94b3aaSPeter Xu             /* Legacy PCI, override requester ID with the bridge's
10924a94b3aaSPeter Xu              * BDF upstream.  When the root complex connects to
10934a94b3aaSPeter Xu              * legacy PCI devices (including buses), it can only
10944a94b3aaSPeter Xu              * obtain requester ID info from directly attached
10954a94b3aaSPeter Xu              * devices.  If devices are attached under bridges, only
10964a94b3aaSPeter Xu              * the requester ID of the bridge that is directly
10974a94b3aaSPeter Xu              * attached to the root complex can be recognized. */
10984a94b3aaSPeter Xu             cache.type = PCI_REQ_ID_BDF;
10994a94b3aaSPeter Xu             cache.dev = parent;
11004a94b3aaSPeter Xu         }
11014a94b3aaSPeter Xu         dev = parent;
11024a94b3aaSPeter Xu     }
11034a94b3aaSPeter Xu 
11044a94b3aaSPeter Xu     return cache;
11054a94b3aaSPeter Xu }
11064a94b3aaSPeter Xu 
11074a94b3aaSPeter Xu uint16_t pci_requester_id(PCIDevice *dev)
11084a94b3aaSPeter Xu {
11094a94b3aaSPeter Xu     return pci_req_id_cache_extract(&dev->requester_id_cache);
11104a94b3aaSPeter Xu }
11114a94b3aaSPeter Xu 
11129b717a3aSMark Cave-Ayland static bool pci_bus_devfn_available(PCIBus *bus, int devfn)
11139b717a3aSMark Cave-Ayland {
11149b717a3aSMark Cave-Ayland     return !(bus->devices[devfn]);
11159b717a3aSMark Cave-Ayland }
11169b717a3aSMark Cave-Ayland 
11178b884984SMark Cave-Ayland static bool pci_bus_devfn_reserved(PCIBus *bus, int devfn)
11188b884984SMark Cave-Ayland {
11198b884984SMark Cave-Ayland     return bus->slot_reserved_mask & (1UL << PCI_SLOT(devfn));
11208b884984SMark Cave-Ayland }
11218b884984SMark Cave-Ayland 
1122b93fe7f2SChuck Zmudzinski uint32_t pci_bus_get_slot_reserved_mask(PCIBus *bus)
1123b93fe7f2SChuck Zmudzinski {
1124b93fe7f2SChuck Zmudzinski     return bus->slot_reserved_mask;
1125b93fe7f2SChuck Zmudzinski }
1126b93fe7f2SChuck Zmudzinski 
1127b93fe7f2SChuck Zmudzinski void pci_bus_set_slot_reserved_mask(PCIBus *bus, uint32_t mask)
1128b93fe7f2SChuck Zmudzinski {
1129b93fe7f2SChuck Zmudzinski     bus->slot_reserved_mask |= mask;
1130b93fe7f2SChuck Zmudzinski }
1131b93fe7f2SChuck Zmudzinski 
1132b93fe7f2SChuck Zmudzinski void pci_bus_clear_slot_reserved_mask(PCIBus *bus, uint32_t mask)
1133b93fe7f2SChuck Zmudzinski {
1134b93fe7f2SChuck Zmudzinski     bus->slot_reserved_mask &= ~mask;
1135b93fe7f2SChuck Zmudzinski }
1136b93fe7f2SChuck Zmudzinski 
1137315a1350SMichael S. Tsirkin /* -1 for devfn means auto assign */
1138fd56e061SDavid Gibson static PCIDevice *do_pci_register_device(PCIDevice *pci_dev,
1139133e9b22SMarkus Armbruster                                          const char *name, int devfn,
1140133e9b22SMarkus Armbruster                                          Error **errp)
1141315a1350SMichael S. Tsirkin {
1142315a1350SMichael S. Tsirkin     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1143315a1350SMichael S. Tsirkin     PCIConfigReadFunc *config_read = pc->config_read;
1144315a1350SMichael S. Tsirkin     PCIConfigWriteFunc *config_write = pc->config_write;
1145133e9b22SMarkus Armbruster     Error *local_err = NULL;
11463f1e1478SCao jin     DeviceState *dev = DEVICE(pci_dev);
1147fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
1148ad494274SIgor Mammedov     bool is_bridge = IS_PCI_BRIDGE(pci_dev);
11493f1e1478SCao jin 
11500144f6f1SMarcel Apfelbaum     /* Only pci bridges can be attached to extra PCI root buses */
1151ad494274SIgor Mammedov     if (pci_bus_is_root(bus) && bus->parent_dev && !is_bridge) {
11520144f6f1SMarcel Apfelbaum         error_setg(errp,
11530144f6f1SMarcel Apfelbaum                    "PCI: Only PCI/PCIe bridges can be plugged into %s",
11540144f6f1SMarcel Apfelbaum                     bus->parent_dev->name);
11550144f6f1SMarcel Apfelbaum         return NULL;
11560144f6f1SMarcel Apfelbaum     }
1157315a1350SMichael S. Tsirkin 
1158315a1350SMichael S. Tsirkin     if (devfn < 0) {
1159315a1350SMichael S. Tsirkin         for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
1160315a1350SMichael S. Tsirkin             devfn += PCI_FUNC_MAX) {
11618b884984SMark Cave-Ayland             if (pci_bus_devfn_available(bus, devfn) &&
11628b884984SMark Cave-Ayland                    !pci_bus_devfn_reserved(bus, devfn)) {
1163315a1350SMichael S. Tsirkin                 goto found;
1164315a1350SMichael S. Tsirkin             }
11659b717a3aSMark Cave-Ayland         }
11668b884984SMark Cave-Ayland         error_setg(errp, "PCI: no slot/function available for %s, all in use "
11678b884984SMark Cave-Ayland                    "or reserved", name);
1168315a1350SMichael S. Tsirkin         return NULL;
1169315a1350SMichael S. Tsirkin     found: ;
11708b884984SMark Cave-Ayland     } else if (pci_bus_devfn_reserved(bus, devfn)) {
11718b884984SMark Cave-Ayland         error_setg(errp, "PCI: slot %d function %d not available for %s,"
11728b884984SMark Cave-Ayland                    " reserved",
11738b884984SMark Cave-Ayland                    PCI_SLOT(devfn), PCI_FUNC(devfn), name);
11748b884984SMark Cave-Ayland         return NULL;
11759b717a3aSMark Cave-Ayland     } else if (!pci_bus_devfn_available(bus, devfn)) {
1176133e9b22SMarkus Armbruster         error_setg(errp, "PCI: slot %d function %d not available for %s,"
1177ad003b9eSZhenzhong Duan                    " in use by %s,id=%s",
1178133e9b22SMarkus Armbruster                    PCI_SLOT(devfn), PCI_FUNC(devfn), name,
1179ad003b9eSZhenzhong Duan                    bus->devices[devfn]->name, bus->devices[devfn]->qdev.id);
1180315a1350SMichael S. Tsirkin         return NULL;
118167d045a0SAni Sinha     } /*
118267d045a0SAni Sinha        * Populating function 0 triggers a scan from the guest that
118367d045a0SAni Sinha        * exposes other non-zero functions. Hence we need to ensure that
118467d045a0SAni Sinha        * function 0 wasn't added yet.
118567d045a0SAni Sinha        */
118667d045a0SAni Sinha     else if (dev->hotplugged &&
11877c0fa8dfSKnut Omang              !pci_is_vf(pci_dev) &&
11883f1e1478SCao jin              pci_get_function_0(pci_dev)) {
11893298bbceSJulia Suvorova         error_setg(errp, "PCI: slot %d function 0 already occupied by %s,"
11903f1e1478SCao jin                    " new func %s cannot be exposed to guest.",
1191d93ddfb1SMichael S. Tsirkin                    PCI_SLOT(pci_get_function_0(pci_dev)->devfn),
1192d93ddfb1SMichael S. Tsirkin                    pci_get_function_0(pci_dev)->name,
11933f1e1478SCao jin                    name);
11943f1e1478SCao jin 
11953f1e1478SCao jin        return NULL;
1196315a1350SMichael S. Tsirkin     }
1197e00387d5SAvi Kivity 
1198efc8188eSLe Tan     pci_dev->devfn = devfn;
11994a94b3aaSPeter Xu     pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
1200d06bce95SAlexey Kardashevskiy     pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
1201e00387d5SAvi Kivity 
12023716d590SJason Wang     memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),
12033716d590SJason Wang                        "bus master container", UINT64_MAX);
12043716d590SJason Wang     address_space_init(&pci_dev->bus_master_as,
12053716d590SJason Wang                        &pci_dev->bus_master_container_region, pci_dev->name);
12063716d590SJason Wang 
12072f181fbdSPaolo Bonzini     if (phase_check(PHASE_MACHINE_READY)) {
1208b86eacb8SMarcel Apfelbaum         pci_init_bus_master(pci_dev);
1209b86eacb8SMarcel Apfelbaum     }
1210315a1350SMichael S. Tsirkin     pci_dev->irq_state = 0;
1211315a1350SMichael S. Tsirkin     pci_config_alloc(pci_dev);
1212315a1350SMichael S. Tsirkin 
1213315a1350SMichael S. Tsirkin     pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1214315a1350SMichael S. Tsirkin     pci_config_set_device_id(pci_dev->config, pc->device_id);
1215315a1350SMichael S. Tsirkin     pci_config_set_revision(pci_dev->config, pc->revision);
1216315a1350SMichael S. Tsirkin     pci_config_set_class(pci_dev->config, pc->class_id);
1217315a1350SMichael S. Tsirkin 
1218ad494274SIgor Mammedov     if (!is_bridge) {
1219315a1350SMichael S. Tsirkin         if (pc->subsystem_vendor_id || pc->subsystem_id) {
1220315a1350SMichael S. Tsirkin             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1221315a1350SMichael S. Tsirkin                          pc->subsystem_vendor_id);
1222315a1350SMichael S. Tsirkin             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1223315a1350SMichael S. Tsirkin                          pc->subsystem_id);
1224315a1350SMichael S. Tsirkin         } else {
1225315a1350SMichael S. Tsirkin             pci_set_default_subsystem_id(pci_dev);
1226315a1350SMichael S. Tsirkin         }
1227315a1350SMichael S. Tsirkin     } else {
1228315a1350SMichael S. Tsirkin         /* subsystem_vendor_id/subsystem_id are only for header type 0 */
1229315a1350SMichael S. Tsirkin         assert(!pc->subsystem_vendor_id);
1230315a1350SMichael S. Tsirkin         assert(!pc->subsystem_id);
1231315a1350SMichael S. Tsirkin     }
1232315a1350SMichael S. Tsirkin     pci_init_cmask(pci_dev);
1233315a1350SMichael S. Tsirkin     pci_init_wmask(pci_dev);
1234315a1350SMichael S. Tsirkin     pci_init_w1cmask(pci_dev);
1235ad494274SIgor Mammedov     if (is_bridge) {
1236315a1350SMichael S. Tsirkin         pci_init_mask_bridge(pci_dev);
1237315a1350SMichael S. Tsirkin     }
1238133e9b22SMarkus Armbruster     pci_init_multifunction(bus, pci_dev, &local_err);
1239133e9b22SMarkus Armbruster     if (local_err) {
1240133e9b22SMarkus Armbruster         error_propagate(errp, local_err);
124130607764SMarcel Apfelbaum         do_pci_unregister_device(pci_dev);
1242315a1350SMichael S. Tsirkin         return NULL;
1243315a1350SMichael S. Tsirkin     }
1244315a1350SMichael S. Tsirkin 
1245315a1350SMichael S. Tsirkin     if (!config_read)
1246315a1350SMichael S. Tsirkin         config_read = pci_default_read_config;
1247315a1350SMichael S. Tsirkin     if (!config_write)
1248315a1350SMichael S. Tsirkin         config_write = pci_default_write_config;
1249315a1350SMichael S. Tsirkin     pci_dev->config_read = config_read;
1250315a1350SMichael S. Tsirkin     pci_dev->config_write = config_write;
1251315a1350SMichael S. Tsirkin     bus->devices[devfn] = pci_dev;
1252315a1350SMichael S. Tsirkin     pci_dev->version_id = 2; /* Current pci device vmstate version */
1253315a1350SMichael S. Tsirkin     return pci_dev;
1254315a1350SMichael S. Tsirkin }
1255315a1350SMichael S. Tsirkin 
1256315a1350SMichael S. Tsirkin static void pci_unregister_io_regions(PCIDevice *pci_dev)
1257315a1350SMichael S. Tsirkin {
1258315a1350SMichael S. Tsirkin     PCIIORegion *r;
1259315a1350SMichael S. Tsirkin     int i;
1260315a1350SMichael S. Tsirkin 
1261315a1350SMichael S. Tsirkin     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1262315a1350SMichael S. Tsirkin         r = &pci_dev->io_regions[i];
1263315a1350SMichael S. Tsirkin         if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1264315a1350SMichael S. Tsirkin             continue;
1265315a1350SMichael S. Tsirkin         memory_region_del_subregion(r->address_space, r->memory);
1266315a1350SMichael S. Tsirkin     }
1267e01fd687SAlex Williamson 
1268e01fd687SAlex Williamson     pci_unregister_vga(pci_dev);
1269315a1350SMichael S. Tsirkin }
1270315a1350SMichael S. Tsirkin 
1271b69c3c21SMarkus Armbruster static void pci_qdev_unrealize(DeviceState *dev)
1272315a1350SMichael S. Tsirkin {
1273315a1350SMichael S. Tsirkin     PCIDevice *pci_dev = PCI_DEVICE(dev);
1274315a1350SMichael S. Tsirkin     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1275315a1350SMichael S. Tsirkin 
1276315a1350SMichael S. Tsirkin     pci_unregister_io_regions(pci_dev);
1277315a1350SMichael S. Tsirkin     pci_del_option_rom(pci_dev);
1278315a1350SMichael S. Tsirkin 
1279315a1350SMichael S. Tsirkin     if (pc->exit) {
1280315a1350SMichael S. Tsirkin         pc->exit(pci_dev);
1281315a1350SMichael S. Tsirkin     }
1282315a1350SMichael S. Tsirkin 
12833936161fSHerongguang (Stephen)     pci_device_deassert_intx(pci_dev);
1284315a1350SMichael S. Tsirkin     do_pci_unregister_device(pci_dev);
128508cf3dc6SJagannathan Raman 
128608cf3dc6SJagannathan Raman     pci_dev->msi_trigger = NULL;
1287041b1c40SIgor Mammedov 
1288041b1c40SIgor Mammedov     /*
1289041b1c40SIgor Mammedov      * clean up acpi-index so it could reused by another device
1290041b1c40SIgor Mammedov      */
1291041b1c40SIgor Mammedov     if (pci_dev->acpi_index) {
1292041b1c40SIgor Mammedov         GSequence *used_indexes = pci_acpi_index_list();
1293041b1c40SIgor Mammedov 
1294041b1c40SIgor Mammedov         g_sequence_remove(g_sequence_lookup(used_indexes,
1295041b1c40SIgor Mammedov                           GINT_TO_POINTER(pci_dev->acpi_index),
1296041b1c40SIgor Mammedov                           g_cmp_uint32, NULL));
1297041b1c40SIgor Mammedov     }
1298315a1350SMichael S. Tsirkin }
1299315a1350SMichael S. Tsirkin 
1300315a1350SMichael S. Tsirkin void pci_register_bar(PCIDevice *pci_dev, int region_num,
1301315a1350SMichael S. Tsirkin                       uint8_t type, MemoryRegion *memory)
1302315a1350SMichael S. Tsirkin {
1303315a1350SMichael S. Tsirkin     PCIIORegion *r;
13045178ecd8SCao jin     uint32_t addr; /* offset in pci config space */
1305315a1350SMichael S. Tsirkin     uint64_t wmask;
1306315a1350SMichael S. Tsirkin     pcibus_t size = memory_region_size(memory);
13076a5b19caSBen Widawsky     uint8_t hdr_type;
1308315a1350SMichael S. Tsirkin 
13097c0fa8dfSKnut Omang     assert(!pci_is_vf(pci_dev)); /* VFs must use pcie_sriov_vf_register_bar */
1310315a1350SMichael S. Tsirkin     assert(region_num >= 0);
1311315a1350SMichael S. Tsirkin     assert(region_num < PCI_NUM_REGIONS);
13122c729dc8SBen Widawsky     assert(is_power_of_2(size));
1313315a1350SMichael S. Tsirkin 
13146a5b19caSBen Widawsky     /* A PCI bridge device (with Type 1 header) may only have at most 2 BARs */
13156a5b19caSBen Widawsky     hdr_type =
13166a5b19caSBen Widawsky         pci_dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
13176a5b19caSBen Widawsky     assert(hdr_type != PCI_HEADER_TYPE_BRIDGE || region_num < 2);
13186a5b19caSBen Widawsky 
1319315a1350SMichael S. Tsirkin     r = &pci_dev->io_regions[region_num];
1320315a1350SMichael S. Tsirkin     r->addr = PCI_BAR_UNMAPPED;
1321315a1350SMichael S. Tsirkin     r->size = size;
1322315a1350SMichael S. Tsirkin     r->type = type;
13235178ecd8SCao jin     r->memory = memory;
13245178ecd8SCao jin     r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1325fd56e061SDavid Gibson                         ? pci_get_bus(pci_dev)->address_space_io
1326fd56e061SDavid Gibson                         : pci_get_bus(pci_dev)->address_space_mem;
1327315a1350SMichael S. Tsirkin 
1328315a1350SMichael S. Tsirkin     wmask = ~(size - 1);
1329315a1350SMichael S. Tsirkin     if (region_num == PCI_ROM_SLOT) {
1330315a1350SMichael S. Tsirkin         /* ROM enable bit is writable */
1331315a1350SMichael S. Tsirkin         wmask |= PCI_ROM_ADDRESS_ENABLE;
1332315a1350SMichael S. Tsirkin     }
13335178ecd8SCao jin 
13345178ecd8SCao jin     addr = pci_bar(pci_dev, region_num);
1335315a1350SMichael S. Tsirkin     pci_set_long(pci_dev->config + addr, type);
13365178ecd8SCao jin 
1337315a1350SMichael S. Tsirkin     if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1338315a1350SMichael S. Tsirkin         r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1339315a1350SMichael S. Tsirkin         pci_set_quad(pci_dev->wmask + addr, wmask);
1340315a1350SMichael S. Tsirkin         pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1341315a1350SMichael S. Tsirkin     } else {
1342315a1350SMichael S. Tsirkin         pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1343315a1350SMichael S. Tsirkin         pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1344315a1350SMichael S. Tsirkin     }
1345315a1350SMichael S. Tsirkin }
1346315a1350SMichael S. Tsirkin 
1347e01fd687SAlex Williamson static void pci_update_vga(PCIDevice *pci_dev)
1348e01fd687SAlex Williamson {
1349e01fd687SAlex Williamson     uint16_t cmd;
1350e01fd687SAlex Williamson 
1351e01fd687SAlex Williamson     if (!pci_dev->has_vga) {
1352e01fd687SAlex Williamson         return;
1353e01fd687SAlex Williamson     }
1354e01fd687SAlex Williamson 
1355e01fd687SAlex Williamson     cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1356e01fd687SAlex Williamson 
1357e01fd687SAlex Williamson     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1358e01fd687SAlex Williamson                               cmd & PCI_COMMAND_MEMORY);
1359e01fd687SAlex Williamson     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1360e01fd687SAlex Williamson                               cmd & PCI_COMMAND_IO);
1361e01fd687SAlex Williamson     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1362e01fd687SAlex Williamson                               cmd & PCI_COMMAND_IO);
1363e01fd687SAlex Williamson }
1364e01fd687SAlex Williamson 
1365e01fd687SAlex Williamson void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1366e01fd687SAlex Williamson                       MemoryRegion *io_lo, MemoryRegion *io_hi)
1367e01fd687SAlex Williamson {
1368fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
1369fd56e061SDavid Gibson 
1370e01fd687SAlex Williamson     assert(!pci_dev->has_vga);
1371e01fd687SAlex Williamson 
1372e01fd687SAlex Williamson     assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1373e01fd687SAlex Williamson     pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1374fd56e061SDavid Gibson     memory_region_add_subregion_overlap(bus->address_space_mem,
1375e01fd687SAlex Williamson                                         QEMU_PCI_VGA_MEM_BASE, mem, 1);
1376e01fd687SAlex Williamson 
1377e01fd687SAlex Williamson     assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1378e01fd687SAlex Williamson     pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1379fd56e061SDavid Gibson     memory_region_add_subregion_overlap(bus->address_space_io,
1380e01fd687SAlex Williamson                                         QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1381e01fd687SAlex Williamson 
1382e01fd687SAlex Williamson     assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1383e01fd687SAlex Williamson     pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1384fd56e061SDavid Gibson     memory_region_add_subregion_overlap(bus->address_space_io,
1385e01fd687SAlex Williamson                                         QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1386e01fd687SAlex Williamson     pci_dev->has_vga = true;
1387e01fd687SAlex Williamson 
1388e01fd687SAlex Williamson     pci_update_vga(pci_dev);
1389e01fd687SAlex Williamson }
1390e01fd687SAlex Williamson 
1391e01fd687SAlex Williamson void pci_unregister_vga(PCIDevice *pci_dev)
1392e01fd687SAlex Williamson {
1393fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
1394fd56e061SDavid Gibson 
1395e01fd687SAlex Williamson     if (!pci_dev->has_vga) {
1396e01fd687SAlex Williamson         return;
1397e01fd687SAlex Williamson     }
1398e01fd687SAlex Williamson 
1399fd56e061SDavid Gibson     memory_region_del_subregion(bus->address_space_mem,
1400e01fd687SAlex Williamson                                 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1401fd56e061SDavid Gibson     memory_region_del_subregion(bus->address_space_io,
1402e01fd687SAlex Williamson                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1403fd56e061SDavid Gibson     memory_region_del_subregion(bus->address_space_io,
1404e01fd687SAlex Williamson                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1405e01fd687SAlex Williamson     pci_dev->has_vga = false;
1406e01fd687SAlex Williamson }
1407e01fd687SAlex Williamson 
1408315a1350SMichael S. Tsirkin pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1409315a1350SMichael S. Tsirkin {
1410315a1350SMichael S. Tsirkin     return pci_dev->io_regions[region_num].addr;
1411315a1350SMichael S. Tsirkin }
1412315a1350SMichael S. Tsirkin 
14137c0fa8dfSKnut Omang static pcibus_t pci_config_get_bar_addr(PCIDevice *d, int reg,
14147c0fa8dfSKnut Omang                                         uint8_t type, pcibus_t size)
14157c0fa8dfSKnut Omang {
14167c0fa8dfSKnut Omang     pcibus_t new_addr;
14177c0fa8dfSKnut Omang     if (!pci_is_vf(d)) {
14187c0fa8dfSKnut Omang         int bar = pci_bar(d, reg);
14197c0fa8dfSKnut Omang         if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
14207c0fa8dfSKnut Omang             new_addr = pci_get_quad(d->config + bar);
14217c0fa8dfSKnut Omang         } else {
14227c0fa8dfSKnut Omang             new_addr = pci_get_long(d->config + bar);
14237c0fa8dfSKnut Omang         }
14247c0fa8dfSKnut Omang     } else {
14257c0fa8dfSKnut Omang         PCIDevice *pf = d->exp.sriov_vf.pf;
14267c0fa8dfSKnut Omang         uint16_t sriov_cap = pf->exp.sriov_cap;
14277c0fa8dfSKnut Omang         int bar = sriov_cap + PCI_SRIOV_BAR + reg * 4;
14287c0fa8dfSKnut Omang         uint16_t vf_offset =
14297c0fa8dfSKnut Omang             pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_OFFSET);
14307c0fa8dfSKnut Omang         uint16_t vf_stride =
14317c0fa8dfSKnut Omang             pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_STRIDE);
14327c0fa8dfSKnut Omang         uint32_t vf_num = (d->devfn - (pf->devfn + vf_offset)) / vf_stride;
14337c0fa8dfSKnut Omang 
14347c0fa8dfSKnut Omang         if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
14357c0fa8dfSKnut Omang             new_addr = pci_get_quad(pf->config + bar);
14367c0fa8dfSKnut Omang         } else {
14377c0fa8dfSKnut Omang             new_addr = pci_get_long(pf->config + bar);
14387c0fa8dfSKnut Omang         }
14397c0fa8dfSKnut Omang         new_addr += vf_num * size;
14407c0fa8dfSKnut Omang     }
14417c0fa8dfSKnut Omang     /* The ROM slot has a specific enable bit, keep it intact */
14427c0fa8dfSKnut Omang     if (reg != PCI_ROM_SLOT) {
14437c0fa8dfSKnut Omang         new_addr &= ~(size - 1);
14447c0fa8dfSKnut Omang     }
14457c0fa8dfSKnut Omang     return new_addr;
14467c0fa8dfSKnut Omang }
14477c0fa8dfSKnut Omang 
14487c0fa8dfSKnut Omang pcibus_t pci_bar_address(PCIDevice *d,
1449315a1350SMichael S. Tsirkin                          int reg, uint8_t type, pcibus_t size)
1450315a1350SMichael S. Tsirkin {
1451315a1350SMichael S. Tsirkin     pcibus_t new_addr, last_addr;
1452315a1350SMichael S. Tsirkin     uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1453271233f2SPhilippe Mathieu-Daudé     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
1454e4024630SLaurent Vivier     bool allow_0_address = mc->pci_allow_0_address;
1455315a1350SMichael S. Tsirkin 
1456315a1350SMichael S. Tsirkin     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1457315a1350SMichael S. Tsirkin         if (!(cmd & PCI_COMMAND_IO)) {
1458315a1350SMichael S. Tsirkin             return PCI_BAR_UNMAPPED;
1459315a1350SMichael S. Tsirkin         }
14607c0fa8dfSKnut Omang         new_addr = pci_config_get_bar_addr(d, reg, type, size);
1461315a1350SMichael S. Tsirkin         last_addr = new_addr + size - 1;
14629f1a029aSHervé Poussineau         /* Check if 32 bit BAR wraps around explicitly.
14639f1a029aSHervé Poussineau          * TODO: make priorities correct and remove this work around.
14649f1a029aSHervé Poussineau          */
1465e4024630SLaurent Vivier         if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1466e4024630SLaurent Vivier             (!allow_0_address && new_addr == 0)) {
1467315a1350SMichael S. Tsirkin             return PCI_BAR_UNMAPPED;
1468315a1350SMichael S. Tsirkin         }
1469315a1350SMichael S. Tsirkin         return new_addr;
1470315a1350SMichael S. Tsirkin     }
1471315a1350SMichael S. Tsirkin 
1472315a1350SMichael S. Tsirkin     if (!(cmd & PCI_COMMAND_MEMORY)) {
1473315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1474315a1350SMichael S. Tsirkin     }
14757c0fa8dfSKnut Omang     new_addr = pci_config_get_bar_addr(d, reg, type, size);
1476315a1350SMichael S. Tsirkin     /* the ROM slot has a specific enable bit */
1477315a1350SMichael S. Tsirkin     if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1478315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1479315a1350SMichael S. Tsirkin     }
1480315a1350SMichael S. Tsirkin     new_addr &= ~(size - 1);
1481315a1350SMichael S. Tsirkin     last_addr = new_addr + size - 1;
1482315a1350SMichael S. Tsirkin     /* NOTE: we do not support wrapping */
1483315a1350SMichael S. Tsirkin     /* XXX: as we cannot support really dynamic
1484315a1350SMichael S. Tsirkin        mappings, we handle specific values as invalid
1485315a1350SMichael S. Tsirkin        mappings. */
1486e4024630SLaurent Vivier     if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1487e4024630SLaurent Vivier         (!allow_0_address && new_addr == 0)) {
1488315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1489315a1350SMichael S. Tsirkin     }
1490315a1350SMichael S. Tsirkin 
1491315a1350SMichael S. Tsirkin     /* Now pcibus_t is 64bit.
1492315a1350SMichael S. Tsirkin      * Check if 32 bit BAR wraps around explicitly.
1493315a1350SMichael S. Tsirkin      * Without this, PC ide doesn't work well.
1494315a1350SMichael S. Tsirkin      * TODO: remove this work around.
1495315a1350SMichael S. Tsirkin      */
1496315a1350SMichael S. Tsirkin     if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1497315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1498315a1350SMichael S. Tsirkin     }
1499315a1350SMichael S. Tsirkin 
1500315a1350SMichael S. Tsirkin     /*
1501315a1350SMichael S. Tsirkin      * OS is allowed to set BAR beyond its addressable
1502315a1350SMichael S. Tsirkin      * bits. For example, 32 bit OS can set 64bit bar
1503315a1350SMichael S. Tsirkin      * to >4G. Check it. TODO: we might need to support
1504315a1350SMichael S. Tsirkin      * it in the future for e.g. PAE.
1505315a1350SMichael S. Tsirkin      */
1506315a1350SMichael S. Tsirkin     if (last_addr >= HWADDR_MAX) {
1507315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1508315a1350SMichael S. Tsirkin     }
1509315a1350SMichael S. Tsirkin 
1510315a1350SMichael S. Tsirkin     return new_addr;
1511315a1350SMichael S. Tsirkin }
1512315a1350SMichael S. Tsirkin 
1513315a1350SMichael S. Tsirkin static void pci_update_mappings(PCIDevice *d)
1514315a1350SMichael S. Tsirkin {
1515315a1350SMichael S. Tsirkin     PCIIORegion *r;
1516315a1350SMichael S. Tsirkin     int i;
1517315a1350SMichael S. Tsirkin     pcibus_t new_addr;
1518315a1350SMichael S. Tsirkin 
1519315a1350SMichael S. Tsirkin     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1520315a1350SMichael S. Tsirkin         r = &d->io_regions[i];
1521315a1350SMichael S. Tsirkin 
1522315a1350SMichael S. Tsirkin         /* this region isn't registered */
1523315a1350SMichael S. Tsirkin         if (!r->size)
1524315a1350SMichael S. Tsirkin             continue;
1525315a1350SMichael S. Tsirkin 
1526315a1350SMichael S. Tsirkin         new_addr = pci_bar_address(d, i, r->type, r->size);
152723786d13SGerd Hoffmann         if (!d->has_power) {
152823786d13SGerd Hoffmann             new_addr = PCI_BAR_UNMAPPED;
152923786d13SGerd Hoffmann         }
1530315a1350SMichael S. Tsirkin 
1531315a1350SMichael S. Tsirkin         /* This bar isn't changed */
1532315a1350SMichael S. Tsirkin         if (new_addr == r->addr)
1533315a1350SMichael S. Tsirkin             continue;
1534315a1350SMichael S. Tsirkin 
1535315a1350SMichael S. Tsirkin         /* now do the real mapping */
1536315a1350SMichael S. Tsirkin         if (r->addr != PCI_BAR_UNMAPPED) {
1537deeb956cSLaurent Vivier             trace_pci_update_mappings_del(d->name, pci_dev_bus_num(d),
15387828d750SDon Koch                                           PCI_SLOT(d->devfn),
15390f288f85SLaszlo Ersek                                           PCI_FUNC(d->devfn),
15407828d750SDon Koch                                           i, r->addr, r->size);
1541315a1350SMichael S. Tsirkin             memory_region_del_subregion(r->address_space, r->memory);
1542315a1350SMichael S. Tsirkin         }
1543315a1350SMichael S. Tsirkin         r->addr = new_addr;
1544315a1350SMichael S. Tsirkin         if (r->addr != PCI_BAR_UNMAPPED) {
1545deeb956cSLaurent Vivier             trace_pci_update_mappings_add(d->name, pci_dev_bus_num(d),
15467828d750SDon Koch                                           PCI_SLOT(d->devfn),
15470f288f85SLaszlo Ersek                                           PCI_FUNC(d->devfn),
15487828d750SDon Koch                                           i, r->addr, r->size);
1549315a1350SMichael S. Tsirkin             memory_region_add_subregion_overlap(r->address_space,
1550315a1350SMichael S. Tsirkin                                                 r->addr, r->memory, 1);
1551315a1350SMichael S. Tsirkin         }
1552315a1350SMichael S. Tsirkin     }
1553e01fd687SAlex Williamson 
1554e01fd687SAlex Williamson     pci_update_vga(d);
1555315a1350SMichael S. Tsirkin }
1556315a1350SMichael S. Tsirkin 
1557315a1350SMichael S. Tsirkin static inline int pci_irq_disabled(PCIDevice *d)
1558315a1350SMichael S. Tsirkin {
1559315a1350SMichael S. Tsirkin     return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1560315a1350SMichael S. Tsirkin }
1561315a1350SMichael S. Tsirkin 
1562315a1350SMichael S. Tsirkin /* Called after interrupt disabled field update in config space,
1563315a1350SMichael S. Tsirkin  * assert/deassert interrupts if necessary.
1564315a1350SMichael S. Tsirkin  * Gets original interrupt disable bit value (before update). */
1565315a1350SMichael S. Tsirkin static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1566315a1350SMichael S. Tsirkin {
1567315a1350SMichael S. Tsirkin     int i, disabled = pci_irq_disabled(d);
1568315a1350SMichael S. Tsirkin     if (disabled == was_irq_disabled)
1569315a1350SMichael S. Tsirkin         return;
1570315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
1571315a1350SMichael S. Tsirkin         int state = pci_irq_state(d, i);
1572315a1350SMichael S. Tsirkin         pci_change_irq_level(d, i, disabled ? -state : state);
1573315a1350SMichael S. Tsirkin     }
1574315a1350SMichael S. Tsirkin }
1575315a1350SMichael S. Tsirkin 
1576315a1350SMichael S. Tsirkin uint32_t pci_default_read_config(PCIDevice *d,
1577315a1350SMichael S. Tsirkin                                  uint32_t address, int len)
1578315a1350SMichael S. Tsirkin {
1579315a1350SMichael S. Tsirkin     uint32_t val = 0;
1580315a1350SMichael S. Tsirkin 
1581f7d6a635SPrasad J Pandit     assert(address + len <= pci_config_size(d));
1582f7d6a635SPrasad J Pandit 
1583727b4866SAlex Williamson     if (pci_is_express_downstream_port(d) &&
1584727b4866SAlex Williamson         ranges_overlap(address, len, d->exp.exp_cap + PCI_EXP_LNKSTA, 2)) {
1585727b4866SAlex Williamson         pcie_sync_bridge_lnk(d);
1586727b4866SAlex Williamson     }
1587315a1350SMichael S. Tsirkin     memcpy(&val, d->config + address, len);
1588315a1350SMichael S. Tsirkin     return le32_to_cpu(val);
1589315a1350SMichael S. Tsirkin }
1590315a1350SMichael S. Tsirkin 
1591d7efb7e0SKnut Omang void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1592315a1350SMichael S. Tsirkin {
1593315a1350SMichael S. Tsirkin     int i, was_irq_disabled = pci_irq_disabled(d);
1594d7efb7e0SKnut Omang     uint32_t val = val_in;
1595315a1350SMichael S. Tsirkin 
1596f7d6a635SPrasad J Pandit     assert(addr + l <= pci_config_size(d));
1597f7d6a635SPrasad J Pandit 
1598315a1350SMichael S. Tsirkin     for (i = 0; i < l; val >>= 8, ++i) {
1599315a1350SMichael S. Tsirkin         uint8_t wmask = d->wmask[addr + i];
1600315a1350SMichael S. Tsirkin         uint8_t w1cmask = d->w1cmask[addr + i];
1601315a1350SMichael S. Tsirkin         assert(!(wmask & w1cmask));
1602315a1350SMichael S. Tsirkin         d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1603315a1350SMichael S. Tsirkin         d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1604315a1350SMichael S. Tsirkin     }
1605315a1350SMichael S. Tsirkin     if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1606315a1350SMichael S. Tsirkin         ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1607315a1350SMichael S. Tsirkin         ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1608315a1350SMichael S. Tsirkin         range_covers_byte(addr, l, PCI_COMMAND))
1609315a1350SMichael S. Tsirkin         pci_update_mappings(d);
1610315a1350SMichael S. Tsirkin 
16110f936247SGuoyi Tu     if (ranges_overlap(addr, l, PCI_COMMAND, 2)) {
1612315a1350SMichael S. Tsirkin         pci_update_irq_disabled(d, was_irq_disabled);
1613315a1350SMichael S. Tsirkin         memory_region_set_enabled(&d->bus_master_enable_region,
161423786d13SGerd Hoffmann                                   (pci_get_word(d->config + PCI_COMMAND)
161523786d13SGerd Hoffmann                                    & PCI_COMMAND_MASTER) && d->has_power);
1616315a1350SMichael S. Tsirkin     }
1617315a1350SMichael S. Tsirkin 
1618d7efb7e0SKnut Omang     msi_write_config(d, addr, val_in, l);
1619d7efb7e0SKnut Omang     msix_write_config(d, addr, val_in, l);
16207c0fa8dfSKnut Omang     pcie_sriov_config_write(d, addr, val_in, l);
1621315a1350SMichael S. Tsirkin }
1622315a1350SMichael S. Tsirkin 
1623315a1350SMichael S. Tsirkin /***********************************************************/
1624315a1350SMichael S. Tsirkin /* generic PCI irq support */
1625315a1350SMichael S. Tsirkin 
1626315a1350SMichael S. Tsirkin /* 0 <= irq_num <= 3. level must be 0 or 1 */
1627d98f08f5SMarcel Apfelbaum static void pci_irq_handler(void *opaque, int irq_num, int level)
1628315a1350SMichael S. Tsirkin {
1629315a1350SMichael S. Tsirkin     PCIDevice *pci_dev = opaque;
1630315a1350SMichael S. Tsirkin     int change;
1631315a1350SMichael S. Tsirkin 
16328ddf5432SIsaku Yamahata     assert(0 <= irq_num && irq_num < PCI_NUM_PINS);
16338ddf5432SIsaku Yamahata     assert(level == 0 || level == 1);
1634315a1350SMichael S. Tsirkin     change = level - pci_irq_state(pci_dev, irq_num);
1635315a1350SMichael S. Tsirkin     if (!change)
1636315a1350SMichael S. Tsirkin         return;
1637315a1350SMichael S. Tsirkin 
1638315a1350SMichael S. Tsirkin     pci_set_irq_state(pci_dev, irq_num, level);
1639315a1350SMichael S. Tsirkin     pci_update_irq_status(pci_dev);
1640315a1350SMichael S. Tsirkin     if (pci_irq_disabled(pci_dev))
1641315a1350SMichael S. Tsirkin         return;
1642315a1350SMichael S. Tsirkin     pci_change_irq_level(pci_dev, irq_num, change);
1643315a1350SMichael S. Tsirkin }
1644315a1350SMichael S. Tsirkin 
1645d98f08f5SMarcel Apfelbaum qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1646d98f08f5SMarcel Apfelbaum {
1647d98f08f5SMarcel Apfelbaum     int intx = pci_intx(pci_dev);
16488ddf5432SIsaku Yamahata     assert(0 <= intx && intx < PCI_NUM_PINS);
1649d98f08f5SMarcel Apfelbaum 
1650d98f08f5SMarcel Apfelbaum     return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1651d98f08f5SMarcel Apfelbaum }
1652d98f08f5SMarcel Apfelbaum 
1653d98f08f5SMarcel Apfelbaum void pci_set_irq(PCIDevice *pci_dev, int level)
1654d98f08f5SMarcel Apfelbaum {
1655d98f08f5SMarcel Apfelbaum     int intx = pci_intx(pci_dev);
1656d98f08f5SMarcel Apfelbaum     pci_irq_handler(pci_dev, intx, level);
1657d98f08f5SMarcel Apfelbaum }
1658d98f08f5SMarcel Apfelbaum 
1659315a1350SMichael S. Tsirkin /* Special hooks used by device assignment */
1660315a1350SMichael S. Tsirkin void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1661315a1350SMichael S. Tsirkin {
16620889464aSAlex Williamson     assert(pci_bus_is_root(bus));
1663315a1350SMichael S. Tsirkin     bus->route_intx_to_irq = route_intx_to_irq;
1664315a1350SMichael S. Tsirkin }
1665315a1350SMichael S. Tsirkin 
1666315a1350SMichael S. Tsirkin PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1667315a1350SMichael S. Tsirkin {
1668315a1350SMichael S. Tsirkin     PCIBus *bus;
1669315a1350SMichael S. Tsirkin 
1670315a1350SMichael S. Tsirkin     do {
167128566eabSPhilippe Mathieu-Daudé         int dev_irq = pin;
1672fd56e061SDavid Gibson         bus = pci_get_bus(dev);
1673315a1350SMichael S. Tsirkin         pin = bus->map_irq(dev, pin);
167428566eabSPhilippe Mathieu-Daudé         trace_pci_route_irq(dev_irq, DEVICE(dev)->canonical_path, pin,
167528566eabSPhilippe Mathieu-Daudé                             pci_bus_is_root(bus) ? "root-complex"
167628566eabSPhilippe Mathieu-Daudé                                     : DEVICE(bus->parent_dev)->canonical_path);
1677315a1350SMichael S. Tsirkin         dev = bus->parent_dev;
1678315a1350SMichael S. Tsirkin     } while (dev);
1679315a1350SMichael S. Tsirkin 
1680315a1350SMichael S. Tsirkin     if (!bus->route_intx_to_irq) {
1681312fd5f2SMarkus Armbruster         error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1682315a1350SMichael S. Tsirkin                      object_get_typename(OBJECT(bus->qbus.parent)));
1683315a1350SMichael S. Tsirkin         return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1684315a1350SMichael S. Tsirkin     }
1685315a1350SMichael S. Tsirkin 
1686315a1350SMichael S. Tsirkin     return bus->route_intx_to_irq(bus->irq_opaque, pin);
1687315a1350SMichael S. Tsirkin }
1688315a1350SMichael S. Tsirkin 
1689315a1350SMichael S. Tsirkin bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1690315a1350SMichael S. Tsirkin {
1691315a1350SMichael S. Tsirkin     return old->mode != new->mode || old->irq != new->irq;
1692315a1350SMichael S. Tsirkin }
1693315a1350SMichael S. Tsirkin 
1694315a1350SMichael S. Tsirkin void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1695315a1350SMichael S. Tsirkin {
1696315a1350SMichael S. Tsirkin     PCIDevice *dev;
1697315a1350SMichael S. Tsirkin     PCIBus *sec;
1698315a1350SMichael S. Tsirkin     int i;
1699315a1350SMichael S. Tsirkin 
1700315a1350SMichael S. Tsirkin     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1701315a1350SMichael S. Tsirkin         dev = bus->devices[i];
1702315a1350SMichael S. Tsirkin         if (dev && dev->intx_routing_notifier) {
1703315a1350SMichael S. Tsirkin             dev->intx_routing_notifier(dev);
1704315a1350SMichael S. Tsirkin         }
1705e5368f0dSAlex Williamson     }
1706e5368f0dSAlex Williamson 
1707315a1350SMichael S. Tsirkin     QLIST_FOREACH(sec, &bus->child, sibling) {
1708315a1350SMichael S. Tsirkin         pci_bus_fire_intx_routing_notifier(sec);
1709315a1350SMichael S. Tsirkin     }
1710315a1350SMichael S. Tsirkin }
1711315a1350SMichael S. Tsirkin 
1712315a1350SMichael S. Tsirkin void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1713315a1350SMichael S. Tsirkin                                           PCIINTxRoutingNotifier notifier)
1714315a1350SMichael S. Tsirkin {
1715315a1350SMichael S. Tsirkin     dev->intx_routing_notifier = notifier;
1716315a1350SMichael S. Tsirkin }
1717315a1350SMichael S. Tsirkin 
1718315a1350SMichael S. Tsirkin /*
1719315a1350SMichael S. Tsirkin  * PCI-to-PCI bridge specification
1720315a1350SMichael S. Tsirkin  * 9.1: Interrupt routing. Table 9-1
1721315a1350SMichael S. Tsirkin  *
1722315a1350SMichael S. Tsirkin  * the PCI Express Base Specification, Revision 2.1
17239d724e0bSPhilippe Mathieu-Daudé  * 2.2.8.1: INTx interrupt signaling - Rules
1724315a1350SMichael S. Tsirkin  *          the Implementation Note
1725315a1350SMichael S. Tsirkin  *          Table 2-20
1726315a1350SMichael S. Tsirkin  */
1727315a1350SMichael S. Tsirkin /*
1728315a1350SMichael S. Tsirkin  * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1729315a1350SMichael S. Tsirkin  * 0-origin unlike PCI interrupt pin register.
1730315a1350SMichael S. Tsirkin  */
1731315a1350SMichael S. Tsirkin int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1732315a1350SMichael S. Tsirkin {
1733e8ec4adfSGreg Kurz     return pci_swizzle(PCI_SLOT(pci_dev->devfn), pin);
1734315a1350SMichael S. Tsirkin }
1735315a1350SMichael S. Tsirkin 
1736315a1350SMichael S. Tsirkin /***********************************************************/
1737315a1350SMichael S. Tsirkin /* monitor info on PCI */
1738315a1350SMichael S. Tsirkin 
1739315a1350SMichael S. Tsirkin static const pci_class_desc pci_class_descriptions[] =
1740315a1350SMichael S. Tsirkin {
1741315a1350SMichael S. Tsirkin     { 0x0001, "VGA controller", "display"},
1742315a1350SMichael S. Tsirkin     { 0x0100, "SCSI controller", "scsi"},
1743315a1350SMichael S. Tsirkin     { 0x0101, "IDE controller", "ide"},
1744315a1350SMichael S. Tsirkin     { 0x0102, "Floppy controller", "fdc"},
1745315a1350SMichael S. Tsirkin     { 0x0103, "IPI controller", "ipi"},
1746315a1350SMichael S. Tsirkin     { 0x0104, "RAID controller", "raid"},
1747315a1350SMichael S. Tsirkin     { 0x0106, "SATA controller"},
1748315a1350SMichael S. Tsirkin     { 0x0107, "SAS controller"},
1749315a1350SMichael S. Tsirkin     { 0x0180, "Storage controller"},
1750315a1350SMichael S. Tsirkin     { 0x0200, "Ethernet controller", "ethernet"},
1751315a1350SMichael S. Tsirkin     { 0x0201, "Token Ring controller", "token-ring"},
1752315a1350SMichael S. Tsirkin     { 0x0202, "FDDI controller", "fddi"},
1753315a1350SMichael S. Tsirkin     { 0x0203, "ATM controller", "atm"},
1754315a1350SMichael S. Tsirkin     { 0x0280, "Network controller"},
1755315a1350SMichael S. Tsirkin     { 0x0300, "VGA controller", "display", 0x00ff},
1756315a1350SMichael S. Tsirkin     { 0x0301, "XGA controller"},
1757315a1350SMichael S. Tsirkin     { 0x0302, "3D controller"},
1758315a1350SMichael S. Tsirkin     { 0x0380, "Display controller"},
1759315a1350SMichael S. Tsirkin     { 0x0400, "Video controller", "video"},
1760315a1350SMichael S. Tsirkin     { 0x0401, "Audio controller", "sound"},
1761315a1350SMichael S. Tsirkin     { 0x0402, "Phone"},
1762315a1350SMichael S. Tsirkin     { 0x0403, "Audio controller", "sound"},
1763315a1350SMichael S. Tsirkin     { 0x0480, "Multimedia controller"},
1764315a1350SMichael S. Tsirkin     { 0x0500, "RAM controller", "memory"},
1765315a1350SMichael S. Tsirkin     { 0x0501, "Flash controller", "flash"},
1766315a1350SMichael S. Tsirkin     { 0x0580, "Memory controller"},
1767315a1350SMichael S. Tsirkin     { 0x0600, "Host bridge", "host"},
1768315a1350SMichael S. Tsirkin     { 0x0601, "ISA bridge", "isa"},
1769315a1350SMichael S. Tsirkin     { 0x0602, "EISA bridge", "eisa"},
1770315a1350SMichael S. Tsirkin     { 0x0603, "MC bridge", "mca"},
17714c41425dSGerd Hoffmann     { 0x0604, "PCI bridge", "pci-bridge"},
1772315a1350SMichael S. Tsirkin     { 0x0605, "PCMCIA bridge", "pcmcia"},
1773315a1350SMichael S. Tsirkin     { 0x0606, "NUBUS bridge", "nubus"},
1774315a1350SMichael S. Tsirkin     { 0x0607, "CARDBUS bridge", "cardbus"},
1775315a1350SMichael S. Tsirkin     { 0x0608, "RACEWAY bridge"},
1776315a1350SMichael S. Tsirkin     { 0x0680, "Bridge"},
1777315a1350SMichael S. Tsirkin     { 0x0700, "Serial port", "serial"},
1778315a1350SMichael S. Tsirkin     { 0x0701, "Parallel port", "parallel"},
1779315a1350SMichael S. Tsirkin     { 0x0800, "Interrupt controller", "interrupt-controller"},
1780315a1350SMichael S. Tsirkin     { 0x0801, "DMA controller", "dma-controller"},
1781315a1350SMichael S. Tsirkin     { 0x0802, "Timer", "timer"},
1782315a1350SMichael S. Tsirkin     { 0x0803, "RTC", "rtc"},
1783315a1350SMichael S. Tsirkin     { 0x0900, "Keyboard", "keyboard"},
1784315a1350SMichael S. Tsirkin     { 0x0901, "Pen", "pen"},
1785315a1350SMichael S. Tsirkin     { 0x0902, "Mouse", "mouse"},
1786315a1350SMichael S. Tsirkin     { 0x0A00, "Dock station", "dock", 0x00ff},
1787315a1350SMichael S. Tsirkin     { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1788d1e9e646SRebecca Cran     { 0x0c00, "Firewire controller", "firewire"},
1789315a1350SMichael S. Tsirkin     { 0x0c01, "Access bus controller", "access-bus"},
1790315a1350SMichael S. Tsirkin     { 0x0c02, "SSA controller", "ssa"},
1791315a1350SMichael S. Tsirkin     { 0x0c03, "USB controller", "usb"},
1792315a1350SMichael S. Tsirkin     { 0x0c04, "Fibre channel controller", "fibre-channel"},
1793315a1350SMichael S. Tsirkin     { 0x0c05, "SMBus"},
1794315a1350SMichael S. Tsirkin     { 0, NULL}
1795315a1350SMichael S. Tsirkin };
1796315a1350SMichael S. Tsirkin 
17972914fc61SPeter Xu void pci_for_each_device_under_bus_reverse(PCIBus *bus,
1798b3dcf94fSPeter Xu                                            pci_bus_dev_fn fn,
1799a8eeafdaSGreg Kurz                                            void *opaque)
1800a8eeafdaSGreg Kurz {
1801a8eeafdaSGreg Kurz     PCIDevice *d;
1802a8eeafdaSGreg Kurz     int devfn;
1803a8eeafdaSGreg Kurz 
1804a8eeafdaSGreg Kurz     for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1805a8eeafdaSGreg Kurz         d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
1806a8eeafdaSGreg Kurz         if (d) {
1807a8eeafdaSGreg Kurz             fn(bus, d, opaque);
1808a8eeafdaSGreg Kurz         }
1809a8eeafdaSGreg Kurz     }
1810a8eeafdaSGreg Kurz }
1811a8eeafdaSGreg Kurz 
1812a8eeafdaSGreg Kurz void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
1813b3dcf94fSPeter Xu                                  pci_bus_dev_fn fn, void *opaque)
1814a8eeafdaSGreg Kurz {
1815a8eeafdaSGreg Kurz     bus = pci_find_bus_nr(bus, bus_num);
1816a8eeafdaSGreg Kurz 
1817a8eeafdaSGreg Kurz     if (bus) {
1818a8eeafdaSGreg Kurz         pci_for_each_device_under_bus_reverse(bus, fn, opaque);
1819a8eeafdaSGreg Kurz     }
1820a8eeafdaSGreg Kurz }
1821a8eeafdaSGreg Kurz 
18222914fc61SPeter Xu void pci_for_each_device_under_bus(PCIBus *bus,
1823b3dcf94fSPeter Xu                                    pci_bus_dev_fn fn, void *opaque)
1824315a1350SMichael S. Tsirkin {
1825315a1350SMichael S. Tsirkin     PCIDevice *d;
1826315a1350SMichael S. Tsirkin     int devfn;
1827315a1350SMichael S. Tsirkin 
1828315a1350SMichael S. Tsirkin     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1829315a1350SMichael S. Tsirkin         d = bus->devices[devfn];
1830315a1350SMichael S. Tsirkin         if (d) {
1831315a1350SMichael S. Tsirkin             fn(bus, d, opaque);
1832315a1350SMichael S. Tsirkin         }
1833315a1350SMichael S. Tsirkin     }
1834315a1350SMichael S. Tsirkin }
1835315a1350SMichael S. Tsirkin 
1836315a1350SMichael S. Tsirkin void pci_for_each_device(PCIBus *bus, int bus_num,
1837b3dcf94fSPeter Xu                          pci_bus_dev_fn fn, void *opaque)
1838315a1350SMichael S. Tsirkin {
1839315a1350SMichael S. Tsirkin     bus = pci_find_bus_nr(bus, bus_num);
1840315a1350SMichael S. Tsirkin 
1841315a1350SMichael S. Tsirkin     if (bus) {
1842315a1350SMichael S. Tsirkin         pci_for_each_device_under_bus(bus, fn, opaque);
1843315a1350SMichael S. Tsirkin     }
1844315a1350SMichael S. Tsirkin }
1845315a1350SMichael S. Tsirkin 
1846987b73b3SMarkus Armbruster const pci_class_desc *get_class_desc(int class)
1847315a1350SMichael S. Tsirkin {
1848315a1350SMichael S. Tsirkin     const pci_class_desc *desc;
1849315a1350SMichael S. Tsirkin 
1850315a1350SMichael S. Tsirkin     desc = pci_class_descriptions;
1851315a1350SMichael S. Tsirkin     while (desc->desc && class != desc->class) {
1852315a1350SMichael S. Tsirkin         desc++;
1853315a1350SMichael S. Tsirkin     }
1854315a1350SMichael S. Tsirkin 
1855315a1350SMichael S. Tsirkin     return desc;
1856315a1350SMichael S. Tsirkin }
1857315a1350SMichael S. Tsirkin 
1858315a1350SMichael S. Tsirkin /* Initialize a PCI NIC.  */
185951f7cb97SThomas Huth PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
186029b358f9SDavid Gibson                                const char *default_model,
186151f7cb97SThomas Huth                                const char *default_devaddr)
1862315a1350SMichael S. Tsirkin {
1863315a1350SMichael S. Tsirkin     const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
186452310c3fSPaolo Bonzini     GPtrArray *pci_nic_models;
1865315a1350SMichael S. Tsirkin     PCIBus *bus;
1866315a1350SMichael S. Tsirkin     PCIDevice *pci_dev;
1867315a1350SMichael S. Tsirkin     DeviceState *dev;
186851f7cb97SThomas Huth     int devfn;
1869315a1350SMichael S. Tsirkin     int i;
18702ad778b8SDavid Gibson     int dom, busnr;
18712ad778b8SDavid Gibson     unsigned slot;
1872315a1350SMichael S. Tsirkin 
187352310c3fSPaolo Bonzini     if (nd->model && !strcmp(nd->model, "virtio")) {
187452310c3fSPaolo Bonzini         g_free(nd->model);
187552310c3fSPaolo Bonzini         nd->model = g_strdup("virtio-net-pci");
187652310c3fSPaolo Bonzini     }
187752310c3fSPaolo Bonzini 
1878c6941b3bSThomas Huth     pci_nic_models = qemu_get_nic_models(TYPE_PCI_DEVICE);
187952310c3fSPaolo Bonzini 
188052310c3fSPaolo Bonzini     if (qemu_show_nic_models(nd->model, (const char **)pci_nic_models->pdata)) {
188151f7cb97SThomas Huth         exit(0);
188251f7cb97SThomas Huth     }
188351f7cb97SThomas Huth 
188452310c3fSPaolo Bonzini     i = qemu_find_nic_model(nd, (const char **)pci_nic_models->pdata,
188552310c3fSPaolo Bonzini                             default_model);
188651f7cb97SThomas Huth     if (i < 0) {
188751f7cb97SThomas Huth         exit(1);
188851f7cb97SThomas Huth     }
1889315a1350SMichael S. Tsirkin 
18902ad778b8SDavid Gibson     if (!rootbus) {
18912ad778b8SDavid Gibson         error_report("No primary PCI bus");
18922ad778b8SDavid Gibson         exit(1);
18932ad778b8SDavid Gibson     }
18942ad778b8SDavid Gibson 
18952ad778b8SDavid Gibson     assert(!rootbus->parent_dev);
18962ad778b8SDavid Gibson 
18972ad778b8SDavid Gibson     if (!devaddr) {
18982ad778b8SDavid Gibson         devfn = -1;
18992ad778b8SDavid Gibson         busnr = 0;
19002ad778b8SDavid Gibson     } else {
19012ad778b8SDavid Gibson         if (pci_parse_devaddr(devaddr, &dom, &busnr, &slot, NULL) < 0) {
19022ad778b8SDavid Gibson             error_report("Invalid PCI device address %s for device %s",
19032ad778b8SDavid Gibson                          devaddr, nd->model);
19042ad778b8SDavid Gibson             exit(1);
19052ad778b8SDavid Gibson         }
19062ad778b8SDavid Gibson 
19072ad778b8SDavid Gibson         if (dom != 0) {
19082ad778b8SDavid Gibson             error_report("No support for non-zero PCI domains");
19092ad778b8SDavid Gibson             exit(1);
19102ad778b8SDavid Gibson         }
19112ad778b8SDavid Gibson 
19122ad778b8SDavid Gibson         devfn = PCI_DEVFN(slot, 0);
19132ad778b8SDavid Gibson     }
19142ad778b8SDavid Gibson 
19152ad778b8SDavid Gibson     bus = pci_find_bus_nr(rootbus, busnr);
1916315a1350SMichael S. Tsirkin     if (!bus) {
1917315a1350SMichael S. Tsirkin         error_report("Invalid PCI device address %s for device %s",
191852310c3fSPaolo Bonzini                      devaddr, nd->model);
191951f7cb97SThomas Huth         exit(1);
1920315a1350SMichael S. Tsirkin     }
1921315a1350SMichael S. Tsirkin 
19229307d06dSMarkus Armbruster     pci_dev = pci_new(devfn, nd->model);
1923315a1350SMichael S. Tsirkin     dev = &pci_dev->qdev;
1924315a1350SMichael S. Tsirkin     qdev_set_nic_properties(dev, nd);
19259307d06dSMarkus Armbruster     pci_realize_and_unref(pci_dev, bus, &error_fatal);
192652310c3fSPaolo Bonzini     g_ptr_array_free(pci_nic_models, true);
192751f7cb97SThomas Huth     return pci_dev;
1928315a1350SMichael S. Tsirkin }
1929315a1350SMichael S. Tsirkin 
1930315a1350SMichael S. Tsirkin PCIDevice *pci_vga_init(PCIBus *bus)
1931315a1350SMichael S. Tsirkin {
1932f9bcb2d6SGautam Agrawal     vga_interface_created = true;
1933315a1350SMichael S. Tsirkin     switch (vga_interface_type) {
1934315a1350SMichael S. Tsirkin     case VGA_CIRRUS:
1935315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "cirrus-vga");
1936315a1350SMichael S. Tsirkin     case VGA_QXL:
1937315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "qxl-vga");
1938315a1350SMichael S. Tsirkin     case VGA_STD:
1939315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "VGA");
1940315a1350SMichael S. Tsirkin     case VGA_VMWARE:
1941315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "vmware-svga");
1942a94f0c5cSGerd Hoffmann     case VGA_VIRTIO:
1943a94f0c5cSGerd Hoffmann         return pci_create_simple(bus, -1, "virtio-vga");
1944315a1350SMichael S. Tsirkin     case VGA_NONE:
1945315a1350SMichael S. Tsirkin     default: /* Other non-PCI types. Checking for unsupported types is already
1946315a1350SMichael S. Tsirkin                 done in vl.c. */
1947315a1350SMichael S. Tsirkin         return NULL;
1948315a1350SMichael S. Tsirkin     }
1949315a1350SMichael S. Tsirkin }
1950315a1350SMichael S. Tsirkin 
1951315a1350SMichael S. Tsirkin /* Whether a given bus number is in range of the secondary
1952315a1350SMichael S. Tsirkin  * bus of the given bridge device. */
1953315a1350SMichael S. Tsirkin static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1954315a1350SMichael S. Tsirkin {
1955315a1350SMichael S. Tsirkin     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1956315a1350SMichael S. Tsirkin              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
195709e5b819SMarcel Apfelbaum         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1958315a1350SMichael S. Tsirkin         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1959315a1350SMichael S. Tsirkin }
1960315a1350SMichael S. Tsirkin 
196109e5b819SMarcel Apfelbaum /* Whether a given bus number is in a range of a root bus */
196209e5b819SMarcel Apfelbaum static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
196309e5b819SMarcel Apfelbaum {
196409e5b819SMarcel Apfelbaum     int i;
196509e5b819SMarcel Apfelbaum 
196609e5b819SMarcel Apfelbaum     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
196709e5b819SMarcel Apfelbaum         PCIDevice *dev = bus->devices[i];
196809e5b819SMarcel Apfelbaum 
1969ad494274SIgor Mammedov         if (dev && IS_PCI_BRIDGE(dev)) {
197009e5b819SMarcel Apfelbaum             if (pci_secondary_bus_in_range(dev, bus_num)) {
197109e5b819SMarcel Apfelbaum                 return true;
197209e5b819SMarcel Apfelbaum             }
197309e5b819SMarcel Apfelbaum         }
197409e5b819SMarcel Apfelbaum     }
197509e5b819SMarcel Apfelbaum 
197609e5b819SMarcel Apfelbaum     return false;
197709e5b819SMarcel Apfelbaum }
197809e5b819SMarcel Apfelbaum 
1979987b73b3SMarkus Armbruster PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1980315a1350SMichael S. Tsirkin {
1981315a1350SMichael S. Tsirkin     PCIBus *sec;
1982315a1350SMichael S. Tsirkin 
1983315a1350SMichael S. Tsirkin     if (!bus) {
1984315a1350SMichael S. Tsirkin         return NULL;
1985315a1350SMichael S. Tsirkin     }
1986315a1350SMichael S. Tsirkin 
1987315a1350SMichael S. Tsirkin     if (pci_bus_num(bus) == bus_num) {
1988315a1350SMichael S. Tsirkin         return bus;
1989315a1350SMichael S. Tsirkin     }
1990315a1350SMichael S. Tsirkin 
1991315a1350SMichael S. Tsirkin     /* Consider all bus numbers in range for the host pci bridge. */
19920889464aSAlex Williamson     if (!pci_bus_is_root(bus) &&
1993315a1350SMichael S. Tsirkin         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1994315a1350SMichael S. Tsirkin         return NULL;
1995315a1350SMichael S. Tsirkin     }
1996315a1350SMichael S. Tsirkin 
1997315a1350SMichael S. Tsirkin     /* try child bus */
1998315a1350SMichael S. Tsirkin     for (; bus; bus = sec) {
1999315a1350SMichael S. Tsirkin         QLIST_FOREACH(sec, &bus->child, sibling) {
200009e5b819SMarcel Apfelbaum             if (pci_bus_num(sec) == bus_num) {
2001315a1350SMichael S. Tsirkin                 return sec;
2002315a1350SMichael S. Tsirkin             }
200309e5b819SMarcel Apfelbaum             /* PXB buses assumed to be children of bus 0 */
200409e5b819SMarcel Apfelbaum             if (pci_bus_is_root(sec)) {
200509e5b819SMarcel Apfelbaum                 if (pci_root_bus_in_range(sec, bus_num)) {
200609e5b819SMarcel Apfelbaum                     break;
200709e5b819SMarcel Apfelbaum                 }
200809e5b819SMarcel Apfelbaum             } else {
2009315a1350SMichael S. Tsirkin                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
2010315a1350SMichael S. Tsirkin                     break;
2011315a1350SMichael S. Tsirkin                 }
2012315a1350SMichael S. Tsirkin             }
2013315a1350SMichael S. Tsirkin         }
201409e5b819SMarcel Apfelbaum     }
2015315a1350SMichael S. Tsirkin 
2016315a1350SMichael S. Tsirkin     return NULL;
2017315a1350SMichael S. Tsirkin }
2018315a1350SMichael S. Tsirkin 
2019b3dcf94fSPeter Xu void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
2020b3dcf94fSPeter Xu                                   pci_bus_fn end, void *parent_state)
2021eb0acfddSMichael S. Tsirkin {
2022eb0acfddSMichael S. Tsirkin     PCIBus *sec;
2023eb0acfddSMichael S. Tsirkin     void *state;
2024eb0acfddSMichael S. Tsirkin 
2025eb0acfddSMichael S. Tsirkin     if (!bus) {
2026eb0acfddSMichael S. Tsirkin         return;
2027eb0acfddSMichael S. Tsirkin     }
2028eb0acfddSMichael S. Tsirkin 
2029eb0acfddSMichael S. Tsirkin     if (begin) {
2030eb0acfddSMichael S. Tsirkin         state = begin(bus, parent_state);
2031eb0acfddSMichael S. Tsirkin     } else {
2032eb0acfddSMichael S. Tsirkin         state = parent_state;
2033eb0acfddSMichael S. Tsirkin     }
2034eb0acfddSMichael S. Tsirkin 
2035eb0acfddSMichael S. Tsirkin     QLIST_FOREACH(sec, &bus->child, sibling) {
2036eb0acfddSMichael S. Tsirkin         pci_for_each_bus_depth_first(sec, begin, end, state);
2037eb0acfddSMichael S. Tsirkin     }
2038eb0acfddSMichael S. Tsirkin 
2039eb0acfddSMichael S. Tsirkin     if (end) {
2040eb0acfddSMichael S. Tsirkin         end(bus, state);
2041eb0acfddSMichael S. Tsirkin     }
2042eb0acfddSMichael S. Tsirkin }
2043eb0acfddSMichael S. Tsirkin 
2044eb0acfddSMichael S. Tsirkin 
2045315a1350SMichael S. Tsirkin PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
2046315a1350SMichael S. Tsirkin {
2047315a1350SMichael S. Tsirkin     bus = pci_find_bus_nr(bus, bus_num);
2048315a1350SMichael S. Tsirkin 
2049315a1350SMichael S. Tsirkin     if (!bus)
2050315a1350SMichael S. Tsirkin         return NULL;
2051315a1350SMichael S. Tsirkin 
2052315a1350SMichael S. Tsirkin     return bus->devices[devfn];
2053315a1350SMichael S. Tsirkin }
2054315a1350SMichael S. Tsirkin 
2055041b1c40SIgor Mammedov #define ONBOARD_INDEX_MAX (16 * 1024 - 1)
2056041b1c40SIgor Mammedov 
2057133e9b22SMarkus Armbruster static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2058315a1350SMichael S. Tsirkin {
2059315a1350SMichael S. Tsirkin     PCIDevice *pci_dev = (PCIDevice *)qdev;
2060315a1350SMichael S. Tsirkin     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2061d61a363dSYoni Bettan     ObjectClass *klass = OBJECT_CLASS(pc);
2062133e9b22SMarkus Armbruster     Error *local_err = NULL;
2063315a1350SMichael S. Tsirkin     bool is_default_rom;
20644f5b6a05SJens Freimann     uint16_t class_id;
2065315a1350SMichael S. Tsirkin 
2066041b1c40SIgor Mammedov     /*
2067041b1c40SIgor Mammedov      * capped by systemd (see: udev-builtin-net_id.c)
2068041b1c40SIgor Mammedov      * as it's the only known user honor it to avoid users
2069041b1c40SIgor Mammedov      * misconfigure QEMU and then wonder why acpi-index doesn't work
2070041b1c40SIgor Mammedov      */
2071041b1c40SIgor Mammedov     if (pci_dev->acpi_index > ONBOARD_INDEX_MAX) {
2072041b1c40SIgor Mammedov         error_setg(errp, "acpi-index should be less or equal to %u",
2073041b1c40SIgor Mammedov                    ONBOARD_INDEX_MAX);
2074041b1c40SIgor Mammedov         return;
2075041b1c40SIgor Mammedov     }
2076041b1c40SIgor Mammedov 
2077041b1c40SIgor Mammedov     /*
2078041b1c40SIgor Mammedov      * make sure that acpi-index is unique across all present PCI devices
2079041b1c40SIgor Mammedov      */
2080041b1c40SIgor Mammedov     if (pci_dev->acpi_index) {
2081041b1c40SIgor Mammedov         GSequence *used_indexes = pci_acpi_index_list();
2082041b1c40SIgor Mammedov 
2083041b1c40SIgor Mammedov         if (g_sequence_lookup(used_indexes,
2084041b1c40SIgor Mammedov                               GINT_TO_POINTER(pci_dev->acpi_index),
2085041b1c40SIgor Mammedov                               g_cmp_uint32, NULL)) {
2086041b1c40SIgor Mammedov             error_setg(errp, "a PCI device with acpi-index = %" PRIu32
2087041b1c40SIgor Mammedov                        " already exist", pci_dev->acpi_index);
2088041b1c40SIgor Mammedov             return;
2089041b1c40SIgor Mammedov         }
2090041b1c40SIgor Mammedov         g_sequence_insert_sorted(used_indexes,
2091041b1c40SIgor Mammedov                                  GINT_TO_POINTER(pci_dev->acpi_index),
2092041b1c40SIgor Mammedov                                  g_cmp_uint32, NULL);
2093041b1c40SIgor Mammedov     }
2094041b1c40SIgor Mammedov 
209508b1df8fSPaolo Bonzini     if (pci_dev->romsize != -1 && !is_power_of_2(pci_dev->romsize)) {
209608b1df8fSPaolo Bonzini         error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
209708b1df8fSPaolo Bonzini         return;
209808b1df8fSPaolo Bonzini     }
209908b1df8fSPaolo Bonzini 
2100d61a363dSYoni Bettan     /* initialize cap_present for pci_is_express() and pci_config_size(),
2101d61a363dSYoni Bettan      * Note that hybrid PCIs are not set automatically and need to manage
2102d61a363dSYoni Bettan      * QEMU_PCI_CAP_EXPRESS manually */
2103d61a363dSYoni Bettan     if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2104d61a363dSYoni Bettan        !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2105315a1350SMichael S. Tsirkin         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2106315a1350SMichael S. Tsirkin     }
2107315a1350SMichael S. Tsirkin 
2108cf04aba2SBen Widawsky     if (object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE)) {
2109cf04aba2SBen Widawsky         pci_dev->cap_present |= QEMU_PCIE_CAP_CXL;
2110cf04aba2SBen Widawsky     }
2111cf04aba2SBen Widawsky 
2112fd56e061SDavid Gibson     pci_dev = do_pci_register_device(pci_dev,
2113315a1350SMichael S. Tsirkin                                      object_get_typename(OBJECT(qdev)),
2114133e9b22SMarkus Armbruster                                      pci_dev->devfn, errp);
2115315a1350SMichael S. Tsirkin     if (pci_dev == NULL)
2116133e9b22SMarkus Armbruster         return;
21172897ae02SIgor Mammedov 
21187ee6c1e1SMarkus Armbruster     if (pc->realize) {
21197ee6c1e1SMarkus Armbruster         pc->realize(pci_dev, &local_err);
21207ee6c1e1SMarkus Armbruster         if (local_err) {
21217ee6c1e1SMarkus Armbruster             error_propagate(errp, local_err);
2122315a1350SMichael S. Tsirkin             do_pci_unregister_device(pci_dev);
2123133e9b22SMarkus Armbruster             return;
2124315a1350SMichael S. Tsirkin         }
2125315a1350SMichael S. Tsirkin     }
2126315a1350SMichael S. Tsirkin 
2127ca92eb5dSAni Sinha     /*
2128ca92eb5dSAni Sinha      * A PCIe Downstream Port that do not have ARI Forwarding enabled must
2129ca92eb5dSAni Sinha      * associate only Device 0 with the device attached to the bus
2130ca92eb5dSAni Sinha      * representing the Link from the Port (PCIe base spec rev 4.0 ver 0.3,
2131ca92eb5dSAni Sinha      * sec 7.3.1).
2132ca92eb5dSAni Sinha      * With ARI, PCI_SLOT() can return non-zero value as the traditional
2133ca92eb5dSAni Sinha      * 5-bit Device Number and 3-bit Function Number fields in its associated
2134ca92eb5dSAni Sinha      * Routing IDs, Requester IDs and Completer IDs are interpreted as a
2135ca92eb5dSAni Sinha      * single 8-bit Function Number. Hence, ignore ARI capable devices.
2136ca92eb5dSAni Sinha      */
2137ca92eb5dSAni Sinha     if (pci_is_express(pci_dev) &&
2138ca92eb5dSAni Sinha         !pcie_find_capability(pci_dev, PCI_EXT_CAP_ID_ARI) &&
2139ca92eb5dSAni Sinha         pcie_has_upstream_port(pci_dev) &&
2140ca92eb5dSAni Sinha         PCI_SLOT(pci_dev->devfn)) {
2141ca92eb5dSAni Sinha         warn_report("PCI: slot %d is not valid for %s,"
2142ca92eb5dSAni Sinha                     " parent device only allows plugging into slot 0.",
2143ca92eb5dSAni Sinha                     PCI_SLOT(pci_dev->devfn), pci_dev->name);
2144ca92eb5dSAni Sinha     }
2145ca92eb5dSAni Sinha 
21464f5b6a05SJens Freimann     if (pci_dev->failover_pair_id) {
21474f5b6a05SJens Freimann         if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
21484f5b6a05SJens Freimann             error_setg(errp, "failover primary device must be on "
21494f5b6a05SJens Freimann                              "PCIExpress bus");
2150b69c3c21SMarkus Armbruster             pci_qdev_unrealize(DEVICE(pci_dev));
21514f5b6a05SJens Freimann             return;
21524f5b6a05SJens Freimann         }
21534f5b6a05SJens Freimann         class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
21544f5b6a05SJens Freimann         if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
21554f5b6a05SJens Freimann             error_setg(errp, "failover primary device is not an "
21564f5b6a05SJens Freimann                              "Ethernet device");
2157b69c3c21SMarkus Armbruster             pci_qdev_unrealize(DEVICE(pci_dev));
21584f5b6a05SJens Freimann             return;
21594f5b6a05SJens Freimann         }
2160b01a4901SLaurent Vivier         if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2161b01a4901SLaurent Vivier             || (PCI_FUNC(pci_dev->devfn) != 0)) {
21624f5b6a05SJens Freimann             error_setg(errp, "failover: primary device must be in its own "
21634f5b6a05SJens Freimann                               "PCI slot");
2164b69c3c21SMarkus Armbruster             pci_qdev_unrealize(DEVICE(pci_dev));
21654f5b6a05SJens Freimann             return;
21664f5b6a05SJens Freimann         }
2167a1190ab6SJens Freimann         qdev->allow_unplug_during_migration = true;
21684f5b6a05SJens Freimann     }
21694f5b6a05SJens Freimann 
2170315a1350SMichael S. Tsirkin     /* rom loading */
2171315a1350SMichael S. Tsirkin     is_default_rom = false;
2172315a1350SMichael S. Tsirkin     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2173315a1350SMichael S. Tsirkin         pci_dev->romfile = g_strdup(pc->romfile);
2174315a1350SMichael S. Tsirkin         is_default_rom = true;
2175315a1350SMichael S. Tsirkin     }
2176178e785fSMarcel Apfelbaum 
2177133e9b22SMarkus Armbruster     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2178133e9b22SMarkus Armbruster     if (local_err) {
2179133e9b22SMarkus Armbruster         error_propagate(errp, local_err);
2180b69c3c21SMarkus Armbruster         pci_qdev_unrealize(DEVICE(pci_dev));
2181133e9b22SMarkus Armbruster         return;
2182178e785fSMarcel Apfelbaum     }
218323786d13SGerd Hoffmann 
218423786d13SGerd Hoffmann     pci_set_power(pci_dev, true);
218508cf3dc6SJagannathan Raman 
218608cf3dc6SJagannathan Raman     pci_dev->msi_trigger = pci_msi_trigger;
2187315a1350SMichael S. Tsirkin }
2188315a1350SMichael S. Tsirkin 
2189c925f40aSBernhard Beschow static PCIDevice *pci_new_internal(int devfn, bool multifunction,
21907411aa63SMarkus Armbruster                                    const char *name)
21917411aa63SMarkus Armbruster {
21927411aa63SMarkus Armbruster     DeviceState *dev;
21937411aa63SMarkus Armbruster 
21947411aa63SMarkus Armbruster     dev = qdev_new(name);
21957411aa63SMarkus Armbruster     qdev_prop_set_int32(dev, "addr", devfn);
21967411aa63SMarkus Armbruster     qdev_prop_set_bit(dev, "multifunction", multifunction);
21977411aa63SMarkus Armbruster     return PCI_DEVICE(dev);
21987411aa63SMarkus Armbruster }
21997411aa63SMarkus Armbruster 
2200c925f40aSBernhard Beschow PCIDevice *pci_new_multifunction(int devfn, const char *name)
2201c925f40aSBernhard Beschow {
2202c925f40aSBernhard Beschow     return pci_new_internal(devfn, true, name);
2203c925f40aSBernhard Beschow }
2204c925f40aSBernhard Beschow 
22057411aa63SMarkus Armbruster PCIDevice *pci_new(int devfn, const char *name)
22067411aa63SMarkus Armbruster {
2207c925f40aSBernhard Beschow     return pci_new_internal(devfn, false, name);
22087411aa63SMarkus Armbruster }
22097411aa63SMarkus Armbruster 
22107411aa63SMarkus Armbruster bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
22117411aa63SMarkus Armbruster {
22127411aa63SMarkus Armbruster     return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
22137411aa63SMarkus Armbruster }
22147411aa63SMarkus Armbruster 
2215315a1350SMichael S. Tsirkin PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2216315a1350SMichael S. Tsirkin                                            const char *name)
2217315a1350SMichael S. Tsirkin {
2218c925f40aSBernhard Beschow     PCIDevice *dev = pci_new_multifunction(devfn, name);
22199307d06dSMarkus Armbruster     pci_realize_and_unref(dev, bus, &error_fatal);
2220315a1350SMichael S. Tsirkin     return dev;
2221315a1350SMichael S. Tsirkin }
2222315a1350SMichael S. Tsirkin 
2223315a1350SMichael S. Tsirkin PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2224315a1350SMichael S. Tsirkin {
2225e052944aSBernhard Beschow     PCIDevice *dev = pci_new(devfn, name);
2226e052944aSBernhard Beschow     pci_realize_and_unref(dev, bus, &error_fatal);
2227e052944aSBernhard Beschow     return dev;
2228315a1350SMichael S. Tsirkin }
2229315a1350SMichael S. Tsirkin 
2230315a1350SMichael S. Tsirkin static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2231315a1350SMichael S. Tsirkin {
2232315a1350SMichael S. Tsirkin     int offset = PCI_CONFIG_HEADER_SIZE;
2233315a1350SMichael S. Tsirkin     int i;
2234315a1350SMichael S. Tsirkin     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2235315a1350SMichael S. Tsirkin         if (pdev->used[i])
2236315a1350SMichael S. Tsirkin             offset = i + 1;
2237315a1350SMichael S. Tsirkin         else if (i - offset + 1 == size)
2238315a1350SMichael S. Tsirkin             return offset;
2239315a1350SMichael S. Tsirkin     }
2240315a1350SMichael S. Tsirkin     return 0;
2241315a1350SMichael S. Tsirkin }
2242315a1350SMichael S. Tsirkin 
2243315a1350SMichael S. Tsirkin static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2244315a1350SMichael S. Tsirkin                                         uint8_t *prev_p)
2245315a1350SMichael S. Tsirkin {
2246315a1350SMichael S. Tsirkin     uint8_t next, prev;
2247315a1350SMichael S. Tsirkin 
2248315a1350SMichael S. Tsirkin     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2249315a1350SMichael S. Tsirkin         return 0;
2250315a1350SMichael S. Tsirkin 
2251315a1350SMichael S. Tsirkin     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2252315a1350SMichael S. Tsirkin          prev = next + PCI_CAP_LIST_NEXT)
2253315a1350SMichael S. Tsirkin         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2254315a1350SMichael S. Tsirkin             break;
2255315a1350SMichael S. Tsirkin 
2256315a1350SMichael S. Tsirkin     if (prev_p)
2257315a1350SMichael S. Tsirkin         *prev_p = prev;
2258315a1350SMichael S. Tsirkin     return next;
2259315a1350SMichael S. Tsirkin }
2260315a1350SMichael S. Tsirkin 
2261315a1350SMichael S. Tsirkin static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2262315a1350SMichael S. Tsirkin {
2263315a1350SMichael S. Tsirkin     uint8_t next, prev, found = 0;
2264315a1350SMichael S. Tsirkin 
2265315a1350SMichael S. Tsirkin     if (!(pdev->used[offset])) {
2266315a1350SMichael S. Tsirkin         return 0;
2267315a1350SMichael S. Tsirkin     }
2268315a1350SMichael S. Tsirkin 
2269315a1350SMichael S. Tsirkin     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2270315a1350SMichael S. Tsirkin 
2271315a1350SMichael S. Tsirkin     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2272315a1350SMichael S. Tsirkin          prev = next + PCI_CAP_LIST_NEXT) {
2273315a1350SMichael S. Tsirkin         if (next <= offset && next > found) {
2274315a1350SMichael S. Tsirkin             found = next;
2275315a1350SMichael S. Tsirkin         }
2276315a1350SMichael S. Tsirkin     }
2277315a1350SMichael S. Tsirkin     return found;
2278315a1350SMichael S. Tsirkin }
2279315a1350SMichael S. Tsirkin 
2280315a1350SMichael S. Tsirkin /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2281315a1350SMichael S. Tsirkin    This is needed for an option rom which is used for more than one device. */
22827c16b5bbSPaolo Bonzini static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2283315a1350SMichael S. Tsirkin {
2284315a1350SMichael S. Tsirkin     uint16_t vendor_id;
2285315a1350SMichael S. Tsirkin     uint16_t device_id;
2286315a1350SMichael S. Tsirkin     uint16_t rom_vendor_id;
2287315a1350SMichael S. Tsirkin     uint16_t rom_device_id;
2288315a1350SMichael S. Tsirkin     uint16_t rom_magic;
2289315a1350SMichael S. Tsirkin     uint16_t pcir_offset;
2290315a1350SMichael S. Tsirkin     uint8_t checksum;
2291315a1350SMichael S. Tsirkin 
2292315a1350SMichael S. Tsirkin     /* Words in rom data are little endian (like in PCI configuration),
2293315a1350SMichael S. Tsirkin        so they can be read / written with pci_get_word / pci_set_word. */
2294315a1350SMichael S. Tsirkin 
2295315a1350SMichael S. Tsirkin     /* Only a valid rom will be patched. */
2296315a1350SMichael S. Tsirkin     rom_magic = pci_get_word(ptr);
2297315a1350SMichael S. Tsirkin     if (rom_magic != 0xaa55) {
2298315a1350SMichael S. Tsirkin         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2299315a1350SMichael S. Tsirkin         return;
2300315a1350SMichael S. Tsirkin     }
2301315a1350SMichael S. Tsirkin     pcir_offset = pci_get_word(ptr + 0x18);
2302315a1350SMichael S. Tsirkin     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2303315a1350SMichael S. Tsirkin         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2304315a1350SMichael S. Tsirkin         return;
2305315a1350SMichael S. Tsirkin     }
2306315a1350SMichael S. Tsirkin 
2307315a1350SMichael S. Tsirkin     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2308315a1350SMichael S. Tsirkin     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2309315a1350SMichael S. Tsirkin     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2310315a1350SMichael S. Tsirkin     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2311315a1350SMichael S. Tsirkin 
2312315a1350SMichael S. Tsirkin     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2313315a1350SMichael S. Tsirkin                 vendor_id, device_id, rom_vendor_id, rom_device_id);
2314315a1350SMichael S. Tsirkin 
2315315a1350SMichael S. Tsirkin     checksum = ptr[6];
2316315a1350SMichael S. Tsirkin 
2317315a1350SMichael S. Tsirkin     if (vendor_id != rom_vendor_id) {
2318315a1350SMichael S. Tsirkin         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2319315a1350SMichael S. Tsirkin         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2320315a1350SMichael S. Tsirkin         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2321315a1350SMichael S. Tsirkin         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2322315a1350SMichael S. Tsirkin         ptr[6] = checksum;
2323315a1350SMichael S. Tsirkin         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2324315a1350SMichael S. Tsirkin     }
2325315a1350SMichael S. Tsirkin 
2326315a1350SMichael S. Tsirkin     if (device_id != rom_device_id) {
2327315a1350SMichael S. Tsirkin         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2328315a1350SMichael S. Tsirkin         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2329315a1350SMichael S. Tsirkin         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2330315a1350SMichael S. Tsirkin         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2331315a1350SMichael S. Tsirkin         ptr[6] = checksum;
2332315a1350SMichael S. Tsirkin         pci_set_word(ptr + pcir_offset + 6, device_id);
2333315a1350SMichael S. Tsirkin     }
2334315a1350SMichael S. Tsirkin }
2335315a1350SMichael S. Tsirkin 
2336315a1350SMichael S. Tsirkin /* Add an option rom for the device */
2337133e9b22SMarkus Armbruster static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2338133e9b22SMarkus Armbruster                                Error **errp)
2339315a1350SMichael S. Tsirkin {
23408eb85fb5SVladimir Sementsov-Ogievskiy     int64_t size = 0;
23415b52692fSVladimir Sementsov-Ogievskiy     g_autofree char *path = NULL;
2342315a1350SMichael S. Tsirkin     char name[32];
2343315a1350SMichael S. Tsirkin     const VMStateDescription *vmsd;
2344315a1350SMichael S. Tsirkin 
23458eb85fb5SVladimir Sementsov-Ogievskiy     /*
23468eb85fb5SVladimir Sementsov-Ogievskiy      * In case of incoming migration ROM will come with migration stream, no
23478eb85fb5SVladimir Sementsov-Ogievskiy      * reason to load the file.  Neither we want to fail if local ROM file
23488eb85fb5SVladimir Sementsov-Ogievskiy      * mismatches with specified romsize.
23498eb85fb5SVladimir Sementsov-Ogievskiy      */
23508eb85fb5SVladimir Sementsov-Ogievskiy     bool load_file = !runstate_check(RUN_STATE_INMIGRATE);
23518eb85fb5SVladimir Sementsov-Ogievskiy 
23524ab049c7SVladimir Sementsov-Ogievskiy     if (!pdev->romfile || !strlen(pdev->romfile)) {
2353133e9b22SMarkus Armbruster         return;
23544ab049c7SVladimir Sementsov-Ogievskiy     }
2355315a1350SMichael S. Tsirkin 
2356315a1350SMichael S. Tsirkin     if (!pdev->rom_bar) {
2357315a1350SMichael S. Tsirkin         /*
2358315a1350SMichael S. Tsirkin          * Load rom via fw_cfg instead of creating a rom bar,
2359315a1350SMichael S. Tsirkin          * for 0.11 compatibility.
2360315a1350SMichael S. Tsirkin          */
2361315a1350SMichael S. Tsirkin         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2362db80c7b9SMarcel Apfelbaum 
2363db80c7b9SMarcel Apfelbaum         /*
2364db80c7b9SMarcel Apfelbaum          * Hot-plugged devices can't use the option ROM
2365db80c7b9SMarcel Apfelbaum          * if the rom bar is disabled.
2366db80c7b9SMarcel Apfelbaum          */
2367db80c7b9SMarcel Apfelbaum         if (DEVICE(pdev)->hotplugged) {
2368133e9b22SMarkus Armbruster             error_setg(errp, "Hot-plugged device without ROM bar"
2369133e9b22SMarkus Armbruster                        " can't have an option ROM");
2370133e9b22SMarkus Armbruster             return;
2371db80c7b9SMarcel Apfelbaum         }
2372db80c7b9SMarcel Apfelbaum 
2373315a1350SMichael S. Tsirkin         if (class == 0x0300) {
2374315a1350SMichael S. Tsirkin             rom_add_vga(pdev->romfile);
2375315a1350SMichael S. Tsirkin         } else {
2376315a1350SMichael S. Tsirkin             rom_add_option(pdev->romfile, -1);
2377315a1350SMichael S. Tsirkin         }
2378133e9b22SMarkus Armbruster         return;
2379315a1350SMichael S. Tsirkin     }
2380315a1350SMichael S. Tsirkin 
23818eb85fb5SVladimir Sementsov-Ogievskiy     if (load_file || pdev->romsize == -1) {
2382315a1350SMichael S. Tsirkin         path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2383315a1350SMichael S. Tsirkin         if (path == NULL) {
2384315a1350SMichael S. Tsirkin             path = g_strdup(pdev->romfile);
2385315a1350SMichael S. Tsirkin         }
2386315a1350SMichael S. Tsirkin 
2387315a1350SMichael S. Tsirkin         size = get_image_size(path);
2388315a1350SMichael S. Tsirkin         if (size < 0) {
2389133e9b22SMarkus Armbruster             error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2390133e9b22SMarkus Armbruster             return;
23918c7f3dd0SStefan Hajnoczi         } else if (size == 0) {
2392133e9b22SMarkus Armbruster             error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2393133e9b22SMarkus Armbruster             return;
23947c16b5bbSPaolo Bonzini         } else if (size > 2 * GiB) {
23958eb85fb5SVladimir Sementsov-Ogievskiy             error_setg(errp,
23968eb85fb5SVladimir Sementsov-Ogievskiy                        "romfile \"%s\" too large (size cannot exceed 2 GiB)",
23977c16b5bbSPaolo Bonzini                        pdev->romfile);
23987c16b5bbSPaolo Bonzini             return;
2399315a1350SMichael S. Tsirkin         }
240008b1df8fSPaolo Bonzini         if (pdev->romsize != -1) {
240108b1df8fSPaolo Bonzini             if (size > pdev->romsize) {
24024ab049c7SVladimir Sementsov-Ogievskiy                 error_setg(errp, "romfile \"%s\" (%u bytes) "
24034ab049c7SVladimir Sementsov-Ogievskiy                            "is too large for ROM size %u",
240408b1df8fSPaolo Bonzini                            pdev->romfile, (uint32_t)size, pdev->romsize);
240508b1df8fSPaolo Bonzini                 return;
240608b1df8fSPaolo Bonzini             }
240708b1df8fSPaolo Bonzini         } else {
240808b1df8fSPaolo Bonzini             pdev->romsize = pow2ceil(size);
240908b1df8fSPaolo Bonzini         }
24108eb85fb5SVladimir Sementsov-Ogievskiy     }
2411315a1350SMichael S. Tsirkin 
2412315a1350SMichael S. Tsirkin     vmsd = qdev_get_vmsd(DEVICE(pdev));
24134ab049c7SVladimir Sementsov-Ogievskiy     snprintf(name, sizeof(name), "%s.rom",
24144ab049c7SVladimir Sementsov-Ogievskiy              vmsd ? vmsd->name : object_get_typename(OBJECT(pdev)));
2415315a1350SMichael S. Tsirkin 
2416315a1350SMichael S. Tsirkin     pdev->has_rom = true;
24174ab049c7SVladimir Sementsov-Ogievskiy     memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize,
24184ab049c7SVladimir Sementsov-Ogievskiy                            &error_fatal);
24194ab049c7SVladimir Sementsov-Ogievskiy 
24208eb85fb5SVladimir Sementsov-Ogievskiy     if (load_file) {
24218eb85fb5SVladimir Sementsov-Ogievskiy         void *ptr = memory_region_get_ram_ptr(&pdev->rom);
24228eb85fb5SVladimir Sementsov-Ogievskiy 
242336bde091SPeter Maydell         if (load_image_size(path, ptr, size) < 0) {
242436bde091SPeter Maydell             error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
242536bde091SPeter Maydell             return;
242636bde091SPeter Maydell         }
2427315a1350SMichael S. Tsirkin 
2428315a1350SMichael S. Tsirkin         if (is_default_rom) {
2429315a1350SMichael S. Tsirkin             /* Only the default rom images will be patched (if needed). */
2430315a1350SMichael S. Tsirkin             pci_patch_ids(pdev, ptr, size);
2431315a1350SMichael S. Tsirkin         }
24328eb85fb5SVladimir Sementsov-Ogievskiy     }
2433315a1350SMichael S. Tsirkin 
2434315a1350SMichael S. Tsirkin     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2435315a1350SMichael S. Tsirkin }
2436315a1350SMichael S. Tsirkin 
2437315a1350SMichael S. Tsirkin static void pci_del_option_rom(PCIDevice *pdev)
2438315a1350SMichael S. Tsirkin {
2439315a1350SMichael S. Tsirkin     if (!pdev->has_rom)
2440315a1350SMichael S. Tsirkin         return;
2441315a1350SMichael S. Tsirkin 
2442315a1350SMichael S. Tsirkin     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2443315a1350SMichael S. Tsirkin     pdev->has_rom = false;
2444315a1350SMichael S. Tsirkin }
2445315a1350SMichael S. Tsirkin 
2446315a1350SMichael S. Tsirkin /*
244727841278SMao Zhongyi  * On success, pci_add_capability() returns a positive value
2448eacbc632SMao Zhongyi  * that the offset of the pci capability.
2449eacbc632SMao Zhongyi  * On failure, it sets an error and returns a negative error
2450eacbc632SMao Zhongyi  * code.
2451eacbc632SMao Zhongyi  */
245227841278SMao Zhongyi int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2453cd9aa33eSLaszlo Ersek                        uint8_t offset, uint8_t size,
2454cd9aa33eSLaszlo Ersek                        Error **errp)
2455cd9aa33eSLaszlo Ersek {
2456315a1350SMichael S. Tsirkin     uint8_t *config;
2457315a1350SMichael S. Tsirkin     int i, overlapping_cap;
2458315a1350SMichael S. Tsirkin 
2459315a1350SMichael S. Tsirkin     if (!offset) {
2460315a1350SMichael S. Tsirkin         offset = pci_find_space(pdev, size);
246197fe42f1SCao jin         /* out of PCI config space is programming error */
246297fe42f1SCao jin         assert(offset);
2463315a1350SMichael S. Tsirkin     } else {
2464315a1350SMichael S. Tsirkin         /* Verify that capabilities don't overlap.  Note: device assignment
2465315a1350SMichael S. Tsirkin          * depends on this check to verify that the device is not broken.
2466315a1350SMichael S. Tsirkin          * Should never trigger for emulated devices, but it's helpful
2467315a1350SMichael S. Tsirkin          * for debugging these. */
2468315a1350SMichael S. Tsirkin         for (i = offset; i < offset + size; i++) {
2469315a1350SMichael S. Tsirkin             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2470315a1350SMichael S. Tsirkin             if (overlapping_cap) {
2471cd9aa33eSLaszlo Ersek                 error_setg(errp, "%s:%02x:%02x.%x "
2472315a1350SMichael S. Tsirkin                            "Attempt to add PCI capability %x at offset "
2473cd9aa33eSLaszlo Ersek                            "%x overlaps existing capability %x at offset %x",
2474fd56e061SDavid Gibson                            pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2475315a1350SMichael S. Tsirkin                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2476315a1350SMichael S. Tsirkin                            cap_id, offset, overlapping_cap, i);
2477315a1350SMichael S. Tsirkin                 return -EINVAL;
2478315a1350SMichael S. Tsirkin             }
2479315a1350SMichael S. Tsirkin         }
2480315a1350SMichael S. Tsirkin     }
2481315a1350SMichael S. Tsirkin 
2482315a1350SMichael S. Tsirkin     config = pdev->config + offset;
2483315a1350SMichael S. Tsirkin     config[PCI_CAP_LIST_ID] = cap_id;
2484315a1350SMichael S. Tsirkin     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2485315a1350SMichael S. Tsirkin     pdev->config[PCI_CAPABILITY_LIST] = offset;
2486315a1350SMichael S. Tsirkin     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2487315a1350SMichael S. Tsirkin     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2488315a1350SMichael S. Tsirkin     /* Make capability read-only by default */
2489315a1350SMichael S. Tsirkin     memset(pdev->wmask + offset, 0, size);
2490315a1350SMichael S. Tsirkin     /* Check capability by default */
2491315a1350SMichael S. Tsirkin     memset(pdev->cmask + offset, 0xFF, size);
2492315a1350SMichael S. Tsirkin     return offset;
2493315a1350SMichael S. Tsirkin }
2494315a1350SMichael S. Tsirkin 
2495315a1350SMichael S. Tsirkin /* Unlink capability from the pci config space. */
2496315a1350SMichael S. Tsirkin void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2497315a1350SMichael S. Tsirkin {
2498315a1350SMichael S. Tsirkin     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2499315a1350SMichael S. Tsirkin     if (!offset)
2500315a1350SMichael S. Tsirkin         return;
2501315a1350SMichael S. Tsirkin     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2502315a1350SMichael S. Tsirkin     /* Make capability writable again */
2503315a1350SMichael S. Tsirkin     memset(pdev->wmask + offset, 0xff, size);
2504315a1350SMichael S. Tsirkin     memset(pdev->w1cmask + offset, 0, size);
2505315a1350SMichael S. Tsirkin     /* Clear cmask as device-specific registers can't be checked */
2506315a1350SMichael S. Tsirkin     memset(pdev->cmask + offset, 0, size);
2507315a1350SMichael S. Tsirkin     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2508315a1350SMichael S. Tsirkin 
2509315a1350SMichael S. Tsirkin     if (!pdev->config[PCI_CAPABILITY_LIST])
2510315a1350SMichael S. Tsirkin         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2511315a1350SMichael S. Tsirkin }
2512315a1350SMichael S. Tsirkin 
2513315a1350SMichael S. Tsirkin uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2514315a1350SMichael S. Tsirkin {
2515315a1350SMichael S. Tsirkin     return pci_find_capability_list(pdev, cap_id, NULL);
2516315a1350SMichael S. Tsirkin }
2517315a1350SMichael S. Tsirkin 
2518315a1350SMichael S. Tsirkin static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2519315a1350SMichael S. Tsirkin {
2520315a1350SMichael S. Tsirkin     PCIDevice *d = (PCIDevice *)dev;
2521315a1350SMichael S. Tsirkin     const char *name = NULL;
2522315a1350SMichael S. Tsirkin     const pci_class_desc *desc =  pci_class_descriptions;
2523315a1350SMichael S. Tsirkin     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2524315a1350SMichael S. Tsirkin 
2525315a1350SMichael S. Tsirkin     while (desc->desc &&
2526315a1350SMichael S. Tsirkin           (class & ~desc->fw_ign_bits) !=
2527315a1350SMichael S. Tsirkin           (desc->class & ~desc->fw_ign_bits)) {
2528315a1350SMichael S. Tsirkin         desc++;
2529315a1350SMichael S. Tsirkin     }
2530315a1350SMichael S. Tsirkin 
2531315a1350SMichael S. Tsirkin     if (desc->desc) {
2532315a1350SMichael S. Tsirkin         name = desc->fw_name;
2533315a1350SMichael S. Tsirkin     }
2534315a1350SMichael S. Tsirkin 
2535315a1350SMichael S. Tsirkin     if (name) {
2536315a1350SMichael S. Tsirkin         pstrcpy(buf, len, name);
2537315a1350SMichael S. Tsirkin     } else {
2538315a1350SMichael S. Tsirkin         snprintf(buf, len, "pci%04x,%04x",
2539315a1350SMichael S. Tsirkin                  pci_get_word(d->config + PCI_VENDOR_ID),
2540315a1350SMichael S. Tsirkin                  pci_get_word(d->config + PCI_DEVICE_ID));
2541315a1350SMichael S. Tsirkin     }
2542315a1350SMichael S. Tsirkin 
2543315a1350SMichael S. Tsirkin     return buf;
2544315a1350SMichael S. Tsirkin }
2545315a1350SMichael S. Tsirkin 
2546315a1350SMichael S. Tsirkin static char *pcibus_get_fw_dev_path(DeviceState *dev)
2547315a1350SMichael S. Tsirkin {
2548315a1350SMichael S. Tsirkin     PCIDevice *d = (PCIDevice *)dev;
254936f18c69SClaudio Fontana     char name[33];
255036f18c69SClaudio Fontana     int has_func = !!PCI_FUNC(d->devfn);
2551315a1350SMichael S. Tsirkin 
255236f18c69SClaudio Fontana     return g_strdup_printf("%s@%x%s%.*x",
255336f18c69SClaudio Fontana                            pci_dev_fw_name(dev, name, sizeof(name)),
255436f18c69SClaudio Fontana                            PCI_SLOT(d->devfn),
255536f18c69SClaudio Fontana                            has_func ? "," : "",
255636f18c69SClaudio Fontana                            has_func,
255736f18c69SClaudio Fontana                            PCI_FUNC(d->devfn));
2558315a1350SMichael S. Tsirkin }
2559315a1350SMichael S. Tsirkin 
2560315a1350SMichael S. Tsirkin static char *pcibus_get_dev_path(DeviceState *dev)
2561315a1350SMichael S. Tsirkin {
2562315a1350SMichael S. Tsirkin     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2563315a1350SMichael S. Tsirkin     PCIDevice *t;
2564315a1350SMichael S. Tsirkin     int slot_depth;
2565315a1350SMichael S. Tsirkin     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2566315a1350SMichael S. Tsirkin      * 00 is added here to make this format compatible with
2567315a1350SMichael S. Tsirkin      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2568315a1350SMichael S. Tsirkin      * Slot.Function list specifies the slot and function numbers for all
2569315a1350SMichael S. Tsirkin      * devices on the path from root to the specific device. */
2570568f0690SDavid Gibson     const char *root_bus_path;
2571568f0690SDavid Gibson     int root_bus_len;
2572315a1350SMichael S. Tsirkin     char slot[] = ":SS.F";
2573315a1350SMichael S. Tsirkin     int slot_len = sizeof slot - 1 /* For '\0' */;
2574315a1350SMichael S. Tsirkin     int path_len;
2575315a1350SMichael S. Tsirkin     char *path, *p;
2576315a1350SMichael S. Tsirkin     int s;
2577315a1350SMichael S. Tsirkin 
2578568f0690SDavid Gibson     root_bus_path = pci_root_bus_path(d);
2579568f0690SDavid Gibson     root_bus_len = strlen(root_bus_path);
2580568f0690SDavid Gibson 
2581315a1350SMichael S. Tsirkin     /* Calculate # of slots on path between device and root. */;
2582315a1350SMichael S. Tsirkin     slot_depth = 0;
2583fd56e061SDavid Gibson     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2584315a1350SMichael S. Tsirkin         ++slot_depth;
2585315a1350SMichael S. Tsirkin     }
2586315a1350SMichael S. Tsirkin 
2587568f0690SDavid Gibson     path_len = root_bus_len + slot_len * slot_depth;
2588315a1350SMichael S. Tsirkin 
2589315a1350SMichael S. Tsirkin     /* Allocate memory, fill in the terminating null byte. */
2590315a1350SMichael S. Tsirkin     path = g_malloc(path_len + 1 /* For '\0' */);
2591315a1350SMichael S. Tsirkin     path[path_len] = '\0';
2592315a1350SMichael S. Tsirkin 
2593568f0690SDavid Gibson     memcpy(path, root_bus_path, root_bus_len);
2594315a1350SMichael S. Tsirkin 
2595315a1350SMichael S. Tsirkin     /* Fill in slot numbers. We walk up from device to root, so need to print
2596315a1350SMichael S. Tsirkin      * them in the reverse order, last to first. */
2597315a1350SMichael S. Tsirkin     p = path + path_len;
2598fd56e061SDavid Gibson     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2599315a1350SMichael S. Tsirkin         p -= slot_len;
2600315a1350SMichael S. Tsirkin         s = snprintf(slot, sizeof slot, ":%02x.%x",
2601315a1350SMichael S. Tsirkin                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2602315a1350SMichael S. Tsirkin         assert(s == slot_len);
2603315a1350SMichael S. Tsirkin         memcpy(p, slot, slot_len);
2604315a1350SMichael S. Tsirkin     }
2605315a1350SMichael S. Tsirkin 
2606315a1350SMichael S. Tsirkin     return path;
2607315a1350SMichael S. Tsirkin }
2608315a1350SMichael S. Tsirkin 
2609315a1350SMichael S. Tsirkin static int pci_qdev_find_recursive(PCIBus *bus,
2610315a1350SMichael S. Tsirkin                                    const char *id, PCIDevice **pdev)
2611315a1350SMichael S. Tsirkin {
2612315a1350SMichael S. Tsirkin     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2613315a1350SMichael S. Tsirkin     if (!qdev) {
2614315a1350SMichael S. Tsirkin         return -ENODEV;
2615315a1350SMichael S. Tsirkin     }
2616315a1350SMichael S. Tsirkin 
2617315a1350SMichael S. Tsirkin     /* roughly check if given qdev is pci device */
2618315a1350SMichael S. Tsirkin     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2619315a1350SMichael S. Tsirkin         *pdev = PCI_DEVICE(qdev);
2620315a1350SMichael S. Tsirkin         return 0;
2621315a1350SMichael S. Tsirkin     }
2622315a1350SMichael S. Tsirkin     return -EINVAL;
2623315a1350SMichael S. Tsirkin }
2624315a1350SMichael S. Tsirkin 
2625315a1350SMichael S. Tsirkin int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2626315a1350SMichael S. Tsirkin {
26277588e2b0SDavid Gibson     PCIHostState *host_bridge;
2628315a1350SMichael S. Tsirkin     int rc = -ENODEV;
2629315a1350SMichael S. Tsirkin 
26307588e2b0SDavid Gibson     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
26317588e2b0SDavid Gibson         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2632315a1350SMichael S. Tsirkin         if (!tmp) {
2633315a1350SMichael S. Tsirkin             rc = 0;
2634315a1350SMichael S. Tsirkin             break;
2635315a1350SMichael S. Tsirkin         }
2636315a1350SMichael S. Tsirkin         if (tmp != -ENODEV) {
2637315a1350SMichael S. Tsirkin             rc = tmp;
2638315a1350SMichael S. Tsirkin         }
2639315a1350SMichael S. Tsirkin     }
2640315a1350SMichael S. Tsirkin 
2641315a1350SMichael S. Tsirkin     return rc;
2642315a1350SMichael S. Tsirkin }
2643315a1350SMichael S. Tsirkin 
2644315a1350SMichael S. Tsirkin MemoryRegion *pci_address_space(PCIDevice *dev)
2645315a1350SMichael S. Tsirkin {
2646fd56e061SDavid Gibson     return pci_get_bus(dev)->address_space_mem;
2647315a1350SMichael S. Tsirkin }
2648315a1350SMichael S. Tsirkin 
2649315a1350SMichael S. Tsirkin MemoryRegion *pci_address_space_io(PCIDevice *dev)
2650315a1350SMichael S. Tsirkin {
2651fd56e061SDavid Gibson     return pci_get_bus(dev)->address_space_io;
2652315a1350SMichael S. Tsirkin }
2653315a1350SMichael S. Tsirkin 
2654315a1350SMichael S. Tsirkin static void pci_device_class_init(ObjectClass *klass, void *data)
2655315a1350SMichael S. Tsirkin {
2656315a1350SMichael S. Tsirkin     DeviceClass *k = DEVICE_CLASS(klass);
26577ee6c1e1SMarkus Armbruster 
2658133e9b22SMarkus Armbruster     k->realize = pci_qdev_realize;
2659133e9b22SMarkus Armbruster     k->unrealize = pci_qdev_unrealize;
2660315a1350SMichael S. Tsirkin     k->bus_type = TYPE_PCI_BUS;
26614f67d30bSMarc-André Lureau     device_class_set_props(k, pci_props);
2662315a1350SMichael S. Tsirkin }
2663315a1350SMichael S. Tsirkin 
26642fefa16cSEduardo Habkost static void pci_device_class_base_init(ObjectClass *klass, void *data)
26652fefa16cSEduardo Habkost {
26662fefa16cSEduardo Habkost     if (!object_class_is_abstract(klass)) {
26672fefa16cSEduardo Habkost         ObjectClass *conventional =
26682fefa16cSEduardo Habkost             object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
26692fefa16cSEduardo Habkost         ObjectClass *pcie =
26702fefa16cSEduardo Habkost             object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2671d86d3019SBen Widawsky         ObjectClass *cxl =
2672d86d3019SBen Widawsky             object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE);
2673d86d3019SBen Widawsky         assert(conventional || pcie || cxl);
26742fefa16cSEduardo Habkost     }
26752fefa16cSEduardo Habkost }
26762fefa16cSEduardo Habkost 
26779eda7d37SAlexey Kardashevskiy AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
26789eda7d37SAlexey Kardashevskiy {
2679fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(dev);
26805af2ae23SBenjamin Herrenschmidt     PCIBus *iommu_bus = bus;
268177ef8f8dSAlex Williamson     uint8_t devfn = dev->devfn;
26829eda7d37SAlexey Kardashevskiy 
2683ba7d12ebSYi Liu     while (iommu_bus && !iommu_bus->iommu_ops && iommu_bus->parent_dev) {
268477ef8f8dSAlex Williamson         PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
268577ef8f8dSAlex Williamson 
268677ef8f8dSAlex Williamson         /*
268777ef8f8dSAlex Williamson          * The requester ID of the provided device may be aliased, as seen from
268877ef8f8dSAlex Williamson          * the IOMMU, due to topology limitations.  The IOMMU relies on a
268977ef8f8dSAlex Williamson          * requester ID to provide a unique AddressSpace for devices, but
269077ef8f8dSAlex Williamson          * conventional PCI buses pre-date such concepts.  Instead, the PCIe-
269177ef8f8dSAlex Williamson          * to-PCI bridge creates and accepts transactions on behalf of down-
269277ef8f8dSAlex Williamson          * stream devices.  When doing so, all downstream devices are masked
269377ef8f8dSAlex Williamson          * (aliased) behind a single requester ID.  The requester ID used
269477ef8f8dSAlex Williamson          * depends on the format of the bridge devices.  Proper PCIe-to-PCI
269577ef8f8dSAlex Williamson          * bridges, with a PCIe capability indicating such, follow the
269677ef8f8dSAlex Williamson          * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
269777ef8f8dSAlex Williamson          * where the bridge uses the seconary bus as the bridge portion of the
269877ef8f8dSAlex Williamson          * requester ID and devfn of 00.0.  For other bridges, typically those
269977ef8f8dSAlex Williamson          * found on the root complex such as the dmi-to-pci-bridge, we follow
270077ef8f8dSAlex Williamson          * the convention of typical bare-metal hardware, which uses the
270177ef8f8dSAlex Williamson          * requester ID of the bridge itself.  There are device specific
270277ef8f8dSAlex Williamson          * exceptions to these rules, but these are the defaults that the
270377ef8f8dSAlex Williamson          * Linux kernel uses when determining DMA aliases itself and believed
270477ef8f8dSAlex Williamson          * to be true for the bare metal equivalents of the devices emulated
270577ef8f8dSAlex Williamson          * in QEMU.
270677ef8f8dSAlex Williamson          */
270777ef8f8dSAlex Williamson         if (!pci_bus_is_express(iommu_bus)) {
270877ef8f8dSAlex Williamson             PCIDevice *parent = iommu_bus->parent_dev;
270977ef8f8dSAlex Williamson 
271077ef8f8dSAlex Williamson             if (pci_is_express(parent) &&
271177ef8f8dSAlex Williamson                 pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
271277ef8f8dSAlex Williamson                 devfn = PCI_DEVFN(0, 0);
271377ef8f8dSAlex Williamson                 bus = iommu_bus;
271477ef8f8dSAlex Williamson             } else {
271577ef8f8dSAlex Williamson                 devfn = parent->devfn;
271677ef8f8dSAlex Williamson                 bus = parent_bus;
271777ef8f8dSAlex Williamson             }
271877ef8f8dSAlex Williamson         }
271977ef8f8dSAlex Williamson 
272077ef8f8dSAlex Williamson         iommu_bus = parent_bus;
27219eda7d37SAlexey Kardashevskiy     }
2722ba7d12ebSYi Liu     if (!pci_bus_bypass_iommu(bus) && iommu_bus->iommu_ops) {
2723ba7d12ebSYi Liu         return iommu_bus->iommu_ops->get_address_space(bus,
2724ba7d12ebSYi Liu                                  iommu_bus->iommu_opaque, devfn);
27259eda7d37SAlexey Kardashevskiy     }
27269eda7d37SAlexey Kardashevskiy     return &address_space_memory;
27279eda7d37SAlexey Kardashevskiy }
27289eda7d37SAlexey Kardashevskiy 
2729ba7d12ebSYi Liu void pci_setup_iommu(PCIBus *bus, const PCIIOMMUOps *ops, void *opaque)
2730315a1350SMichael S. Tsirkin {
2731ba7d12ebSYi Liu     /*
2732ba7d12ebSYi Liu      * If called, pci_setup_iommu() should provide a minimum set of
2733ba7d12ebSYi Liu      * useful callbacks for the bus.
2734ba7d12ebSYi Liu      */
2735ba7d12ebSYi Liu     assert(ops);
2736ba7d12ebSYi Liu     assert(ops->get_address_space);
2737ba7d12ebSYi Liu 
2738ba7d12ebSYi Liu     bus->iommu_ops = ops;
2739e00387d5SAvi Kivity     bus->iommu_opaque = opaque;
2740315a1350SMichael S. Tsirkin }
2741315a1350SMichael S. Tsirkin 
274243864069SMichael S. Tsirkin static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
274343864069SMichael S. Tsirkin {
274443864069SMichael S. Tsirkin     Range *range = opaque;
274543864069SMichael S. Tsirkin     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
274677d6f4eaSMichael S. Tsirkin     int i;
274743864069SMichael S. Tsirkin 
274843864069SMichael S. Tsirkin     if (!(cmd & PCI_COMMAND_MEMORY)) {
274943864069SMichael S. Tsirkin         return;
275043864069SMichael S. Tsirkin     }
275143864069SMichael S. Tsirkin 
2752ad494274SIgor Mammedov     if (IS_PCI_BRIDGE(dev)) {
275343864069SMichael S. Tsirkin         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
275443864069SMichael S. Tsirkin         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
275543864069SMichael S. Tsirkin 
275643864069SMichael S. Tsirkin         base = MAX(base, 0x1ULL << 32);
275743864069SMichael S. Tsirkin 
275843864069SMichael S. Tsirkin         if (limit >= base) {
275943864069SMichael S. Tsirkin             Range pref_range;
2760a0efbf16SMarkus Armbruster             range_set_bounds(&pref_range, base, limit);
276143864069SMichael S. Tsirkin             range_extend(range, &pref_range);
276243864069SMichael S. Tsirkin         }
276343864069SMichael S. Tsirkin     }
276477d6f4eaSMichael S. Tsirkin     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
276577d6f4eaSMichael S. Tsirkin         PCIIORegion *r = &dev->io_regions[i];
2766a0efbf16SMarkus Armbruster         pcibus_t lob, upb;
276743864069SMichael S. Tsirkin         Range region_range;
276843864069SMichael S. Tsirkin 
276977d6f4eaSMichael S. Tsirkin         if (!r->size ||
277077d6f4eaSMichael S. Tsirkin             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
277177d6f4eaSMichael S. Tsirkin             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
277243864069SMichael S. Tsirkin             continue;
277343864069SMichael S. Tsirkin         }
277477d6f4eaSMichael S. Tsirkin 
2775a0efbf16SMarkus Armbruster         lob = pci_bar_address(dev, i, r->type, r->size);
2776a0efbf16SMarkus Armbruster         upb = lob + r->size - 1;
2777a0efbf16SMarkus Armbruster         if (lob == PCI_BAR_UNMAPPED) {
277877d6f4eaSMichael S. Tsirkin             continue;
277977d6f4eaSMichael S. Tsirkin         }
278043864069SMichael S. Tsirkin 
2781a0efbf16SMarkus Armbruster         lob = MAX(lob, 0x1ULL << 32);
278243864069SMichael S. Tsirkin 
2783a0efbf16SMarkus Armbruster         if (upb >= lob) {
2784a0efbf16SMarkus Armbruster             range_set_bounds(&region_range, lob, upb);
278543864069SMichael S. Tsirkin             range_extend(range, &region_range);
278643864069SMichael S. Tsirkin         }
278743864069SMichael S. Tsirkin     }
278843864069SMichael S. Tsirkin }
278943864069SMichael S. Tsirkin 
279043864069SMichael S. Tsirkin void pci_bus_get_w64_range(PCIBus *bus, Range *range)
279143864069SMichael S. Tsirkin {
2792a0efbf16SMarkus Armbruster     range_make_empty(range);
279343864069SMichael S. Tsirkin     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
279443864069SMichael S. Tsirkin }
279543864069SMichael S. Tsirkin 
27963f1e1478SCao jin static bool pcie_has_upstream_port(PCIDevice *dev)
27973f1e1478SCao jin {
2798fd56e061SDavid Gibson     PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
27993f1e1478SCao jin 
28003f1e1478SCao jin     /* Device associated with an upstream port.
28013f1e1478SCao jin      * As there are several types of these, it's easier to check the
28023f1e1478SCao jin      * parent device: upstream ports are always connected to
28033f1e1478SCao jin      * root or downstream ports.
28043f1e1478SCao jin      */
28053f1e1478SCao jin     return parent_dev &&
28063f1e1478SCao jin         pci_is_express(parent_dev) &&
28073f1e1478SCao jin         parent_dev->exp.exp_cap &&
28083f1e1478SCao jin         (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
28093f1e1478SCao jin          pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
28103f1e1478SCao jin }
28113f1e1478SCao jin 
28123f1e1478SCao jin PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
28133f1e1478SCao jin {
2814fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
2815fd56e061SDavid Gibson 
28163f1e1478SCao jin     if(pcie_has_upstream_port(pci_dev)) {
28173f1e1478SCao jin         /* With an upstream PCIe port, we only support 1 device at slot 0 */
2818fd56e061SDavid Gibson         return bus->devices[0];
28193f1e1478SCao jin     } else {
28203f1e1478SCao jin         /* Other bus types might support multiple devices at slots 0-31 */
2821fd56e061SDavid Gibson         return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
28223f1e1478SCao jin     }
28233f1e1478SCao jin }
28243f1e1478SCao jin 
2825e1d4fb2dSPeter Xu MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2826e1d4fb2dSPeter Xu {
2827e1d4fb2dSPeter Xu     MSIMessage msg;
2828e1d4fb2dSPeter Xu     if (msix_enabled(dev)) {
2829e1d4fb2dSPeter Xu         msg = msix_get_message(dev, vector);
2830e1d4fb2dSPeter Xu     } else if (msi_enabled(dev)) {
2831e1d4fb2dSPeter Xu         msg = msi_get_message(dev, vector);
2832e1d4fb2dSPeter Xu     } else {
2833e1d4fb2dSPeter Xu         /* Should never happen */
2834e1d4fb2dSPeter Xu         error_report("%s: unknown interrupt type", __func__);
2835e1d4fb2dSPeter Xu         abort();
2836e1d4fb2dSPeter Xu     }
2837e1d4fb2dSPeter Xu     return msg;
2838e1d4fb2dSPeter Xu }
2839e1d4fb2dSPeter Xu 
284023786d13SGerd Hoffmann void pci_set_power(PCIDevice *d, bool state)
284123786d13SGerd Hoffmann {
284223786d13SGerd Hoffmann     if (d->has_power == state) {
284323786d13SGerd Hoffmann         return;
284423786d13SGerd Hoffmann     }
284523786d13SGerd Hoffmann 
284623786d13SGerd Hoffmann     d->has_power = state;
284723786d13SGerd Hoffmann     pci_update_mappings(d);
284823786d13SGerd Hoffmann     memory_region_set_enabled(&d->bus_master_enable_region,
284923786d13SGerd Hoffmann                               (pci_get_word(d->config + PCI_COMMAND)
285023786d13SGerd Hoffmann                                & PCI_COMMAND_MASTER) && d->has_power);
285123786d13SGerd Hoffmann     if (!d->has_power) {
285223786d13SGerd Hoffmann         pci_device_reset(d);
285323786d13SGerd Hoffmann     }
285423786d13SGerd Hoffmann }
285523786d13SGerd Hoffmann 
28568c43a6f0SAndreas Färber static const TypeInfo pci_device_type_info = {
2857315a1350SMichael S. Tsirkin     .name = TYPE_PCI_DEVICE,
2858315a1350SMichael S. Tsirkin     .parent = TYPE_DEVICE,
2859315a1350SMichael S. Tsirkin     .instance_size = sizeof(PCIDevice),
2860315a1350SMichael S. Tsirkin     .abstract = true,
2861315a1350SMichael S. Tsirkin     .class_size = sizeof(PCIDeviceClass),
2862315a1350SMichael S. Tsirkin     .class_init = pci_device_class_init,
28632fefa16cSEduardo Habkost     .class_base_init = pci_device_class_base_init,
2864315a1350SMichael S. Tsirkin };
2865315a1350SMichael S. Tsirkin 
2866315a1350SMichael S. Tsirkin static void pci_register_types(void)
2867315a1350SMichael S. Tsirkin {
2868315a1350SMichael S. Tsirkin     type_register_static(&pci_bus_info);
28693a861c46SAlex Williamson     type_register_static(&pcie_bus_info);
28704f8db871SBen Widawsky     type_register_static(&cxl_bus_info);
2871619f02aeSEduardo Habkost     type_register_static(&conventional_pci_interface_info);
2872cf04aba2SBen Widawsky     type_register_static(&cxl_interface_info);
2873619f02aeSEduardo Habkost     type_register_static(&pcie_interface_info);
2874315a1350SMichael S. Tsirkin     type_register_static(&pci_device_type_info);
2875315a1350SMichael S. Tsirkin }
2876315a1350SMichael S. Tsirkin 
2877315a1350SMichael S. Tsirkin type_init(pci_register_types)
2878