xref: /openbmc/qemu/hw/pci/pci.c (revision 9eb9350c0e519be97716f6b27f664bd0a3c41a36)
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);
67ad80e367SPeter Maydell static void pcibus_reset_hold(Object *obj, ResetType type);
68ca92eb5dSAni Sinha static bool pcie_has_upstream_port(PCIDevice *dev);
69315a1350SMichael S. Tsirkin 
prop_pci_busnr_get(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)70df9ac725SJonathan Cameron static void prop_pci_busnr_get(Object *obj, Visitor *v, const char *name,
71df9ac725SJonathan Cameron                              void *opaque, Error **errp)
72df9ac725SJonathan Cameron {
73df9ac725SJonathan Cameron     uint8_t busnr = pci_dev_bus_num(PCI_DEVICE(obj));
74df9ac725SJonathan Cameron 
75df9ac725SJonathan Cameron     visit_type_uint8(v, name, &busnr, errp);
76df9ac725SJonathan Cameron }
77df9ac725SJonathan Cameron 
78df9ac725SJonathan Cameron static const PropertyInfo prop_pci_busnr = {
79df9ac725SJonathan Cameron     .name = "busnr",
80df9ac725SJonathan Cameron     .get = prop_pci_busnr_get,
81df9ac725SJonathan Cameron };
82df9ac725SJonathan Cameron 
83315a1350SMichael S. Tsirkin static Property pci_props[] = {
84315a1350SMichael S. Tsirkin     DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
85315a1350SMichael S. Tsirkin     DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
866a67577dSAkihiko Odaki     DEFINE_PROP_UINT32("romsize", PCIDevice, romsize, UINT32_MAX),
87315a1350SMichael S. Tsirkin     DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
88315a1350SMichael S. Tsirkin     DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
89315a1350SMichael S. Tsirkin                     QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
906b449540SMichael S. Tsirkin     DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
916b449540SMichael S. Tsirkin                     QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
92f03d8ea3SMarcel Apfelbaum     DEFINE_PROP_BIT("x-pcie-extcap-init", PCIDevice, cap_present,
93f03d8ea3SMarcel Apfelbaum                     QEMU_PCIE_EXTCAP_INIT_BITNR, true),
944f5b6a05SJens Freimann     DEFINE_PROP_STRING("failover_pair_id", PCIDevice,
954f5b6a05SJens Freimann                        failover_pair_id),
96b32bd763SIgor Mammedov     DEFINE_PROP_UINT32("acpi-index",  PCIDevice, acpi_index, 0),
975ed3dabeSLeonardo Bras     DEFINE_PROP_BIT("x-pcie-err-unc-mask", PCIDevice, cap_present,
985ed3dabeSLeonardo Bras                     QEMU_PCIE_ERR_UNC_MASK_BITNR, true),
997c228c5fSAkihiko Odaki     DEFINE_PROP_BIT("x-pcie-ari-nextfn-1", PCIDevice, cap_present,
1007c228c5fSAkihiko Odaki                     QEMU_PCIE_ARI_NEXTFN_1_BITNR, false),
101637b0aa1SMattias Nissler     DEFINE_PROP_SIZE32("x-max-bounce-buffer-size", PCIDevice,
102637b0aa1SMattias Nissler                      max_bounce_buffer_size, DEFAULT_MAX_BOUNCE_BUFFER_SIZE),
103*449dca6aSMarcin Juszkiewicz     DEFINE_PROP_BIT("x-pcie-ext-tag", PCIDevice, cap_present,
104*449dca6aSMarcin Juszkiewicz                     QEMU_PCIE_EXT_TAG_BITNR, true),
105df9ac725SJonathan Cameron     { .name = "busnr", .info = &prop_pci_busnr },
106315a1350SMichael S. Tsirkin     DEFINE_PROP_END_OF_LIST()
107315a1350SMichael S. Tsirkin };
108315a1350SMichael S. Tsirkin 
109d2f69df7SBandan Das static const VMStateDescription vmstate_pcibus = {
110d2f69df7SBandan Das     .name = "PCIBUS",
111d2f69df7SBandan Das     .version_id = 1,
112d2f69df7SBandan Das     .minimum_version_id = 1,
1138e5e0890SRichard Henderson     .fields = (const VMStateField[]) {
114d2164ad3SHalil Pasic         VMSTATE_INT32_EQUAL(nirq, PCIBus, NULL),
115d2f69df7SBandan Das         VMSTATE_VARRAY_INT32(irq_count, PCIBus,
116d2f69df7SBandan Das                              nirq, 0, vmstate_info_int32,
117d2f69df7SBandan Das                              int32_t),
118d2f69df7SBandan Das         VMSTATE_END_OF_LIST()
119d2f69df7SBandan Das     }
120d2f69df7SBandan Das };
121d2f69df7SBandan Das 
g_cmp_uint32(gconstpointer a,gconstpointer b,gpointer user_data)122041b1c40SIgor Mammedov static gint g_cmp_uint32(gconstpointer a, gconstpointer b, gpointer user_data)
123041b1c40SIgor Mammedov {
124041b1c40SIgor Mammedov     return a - b;
125041b1c40SIgor Mammedov }
126041b1c40SIgor Mammedov 
pci_acpi_index_list(void)127041b1c40SIgor Mammedov static GSequence *pci_acpi_index_list(void)
128041b1c40SIgor Mammedov {
129041b1c40SIgor Mammedov     static GSequence *used_acpi_index_list;
130041b1c40SIgor Mammedov 
131041b1c40SIgor Mammedov     if (!used_acpi_index_list) {
132041b1c40SIgor Mammedov         used_acpi_index_list = g_sequence_new(NULL);
133041b1c40SIgor Mammedov     }
134041b1c40SIgor Mammedov     return used_acpi_index_list;
135041b1c40SIgor Mammedov }
136041b1c40SIgor Mammedov 
pci_init_bus_master(PCIDevice * pci_dev)137b86eacb8SMarcel Apfelbaum static void pci_init_bus_master(PCIDevice *pci_dev)
138b86eacb8SMarcel Apfelbaum {
139b86eacb8SMarcel Apfelbaum     AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
140b86eacb8SMarcel Apfelbaum 
141b86eacb8SMarcel Apfelbaum     memory_region_init_alias(&pci_dev->bus_master_enable_region,
142b86eacb8SMarcel Apfelbaum                              OBJECT(pci_dev), "bus master",
143b86eacb8SMarcel Apfelbaum                              dma_as->root, 0, memory_region_size(dma_as->root));
144b86eacb8SMarcel Apfelbaum     memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
1453716d590SJason Wang     memory_region_add_subregion(&pci_dev->bus_master_container_region, 0,
1463716d590SJason Wang                                 &pci_dev->bus_master_enable_region);
147b86eacb8SMarcel Apfelbaum }
148b86eacb8SMarcel Apfelbaum 
pcibus_machine_done(Notifier * notifier,void * data)149b86eacb8SMarcel Apfelbaum static void pcibus_machine_done(Notifier *notifier, void *data)
150b86eacb8SMarcel Apfelbaum {
151b86eacb8SMarcel Apfelbaum     PCIBus *bus = container_of(notifier, PCIBus, machine_done);
152b86eacb8SMarcel Apfelbaum     int i;
153b86eacb8SMarcel Apfelbaum 
154b86eacb8SMarcel Apfelbaum     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
155b86eacb8SMarcel Apfelbaum         if (bus->devices[i]) {
156b86eacb8SMarcel Apfelbaum             pci_init_bus_master(bus->devices[i]);
157b86eacb8SMarcel Apfelbaum         }
158b86eacb8SMarcel Apfelbaum     }
159b86eacb8SMarcel Apfelbaum }
160b86eacb8SMarcel Apfelbaum 
pci_bus_realize(BusState * qbus,Error ** errp)161d2f69df7SBandan Das static void pci_bus_realize(BusState *qbus, Error **errp)
162d2f69df7SBandan Das {
163d2f69df7SBandan Das     PCIBus *bus = PCI_BUS(qbus);
164d2f69df7SBandan Das 
165b86eacb8SMarcel Apfelbaum     bus->machine_done.notify = pcibus_machine_done;
166b86eacb8SMarcel Apfelbaum     qemu_add_machine_init_done_notifier(&bus->machine_done);
167b86eacb8SMarcel Apfelbaum 
16899b16e8eSJuan Quintela     vmstate_register_any(NULL, &vmstate_pcibus, bus);
169d2f69df7SBandan Das }
170d2f69df7SBandan Das 
pcie_bus_realize(BusState * qbus,Error ** errp)1712f57db8aSDavid Gibson static void pcie_bus_realize(BusState *qbus, Error **errp)
1722f57db8aSDavid Gibson {
1732f57db8aSDavid Gibson     PCIBus *bus = PCI_BUS(qbus);
174b52fa0eaSPhilippe Mathieu-Daudé     Error *local_err = NULL;
1752f57db8aSDavid Gibson 
176b52fa0eaSPhilippe Mathieu-Daudé     pci_bus_realize(qbus, &local_err);
177b52fa0eaSPhilippe Mathieu-Daudé     if (local_err) {
178b52fa0eaSPhilippe Mathieu-Daudé         error_propagate(errp, local_err);
179b52fa0eaSPhilippe Mathieu-Daudé         return;
180b52fa0eaSPhilippe Mathieu-Daudé     }
1812f57db8aSDavid Gibson 
1822f57db8aSDavid Gibson     /*
1832f57db8aSDavid Gibson      * A PCI-E bus can support extended config space if it's the root
1842f57db8aSDavid Gibson      * bus, or if the bus/bridge above it does as well
1852f57db8aSDavid Gibson      */
1862f57db8aSDavid Gibson     if (pci_bus_is_root(bus)) {
1872f57db8aSDavid Gibson         bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
1882f57db8aSDavid Gibson     } else {
1892f57db8aSDavid Gibson         PCIBus *parent_bus = pci_get_bus(bus->parent_dev);
1902f57db8aSDavid Gibson 
1912f57db8aSDavid Gibson         if (pci_bus_allows_extended_config_space(parent_bus)) {
1922f57db8aSDavid Gibson             bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
1932f57db8aSDavid Gibson         }
1942f57db8aSDavid Gibson     }
1952f57db8aSDavid Gibson }
1962f57db8aSDavid Gibson 
pci_bus_unrealize(BusState * qbus)197b69c3c21SMarkus Armbruster static void pci_bus_unrealize(BusState *qbus)
198d2f69df7SBandan Das {
199d2f69df7SBandan Das     PCIBus *bus = PCI_BUS(qbus);
200d2f69df7SBandan Das 
201b86eacb8SMarcel Apfelbaum     qemu_remove_machine_init_done_notifier(&bus->machine_done);
202b86eacb8SMarcel Apfelbaum 
203d2f69df7SBandan Das     vmstate_unregister(NULL, &vmstate_pcibus, bus);
204d2f69df7SBandan Das }
205d2f69df7SBandan Das 
pcibus_num(PCIBus * bus)206602141d9SMarcel Apfelbaum static int pcibus_num(PCIBus *bus)
207602141d9SMarcel Apfelbaum {
208b0e5196aSDavid Gibson     if (pci_bus_is_root(bus)) {
209602141d9SMarcel Apfelbaum         return 0; /* pci host bridge */
210602141d9SMarcel Apfelbaum     }
211602141d9SMarcel Apfelbaum     return bus->parent_dev->config[PCI_SECONDARY_BUS];
212602141d9SMarcel Apfelbaum }
213602141d9SMarcel Apfelbaum 
pcibus_numa_node(PCIBus * bus)2146a3042b2SMarcel Apfelbaum static uint16_t pcibus_numa_node(PCIBus *bus)
2156a3042b2SMarcel Apfelbaum {
2166a3042b2SMarcel Apfelbaum     return NUMA_NODE_UNASSIGNED;
2176a3042b2SMarcel Apfelbaum }
2186a3042b2SMarcel Apfelbaum 
pci_bus_class_init(ObjectClass * klass,void * data)219315a1350SMichael S. Tsirkin static void pci_bus_class_init(ObjectClass *klass, void *data)
220315a1350SMichael S. Tsirkin {
221315a1350SMichael S. Tsirkin     BusClass *k = BUS_CLASS(klass);
222ce6a28eeSMarcel Apfelbaum     PCIBusClass *pbc = PCI_BUS_CLASS(klass);
223e6c03989SPeter Maydell     ResettableClass *rc = RESETTABLE_CLASS(klass);
224315a1350SMichael S. Tsirkin 
225315a1350SMichael S. Tsirkin     k->print_dev = pcibus_dev_print;
226315a1350SMichael S. Tsirkin     k->get_dev_path = pcibus_get_dev_path;
227315a1350SMichael S. Tsirkin     k->get_fw_dev_path = pcibus_get_fw_dev_path;
228d2f69df7SBandan Das     k->realize = pci_bus_realize;
229d2f69df7SBandan Das     k->unrealize = pci_bus_unrealize;
230e6c03989SPeter Maydell 
231e6c03989SPeter Maydell     rc->phases.hold = pcibus_reset_hold;
232ce6a28eeSMarcel Apfelbaum 
233602141d9SMarcel Apfelbaum     pbc->bus_num = pcibus_num;
2346a3042b2SMarcel Apfelbaum     pbc->numa_node = pcibus_numa_node;
235315a1350SMichael S. Tsirkin }
236315a1350SMichael S. Tsirkin 
237315a1350SMichael S. Tsirkin static const TypeInfo pci_bus_info = {
238315a1350SMichael S. Tsirkin     .name = TYPE_PCI_BUS,
239315a1350SMichael S. Tsirkin     .parent = TYPE_BUS,
240315a1350SMichael S. Tsirkin     .instance_size = sizeof(PCIBus),
241ce6a28eeSMarcel Apfelbaum     .class_size = sizeof(PCIBusClass),
242315a1350SMichael S. Tsirkin     .class_init = pci_bus_class_init,
243315a1350SMichael S. Tsirkin };
244315a1350SMichael S. Tsirkin 
245cf04aba2SBen Widawsky static const TypeInfo cxl_interface_info = {
246cf04aba2SBen Widawsky     .name          = INTERFACE_CXL_DEVICE,
247cf04aba2SBen Widawsky     .parent        = TYPE_INTERFACE,
248cf04aba2SBen Widawsky };
249cf04aba2SBen Widawsky 
250619f02aeSEduardo Habkost static const TypeInfo pcie_interface_info = {
251619f02aeSEduardo Habkost     .name          = INTERFACE_PCIE_DEVICE,
252619f02aeSEduardo Habkost     .parent        = TYPE_INTERFACE,
253619f02aeSEduardo Habkost };
254619f02aeSEduardo Habkost 
255619f02aeSEduardo Habkost static const TypeInfo conventional_pci_interface_info = {
256619f02aeSEduardo Habkost     .name          = INTERFACE_CONVENTIONAL_PCI_DEVICE,
257619f02aeSEduardo Habkost     .parent        = TYPE_INTERFACE,
258619f02aeSEduardo Habkost };
259619f02aeSEduardo Habkost 
pcie_bus_class_init(ObjectClass * klass,void * data)2601c685a90SGreg Kurz static void pcie_bus_class_init(ObjectClass *klass, void *data)
2611c685a90SGreg Kurz {
2622f57db8aSDavid Gibson     BusClass *k = BUS_CLASS(klass);
2631c685a90SGreg Kurz 
2642f57db8aSDavid Gibson     k->realize = pcie_bus_realize;
2651c685a90SGreg Kurz }
2661c685a90SGreg Kurz 
2673a861c46SAlex Williamson static const TypeInfo pcie_bus_info = {
2683a861c46SAlex Williamson     .name = TYPE_PCIE_BUS,
2693a861c46SAlex Williamson     .parent = TYPE_PCI_BUS,
2701c685a90SGreg Kurz     .class_init = pcie_bus_class_init,
2713a861c46SAlex Williamson };
2723a861c46SAlex Williamson 
2734f8db871SBen Widawsky static const TypeInfo cxl_bus_info = {
2744f8db871SBen Widawsky     .name       = TYPE_CXL_BUS,
2754f8db871SBen Widawsky     .parent     = TYPE_PCIE_BUS,
2764f8db871SBen Widawsky     .class_init = pcie_bus_class_init,
2774f8db871SBen Widawsky };
2784f8db871SBen Widawsky 
279315a1350SMichael S. Tsirkin static void pci_update_mappings(PCIDevice *d);
280d98f08f5SMarcel Apfelbaum static void pci_irq_handler(void *opaque, int irq_num, int level);
281133e9b22SMarkus Armbruster static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
282315a1350SMichael S. Tsirkin static void pci_del_option_rom(PCIDevice *pdev);
283315a1350SMichael S. Tsirkin 
284315a1350SMichael S. Tsirkin static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
285315a1350SMichael S. Tsirkin static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
286315a1350SMichael S. Tsirkin 
287987b73b3SMarkus Armbruster PCIHostStateList pci_host_bridges;
288315a1350SMichael S. Tsirkin 
pci_bar(PCIDevice * d,int reg)289cf8c704dSMichael Roth int pci_bar(PCIDevice *d, int reg)
290315a1350SMichael S. Tsirkin {
291315a1350SMichael S. Tsirkin     uint8_t type;
292315a1350SMichael S. Tsirkin 
2937c0fa8dfSKnut Omang     /* PCIe virtual functions do not have their own BARs */
2947c0fa8dfSKnut Omang     assert(!pci_is_vf(d));
2957c0fa8dfSKnut Omang 
296315a1350SMichael S. Tsirkin     if (reg != PCI_ROM_SLOT)
297315a1350SMichael S. Tsirkin         return PCI_BASE_ADDRESS_0 + reg * 4;
298315a1350SMichael S. Tsirkin 
299315a1350SMichael S. Tsirkin     type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
300315a1350SMichael S. Tsirkin     return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
301315a1350SMichael S. Tsirkin }
302315a1350SMichael S. Tsirkin 
pci_irq_state(PCIDevice * d,int irq_num)303315a1350SMichael S. Tsirkin static inline int pci_irq_state(PCIDevice *d, int irq_num)
304315a1350SMichael S. Tsirkin {
305315a1350SMichael S. Tsirkin         return (d->irq_state >> irq_num) & 0x1;
306315a1350SMichael S. Tsirkin }
307315a1350SMichael S. Tsirkin 
pci_set_irq_state(PCIDevice * d,int irq_num,int level)308315a1350SMichael S. Tsirkin static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
309315a1350SMichael S. Tsirkin {
310315a1350SMichael S. Tsirkin         d->irq_state &= ~(0x1 << irq_num);
311315a1350SMichael S. Tsirkin         d->irq_state |= level << irq_num;
312315a1350SMichael S. Tsirkin }
313315a1350SMichael S. Tsirkin 
pci_bus_change_irq_level(PCIBus * bus,int irq_num,int change)314b06fe3e7SPhilippe Mathieu-Daudé static void pci_bus_change_irq_level(PCIBus *bus, int irq_num, int change)
315b06fe3e7SPhilippe Mathieu-Daudé {
316459ca8bfSMark Cave-Ayland     assert(irq_num >= 0);
317459ca8bfSMark Cave-Ayland     assert(irq_num < bus->nirq);
318b06fe3e7SPhilippe Mathieu-Daudé     bus->irq_count[irq_num] += change;
319b06fe3e7SPhilippe Mathieu-Daudé     bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
320b06fe3e7SPhilippe Mathieu-Daudé }
321b06fe3e7SPhilippe Mathieu-Daudé 
pci_change_irq_level(PCIDevice * pci_dev,int irq_num,int change)322315a1350SMichael S. Tsirkin static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
323315a1350SMichael S. Tsirkin {
324315a1350SMichael S. Tsirkin     PCIBus *bus;
325315a1350SMichael S. Tsirkin     for (;;) {
32628566eabSPhilippe Mathieu-Daudé         int dev_irq = irq_num;
327fd56e061SDavid Gibson         bus = pci_get_bus(pci_dev);
328f021f4e9SBernhard Beschow         assert(bus->map_irq);
329315a1350SMichael S. Tsirkin         irq_num = bus->map_irq(pci_dev, irq_num);
33028566eabSPhilippe Mathieu-Daudé         trace_pci_route_irq(dev_irq, DEVICE(pci_dev)->canonical_path, irq_num,
33128566eabSPhilippe Mathieu-Daudé                             pci_bus_is_root(bus) ? "root-complex"
33228566eabSPhilippe Mathieu-Daudé                                     : DEVICE(bus->parent_dev)->canonical_path);
333315a1350SMichael S. Tsirkin         if (bus->set_irq)
334315a1350SMichael S. Tsirkin             break;
335315a1350SMichael S. Tsirkin         pci_dev = bus->parent_dev;
336315a1350SMichael S. Tsirkin     }
337b06fe3e7SPhilippe Mathieu-Daudé     pci_bus_change_irq_level(bus, irq_num, change);
338315a1350SMichael S. Tsirkin }
339315a1350SMichael S. Tsirkin 
pci_bus_get_irq_level(PCIBus * bus,int irq_num)340315a1350SMichael S. Tsirkin int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
341315a1350SMichael S. Tsirkin {
342315a1350SMichael S. Tsirkin     assert(irq_num >= 0);
343315a1350SMichael S. Tsirkin     assert(irq_num < bus->nirq);
344315a1350SMichael S. Tsirkin     return !!bus->irq_count[irq_num];
345315a1350SMichael S. Tsirkin }
346315a1350SMichael S. Tsirkin 
347315a1350SMichael S. Tsirkin /* Update interrupt status bit in config space on interrupt
348315a1350SMichael S. Tsirkin  * state change. */
pci_update_irq_status(PCIDevice * dev)349315a1350SMichael S. Tsirkin static void pci_update_irq_status(PCIDevice *dev)
350315a1350SMichael S. Tsirkin {
351315a1350SMichael S. Tsirkin     if (dev->irq_state) {
352315a1350SMichael S. Tsirkin         dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
353315a1350SMichael S. Tsirkin     } else {
354315a1350SMichael S. Tsirkin         dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
355315a1350SMichael S. Tsirkin     }
356315a1350SMichael S. Tsirkin }
357315a1350SMichael S. Tsirkin 
pci_device_deassert_intx(PCIDevice * dev)358315a1350SMichael S. Tsirkin void pci_device_deassert_intx(PCIDevice *dev)
359315a1350SMichael S. Tsirkin {
360315a1350SMichael S. Tsirkin     int i;
361315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
362d98f08f5SMarcel Apfelbaum         pci_irq_handler(dev, i, 0);
363315a1350SMichael S. Tsirkin     }
364315a1350SMichael S. Tsirkin }
365315a1350SMichael S. Tsirkin 
pci_msi_trigger(PCIDevice * dev,MSIMessage msg)36608cf3dc6SJagannathan Raman static void pci_msi_trigger(PCIDevice *dev, MSIMessage msg)
36708cf3dc6SJagannathan Raman {
36808cf3dc6SJagannathan Raman     MemTxAttrs attrs = {};
36908cf3dc6SJagannathan Raman 
3706096cf78SDavid Woodhouse     /*
3716096cf78SDavid Woodhouse      * Xen uses the high bits of the address to contain some of the bits
3726096cf78SDavid Woodhouse      * of the PIRQ#. Therefore we can't just send the write cycle and
3736096cf78SDavid Woodhouse      * trust that it's caught by the APIC at 0xfee00000 because the
3746096cf78SDavid Woodhouse      * target of the write might be e.g. 0x0x1000fee46000 for PIRQ#4166.
3756096cf78SDavid Woodhouse      * So we intercept the delivery here instead of in kvm_send_msi().
3766096cf78SDavid Woodhouse      */
3776096cf78SDavid Woodhouse     if (xen_mode == XEN_EMULATE &&
3786096cf78SDavid Woodhouse         xen_evtchn_deliver_pirq_msi(msg.address, msg.data)) {
3796096cf78SDavid Woodhouse         return;
3806096cf78SDavid Woodhouse     }
38108cf3dc6SJagannathan Raman     attrs.requester_id = pci_requester_id(dev);
38208cf3dc6SJagannathan Raman     address_space_stl_le(&dev->bus_master_as, msg.address, msg.data,
38308cf3dc6SJagannathan Raman                          attrs, NULL);
38408cf3dc6SJagannathan Raman }
38508cf3dc6SJagannathan Raman 
pci_reset_regions(PCIDevice * dev)3867c0fa8dfSKnut Omang static void pci_reset_regions(PCIDevice *dev)
387315a1350SMichael S. Tsirkin {
388315a1350SMichael S. Tsirkin     int r;
3897c0fa8dfSKnut Omang     if (pci_is_vf(dev)) {
3907c0fa8dfSKnut Omang         return;
3917c0fa8dfSKnut Omang     }
392315a1350SMichael S. Tsirkin 
3937c0fa8dfSKnut Omang     for (r = 0; r < PCI_NUM_REGIONS; ++r) {
3947c0fa8dfSKnut Omang         PCIIORegion *region = &dev->io_regions[r];
3957c0fa8dfSKnut Omang         if (!region->size) {
3967c0fa8dfSKnut Omang             continue;
3977c0fa8dfSKnut Omang         }
3987c0fa8dfSKnut Omang 
3997c0fa8dfSKnut Omang         if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
4007c0fa8dfSKnut Omang             region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
4017c0fa8dfSKnut Omang             pci_set_quad(dev->config + pci_bar(dev, r), region->type);
4027c0fa8dfSKnut Omang         } else {
4037c0fa8dfSKnut Omang             pci_set_long(dev->config + pci_bar(dev, r), region->type);
4047c0fa8dfSKnut Omang         }
4057c0fa8dfSKnut Omang     }
4067c0fa8dfSKnut Omang }
4077c0fa8dfSKnut Omang 
pci_do_device_reset(PCIDevice * dev)4087c0fa8dfSKnut Omang static void pci_do_device_reset(PCIDevice *dev)
4097c0fa8dfSKnut Omang {
410315a1350SMichael S. Tsirkin     pci_device_deassert_intx(dev);
41158b59014SCole Robinson     assert(dev->irq_state == 0);
41258b59014SCole Robinson 
413315a1350SMichael S. Tsirkin     /* Clear all writable bits */
414315a1350SMichael S. Tsirkin     pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
415315a1350SMichael S. Tsirkin                                  pci_get_word(dev->wmask + PCI_COMMAND) |
416315a1350SMichael S. Tsirkin                                  pci_get_word(dev->w1cmask + PCI_COMMAND));
417315a1350SMichael S. Tsirkin     pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
418315a1350SMichael S. Tsirkin                                  pci_get_word(dev->wmask + PCI_STATUS) |
419315a1350SMichael S. Tsirkin                                  pci_get_word(dev->w1cmask + PCI_STATUS));
4207ff81d63SBALATON Zoltan     /* Some devices make bits of PCI_INTERRUPT_LINE read only */
4217ff81d63SBALATON Zoltan     pci_byte_test_and_clear_mask(dev->config + PCI_INTERRUPT_LINE,
4227ff81d63SBALATON Zoltan                               pci_get_word(dev->wmask + PCI_INTERRUPT_LINE) |
4237ff81d63SBALATON Zoltan                               pci_get_word(dev->w1cmask + PCI_INTERRUPT_LINE));
424315a1350SMichael S. Tsirkin     dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
4257c0fa8dfSKnut Omang     pci_reset_regions(dev);
426315a1350SMichael S. Tsirkin     pci_update_mappings(dev);
427315a1350SMichael S. Tsirkin 
428315a1350SMichael S. Tsirkin     msi_reset(dev);
429315a1350SMichael S. Tsirkin     msix_reset(dev);
4301a909e3dSAkihiko Odaki     pcie_sriov_pf_reset(dev);
431315a1350SMichael S. Tsirkin }
432315a1350SMichael S. Tsirkin 
433315a1350SMichael S. Tsirkin /*
434dcc20931SPaolo Bonzini  * This function is called on #RST and FLR.
435dcc20931SPaolo Bonzini  * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
436315a1350SMichael S. Tsirkin  */
pci_device_reset(PCIDevice * dev)437dcc20931SPaolo Bonzini void pci_device_reset(PCIDevice *dev)
438dcc20931SPaolo Bonzini {
43978e4d5cbSPeter Maydell     device_cold_reset(&dev->qdev);
440dcc20931SPaolo Bonzini     pci_do_device_reset(dev);
441dcc20931SPaolo Bonzini }
442dcc20931SPaolo Bonzini 
443dcc20931SPaolo Bonzini /*
444dcc20931SPaolo Bonzini  * Trigger pci bus reset under a given bus.
44578e4d5cbSPeter Maydell  * Called via bus_cold_reset on RST# assert, after the devices
44678e4d5cbSPeter Maydell  * have been reset device_cold_reset-ed already.
447dcc20931SPaolo Bonzini  */
pcibus_reset_hold(Object * obj,ResetType type)448ad80e367SPeter Maydell static void pcibus_reset_hold(Object *obj, ResetType type)
449315a1350SMichael S. Tsirkin {
450e6c03989SPeter Maydell     PCIBus *bus = PCI_BUS(obj);
451315a1350SMichael S. Tsirkin     int i;
452315a1350SMichael S. Tsirkin 
453315a1350SMichael S. Tsirkin     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
454315a1350SMichael S. Tsirkin         if (bus->devices[i]) {
455dcc20931SPaolo Bonzini             pci_do_device_reset(bus->devices[i]);
456315a1350SMichael S. Tsirkin         }
457315a1350SMichael S. Tsirkin     }
458315a1350SMichael S. Tsirkin 
4599bdbbfc3SPaolo Bonzini     for (i = 0; i < bus->nirq; i++) {
4609bdbbfc3SPaolo Bonzini         assert(bus->irq_count[i] == 0);
4619bdbbfc3SPaolo Bonzini     }
462315a1350SMichael S. Tsirkin }
463315a1350SMichael S. Tsirkin 
pci_host_bus_register(DeviceState * host)4643dbc01aeSCao jin static void pci_host_bus_register(DeviceState *host)
465315a1350SMichael S. Tsirkin {
4663dbc01aeSCao jin     PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
4677588e2b0SDavid Gibson 
4687588e2b0SDavid Gibson     QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
469315a1350SMichael S. Tsirkin }
470315a1350SMichael S. Tsirkin 
pci_host_bus_unregister(DeviceState * host)471c13ee169SMichael Roth static void pci_host_bus_unregister(DeviceState *host)
472c13ee169SMichael Roth {
473c13ee169SMichael Roth     PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
474c13ee169SMichael Roth 
475c13ee169SMichael Roth     QLIST_REMOVE(host_bridge, next);
476c13ee169SMichael Roth }
477c13ee169SMichael Roth 
pci_device_root_bus(const PCIDevice * d)478c473d18dSDavid Gibson PCIBus *pci_device_root_bus(const PCIDevice *d)
479315a1350SMichael S. Tsirkin {
480fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(d);
481315a1350SMichael S. Tsirkin 
482ce6a28eeSMarcel Apfelbaum     while (!pci_bus_is_root(bus)) {
483ce6a28eeSMarcel Apfelbaum         d = bus->parent_dev;
484ce6a28eeSMarcel Apfelbaum         assert(d != NULL);
485ce6a28eeSMarcel Apfelbaum 
486fd56e061SDavid Gibson         bus = pci_get_bus(d);
487315a1350SMichael S. Tsirkin     }
488315a1350SMichael S. Tsirkin 
489c473d18dSDavid Gibson     return bus;
490315a1350SMichael S. Tsirkin }
491315a1350SMichael S. Tsirkin 
pci_root_bus_path(PCIDevice * dev)492568f0690SDavid Gibson const char *pci_root_bus_path(PCIDevice *dev)
493c473d18dSDavid Gibson {
494568f0690SDavid Gibson     PCIBus *rootbus = pci_device_root_bus(dev);
495568f0690SDavid Gibson     PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
496568f0690SDavid Gibson     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
497c473d18dSDavid Gibson 
498568f0690SDavid Gibson     assert(host_bridge->bus == rootbus);
499568f0690SDavid Gibson 
500568f0690SDavid Gibson     if (hc->root_bus_path) {
501568f0690SDavid Gibson         return (*hc->root_bus_path)(host_bridge, rootbus);
502315a1350SMichael S. Tsirkin     }
503315a1350SMichael S. Tsirkin 
504568f0690SDavid Gibson     return rootbus->qbus.name;
505315a1350SMichael S. Tsirkin }
506315a1350SMichael S. Tsirkin 
pci_bus_bypass_iommu(PCIBus * bus)5072d64b7bbSXingang Wang bool pci_bus_bypass_iommu(PCIBus *bus)
5082d64b7bbSXingang Wang {
5092d64b7bbSXingang Wang     PCIBus *rootbus = bus;
5102d64b7bbSXingang Wang     PCIHostState *host_bridge;
5112d64b7bbSXingang Wang 
5122d64b7bbSXingang Wang     if (!pci_bus_is_root(bus)) {
5132d64b7bbSXingang Wang         rootbus = pci_device_root_bus(bus->parent_dev);
5142d64b7bbSXingang Wang     }
5152d64b7bbSXingang Wang 
5162d64b7bbSXingang Wang     host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
5172d64b7bbSXingang Wang 
5182d64b7bbSXingang Wang     assert(host_bridge->bus == rootbus);
5192d64b7bbSXingang Wang 
5202d64b7bbSXingang Wang     return host_bridge->bypass_iommu;
5212d64b7bbSXingang Wang }
5222d64b7bbSXingang Wang 
pci_root_bus_internal_init(PCIBus * bus,DeviceState * parent,MemoryRegion * mem,MemoryRegion * io,uint8_t devfn_min)5238d4cdf01SPeter Maydell static void pci_root_bus_internal_init(PCIBus *bus, DeviceState *parent,
52449909a0dSPhilippe Mathieu-Daudé                                        MemoryRegion *mem, MemoryRegion *io,
525315a1350SMichael S. Tsirkin                                        uint8_t devfn_min)
526315a1350SMichael S. Tsirkin {
527315a1350SMichael S. Tsirkin     assert(PCI_FUNC(devfn_min) == 0);
528315a1350SMichael S. Tsirkin     bus->devfn_min = devfn_min;
5298b884984SMark Cave-Ayland     bus->slot_reserved_mask = 0x0;
53049909a0dSPhilippe Mathieu-Daudé     bus->address_space_mem = mem;
53149909a0dSPhilippe Mathieu-Daudé     bus->address_space_io = io;
532b0e5196aSDavid Gibson     bus->flags |= PCI_BUS_IS_ROOT;
533315a1350SMichael S. Tsirkin 
534315a1350SMichael S. Tsirkin     /* host bridge */
535315a1350SMichael S. Tsirkin     QLIST_INIT(&bus->child);
5362b8cc89aSDavid Gibson 
5373dbc01aeSCao jin     pci_host_bus_register(parent);
538315a1350SMichael S. Tsirkin }
539315a1350SMichael S. Tsirkin 
pci_bus_uninit(PCIBus * bus)540c13ee169SMichael Roth static void pci_bus_uninit(PCIBus *bus)
541c13ee169SMichael Roth {
542c13ee169SMichael Roth     pci_host_bus_unregister(BUS(bus)->parent);
543c13ee169SMichael Roth }
544c13ee169SMichael Roth 
pci_bus_is_express(const PCIBus * bus)545c6f16471SIgor Mammedov bool pci_bus_is_express(const PCIBus *bus)
5468c0bf9e2SAlex Williamson {
5478c0bf9e2SAlex Williamson     return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
5488c0bf9e2SAlex Williamson }
5498c0bf9e2SAlex Williamson 
pci_root_bus_init(PCIBus * bus,size_t bus_size,DeviceState * parent,const char * name,MemoryRegion * mem,MemoryRegion * io,uint8_t devfn_min,const char * typename)5508d4cdf01SPeter Maydell void pci_root_bus_init(PCIBus *bus, size_t bus_size, DeviceState *parent,
5514fec6404SPaolo Bonzini                        const char *name,
55249909a0dSPhilippe Mathieu-Daudé                        MemoryRegion *mem, MemoryRegion *io,
55360a0e443SAlex Williamson                        uint8_t devfn_min, const char *typename)
5544fec6404SPaolo Bonzini {
555d637e1dcSPeter Maydell     qbus_init(bus, bus_size, typename, parent, name);
55649909a0dSPhilippe Mathieu-Daudé     pci_root_bus_internal_init(bus, parent, mem, io, devfn_min);
5574fec6404SPaolo Bonzini }
5584fec6404SPaolo Bonzini 
pci_root_bus_new(DeviceState * parent,const char * name,MemoryRegion * mem,MemoryRegion * io,uint8_t devfn_min,const char * typename)5591115ff6dSDavid Gibson PCIBus *pci_root_bus_new(DeviceState *parent, const char *name,
56049909a0dSPhilippe Mathieu-Daudé                          MemoryRegion *mem, MemoryRegion *io,
56160a0e443SAlex Williamson                          uint8_t devfn_min, const char *typename)
562315a1350SMichael S. Tsirkin {
563315a1350SMichael S. Tsirkin     PCIBus *bus;
564315a1350SMichael S. Tsirkin 
5659388d170SPeter Maydell     bus = PCI_BUS(qbus_new(typename, parent, name));
56649909a0dSPhilippe Mathieu-Daudé     pci_root_bus_internal_init(bus, parent, mem, io, devfn_min);
567315a1350SMichael S. Tsirkin     return bus;
568315a1350SMichael S. Tsirkin }
569315a1350SMichael S. Tsirkin 
pci_root_bus_cleanup(PCIBus * bus)570c13ee169SMichael Roth void pci_root_bus_cleanup(PCIBus *bus)
571c13ee169SMichael Roth {
572c13ee169SMichael Roth     pci_bus_uninit(bus);
57307578b0aSDavid Hildenbrand     /* the caller of the unplug hotplug handler will delete this device */
574f1483b46SMarkus Armbruster     qbus_unrealize(BUS(bus));
575c13ee169SMichael Roth }
576c13ee169SMichael Roth 
pci_bus_irqs(PCIBus * bus,pci_set_irq_fn set_irq,void * irq_opaque,int nirq)577f021f4e9SBernhard Beschow void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq,
578315a1350SMichael S. Tsirkin                   void *irq_opaque, int nirq)
579315a1350SMichael S. Tsirkin {
580315a1350SMichael S. Tsirkin     bus->set_irq = set_irq;
581315a1350SMichael S. Tsirkin     bus->irq_opaque = irq_opaque;
582315a1350SMichael S. Tsirkin     bus->nirq = nirq;
583c0b59416SBernhard Beschow     g_free(bus->irq_count);
584315a1350SMichael S. Tsirkin     bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
585315a1350SMichael S. Tsirkin }
586315a1350SMichael S. Tsirkin 
pci_bus_map_irqs(PCIBus * bus,pci_map_irq_fn map_irq)587f021f4e9SBernhard Beschow void pci_bus_map_irqs(PCIBus *bus, pci_map_irq_fn map_irq)
588f021f4e9SBernhard Beschow {
589f021f4e9SBernhard Beschow     bus->map_irq = map_irq;
590f021f4e9SBernhard Beschow }
591f021f4e9SBernhard Beschow 
pci_bus_irqs_cleanup(PCIBus * bus)592c13ee169SMichael Roth void pci_bus_irqs_cleanup(PCIBus *bus)
593c13ee169SMichael Roth {
594c13ee169SMichael Roth     bus->set_irq = NULL;
595c13ee169SMichael Roth     bus->map_irq = NULL;
596c13ee169SMichael Roth     bus->irq_opaque = NULL;
597c13ee169SMichael Roth     bus->nirq = 0;
598c13ee169SMichael Roth     g_free(bus->irq_count);
599c0b59416SBernhard Beschow     bus->irq_count = NULL;
600c13ee169SMichael Roth }
601c13ee169SMichael Roth 
pci_register_root_bus(DeviceState * parent,const char * name,pci_set_irq_fn set_irq,pci_map_irq_fn map_irq,void * irq_opaque,MemoryRegion * mem,MemoryRegion * io,uint8_t devfn_min,int nirq,const char * typename)6021115ff6dSDavid Gibson PCIBus *pci_register_root_bus(DeviceState *parent, const char *name,
603315a1350SMichael S. Tsirkin                               pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
604315a1350SMichael S. Tsirkin                               void *irq_opaque,
60549909a0dSPhilippe Mathieu-Daudé                               MemoryRegion *mem, MemoryRegion *io,
6061115ff6dSDavid Gibson                               uint8_t devfn_min, int nirq,
6071115ff6dSDavid Gibson                               const char *typename)
608315a1350SMichael S. Tsirkin {
609315a1350SMichael S. Tsirkin     PCIBus *bus;
610315a1350SMichael S. Tsirkin 
61149909a0dSPhilippe Mathieu-Daudé     bus = pci_root_bus_new(parent, name, mem, io, devfn_min, typename);
612f021f4e9SBernhard Beschow     pci_bus_irqs(bus, set_irq, irq_opaque, nirq);
613f021f4e9SBernhard Beschow     pci_bus_map_irqs(bus, map_irq);
614315a1350SMichael S. Tsirkin     return bus;
615315a1350SMichael S. Tsirkin }
616315a1350SMichael S. Tsirkin 
pci_unregister_root_bus(PCIBus * bus)617c13ee169SMichael Roth void pci_unregister_root_bus(PCIBus *bus)
618c13ee169SMichael Roth {
619c13ee169SMichael Roth     pci_bus_irqs_cleanup(bus);
620c13ee169SMichael Roth     pci_root_bus_cleanup(bus);
621c13ee169SMichael Roth }
622c13ee169SMichael Roth 
pci_bus_num(PCIBus * s)623315a1350SMichael S. Tsirkin int pci_bus_num(PCIBus *s)
624315a1350SMichael S. Tsirkin {
625602141d9SMarcel Apfelbaum     return PCI_BUS_GET_CLASS(s)->bus_num(s);
626315a1350SMichael S. Tsirkin }
627315a1350SMichael S. Tsirkin 
628500db1daSXingang Wang /* Returns the min and max bus numbers of a PCI bus hierarchy */
pci_bus_range(PCIBus * bus,int * min_bus,int * max_bus)629500db1daSXingang Wang void pci_bus_range(PCIBus *bus, int *min_bus, int *max_bus)
630500db1daSXingang Wang {
631500db1daSXingang Wang     int i;
632500db1daSXingang Wang     *min_bus = *max_bus = pci_bus_num(bus);
633500db1daSXingang Wang 
634500db1daSXingang Wang     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
635500db1daSXingang Wang         PCIDevice *dev = bus->devices[i];
636500db1daSXingang Wang 
637ad494274SIgor Mammedov         if (dev && IS_PCI_BRIDGE(dev)) {
638500db1daSXingang Wang             *min_bus = MIN(*min_bus, dev->config[PCI_SECONDARY_BUS]);
639500db1daSXingang Wang             *max_bus = MAX(*max_bus, dev->config[PCI_SUBORDINATE_BUS]);
640500db1daSXingang Wang         }
641500db1daSXingang Wang     }
642500db1daSXingang Wang }
643500db1daSXingang Wang 
pci_bus_numa_node(PCIBus * bus)6446a3042b2SMarcel Apfelbaum int pci_bus_numa_node(PCIBus *bus)
6456a3042b2SMarcel Apfelbaum {
6466a3042b2SMarcel Apfelbaum     return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
647315a1350SMichael S. Tsirkin }
648315a1350SMichael S. Tsirkin 
get_pci_config_device(QEMUFile * f,void * pv,size_t size,const VMStateField * field)6492c21ee76SJianjun Duan static int get_pci_config_device(QEMUFile *f, void *pv, size_t size,
65003fee66fSMarc-André Lureau                                  const VMStateField *field)
651315a1350SMichael S. Tsirkin {
652315a1350SMichael S. Tsirkin     PCIDevice *s = container_of(pv, PCIDevice, config);
653315a1350SMichael S. Tsirkin     uint8_t *config;
654315a1350SMichael S. Tsirkin     int i;
655315a1350SMichael S. Tsirkin 
656315a1350SMichael S. Tsirkin     assert(size == pci_config_size(s));
657315a1350SMichael S. Tsirkin     config = g_malloc(size);
658315a1350SMichael S. Tsirkin 
659315a1350SMichael S. Tsirkin     qemu_get_buffer(f, config, size);
660315a1350SMichael S. Tsirkin     for (i = 0; i < size; ++i) {
661315a1350SMichael S. Tsirkin         if ((config[i] ^ s->config[i]) &
662315a1350SMichael S. Tsirkin             s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
6637c59364dSDr. David Alan Gilbert             error_report("%s: Bad config data: i=0x%x read: %x device: %x "
6647c59364dSDr. David Alan Gilbert                          "cmask: %x wmask: %x w1cmask:%x", __func__,
6657c59364dSDr. David Alan Gilbert                          i, config[i], s->config[i],
6667c59364dSDr. David Alan Gilbert                          s->cmask[i], s->wmask[i], s->w1cmask[i]);
667315a1350SMichael S. Tsirkin             g_free(config);
668315a1350SMichael S. Tsirkin             return -EINVAL;
669315a1350SMichael S. Tsirkin         }
670315a1350SMichael S. Tsirkin     }
671315a1350SMichael S. Tsirkin     memcpy(s->config, config, size);
672315a1350SMichael S. Tsirkin 
673315a1350SMichael S. Tsirkin     pci_update_mappings(s);
674ad494274SIgor Mammedov     if (IS_PCI_BRIDGE(s)) {
675ad494274SIgor Mammedov         pci_bridge_update_mappings(PCI_BRIDGE(s));
676e78e9ae4SDon Koch     }
677315a1350SMichael S. Tsirkin 
678315a1350SMichael S. Tsirkin     memory_region_set_enabled(&s->bus_master_enable_region,
679315a1350SMichael S. Tsirkin                               pci_get_word(s->config + PCI_COMMAND)
680315a1350SMichael S. Tsirkin                               & PCI_COMMAND_MASTER);
681315a1350SMichael S. Tsirkin 
682315a1350SMichael S. Tsirkin     g_free(config);
683315a1350SMichael S. Tsirkin     return 0;
684315a1350SMichael S. Tsirkin }
685315a1350SMichael S. Tsirkin 
686315a1350SMichael S. Tsirkin /* just put buffer */
put_pci_config_device(QEMUFile * f,void * pv,size_t size,const VMStateField * field,JSONWriter * vmdesc)6872c21ee76SJianjun Duan static int put_pci_config_device(QEMUFile *f, void *pv, size_t size,
6883ddba9a9SMarkus Armbruster                                  const VMStateField *field, JSONWriter *vmdesc)
689315a1350SMichael S. Tsirkin {
690315a1350SMichael S. Tsirkin     const uint8_t **v = pv;
691315a1350SMichael S. Tsirkin     assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
692315a1350SMichael S. Tsirkin     qemu_put_buffer(f, *v, size);
6932c21ee76SJianjun Duan 
6942c21ee76SJianjun Duan     return 0;
695315a1350SMichael S. Tsirkin }
696315a1350SMichael S. Tsirkin 
6978e5e0890SRichard Henderson static const VMStateInfo vmstate_info_pci_config = {
698315a1350SMichael S. Tsirkin     .name = "pci config",
699315a1350SMichael S. Tsirkin     .get  = get_pci_config_device,
700315a1350SMichael S. Tsirkin     .put  = put_pci_config_device,
701315a1350SMichael S. Tsirkin };
702315a1350SMichael S. Tsirkin 
get_pci_irq_state(QEMUFile * f,void * pv,size_t size,const VMStateField * field)7032c21ee76SJianjun Duan static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size,
70403fee66fSMarc-André Lureau                              const VMStateField *field)
705315a1350SMichael S. Tsirkin {
706315a1350SMichael S. Tsirkin     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
707315a1350SMichael S. Tsirkin     uint32_t irq_state[PCI_NUM_PINS];
708315a1350SMichael S. Tsirkin     int i;
709315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
710315a1350SMichael S. Tsirkin         irq_state[i] = qemu_get_be32(f);
711315a1350SMichael S. Tsirkin         if (irq_state[i] != 0x1 && irq_state[i] != 0) {
712315a1350SMichael S. Tsirkin             fprintf(stderr, "irq state %d: must be 0 or 1.\n",
713315a1350SMichael S. Tsirkin                     irq_state[i]);
714315a1350SMichael S. Tsirkin             return -EINVAL;
715315a1350SMichael S. Tsirkin         }
716315a1350SMichael S. Tsirkin     }
717315a1350SMichael S. Tsirkin 
718315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
719315a1350SMichael S. Tsirkin         pci_set_irq_state(s, i, irq_state[i]);
720315a1350SMichael S. Tsirkin     }
721315a1350SMichael S. Tsirkin 
722315a1350SMichael S. Tsirkin     return 0;
723315a1350SMichael S. Tsirkin }
724315a1350SMichael S. Tsirkin 
put_pci_irq_state(QEMUFile * f,void * pv,size_t size,const VMStateField * field,JSONWriter * vmdesc)7252c21ee76SJianjun Duan static int put_pci_irq_state(QEMUFile *f, void *pv, size_t size,
7263ddba9a9SMarkus Armbruster                              const VMStateField *field, JSONWriter *vmdesc)
727315a1350SMichael S. Tsirkin {
728315a1350SMichael S. Tsirkin     int i;
729315a1350SMichael S. Tsirkin     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
730315a1350SMichael S. Tsirkin 
731315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
732315a1350SMichael S. Tsirkin         qemu_put_be32(f, pci_irq_state(s, i));
733315a1350SMichael S. Tsirkin     }
7342c21ee76SJianjun Duan 
7352c21ee76SJianjun Duan     return 0;
736315a1350SMichael S. Tsirkin }
737315a1350SMichael S. Tsirkin 
7388e5e0890SRichard Henderson static const VMStateInfo vmstate_info_pci_irq_state = {
739315a1350SMichael S. Tsirkin     .name = "pci irq state",
740315a1350SMichael S. Tsirkin     .get  = get_pci_irq_state,
741315a1350SMichael S. Tsirkin     .put  = put_pci_irq_state,
742315a1350SMichael S. Tsirkin };
743315a1350SMichael S. Tsirkin 
migrate_is_pcie(void * opaque,int version_id)74420daa90aSDr. David Alan Gilbert static bool migrate_is_pcie(void *opaque, int version_id)
74520daa90aSDr. David Alan Gilbert {
74620daa90aSDr. David Alan Gilbert     return pci_is_express((PCIDevice *)opaque);
74720daa90aSDr. David Alan Gilbert }
74820daa90aSDr. David Alan Gilbert 
migrate_is_not_pcie(void * opaque,int version_id)74920daa90aSDr. David Alan Gilbert static bool migrate_is_not_pcie(void *opaque, int version_id)
75020daa90aSDr. David Alan Gilbert {
75120daa90aSDr. David Alan Gilbert     return !pci_is_express((PCIDevice *)opaque);
75220daa90aSDr. David Alan Gilbert }
75320daa90aSDr. David Alan Gilbert 
754315a1350SMichael S. Tsirkin const VMStateDescription vmstate_pci_device = {
755315a1350SMichael S. Tsirkin     .name = "PCIDevice",
756315a1350SMichael S. Tsirkin     .version_id = 2,
757315a1350SMichael S. Tsirkin     .minimum_version_id = 1,
7588e5e0890SRichard Henderson     .fields = (const VMStateField[]) {
7593476436aSMichael S. Tsirkin         VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
76020daa90aSDr. David Alan Gilbert         VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
76120daa90aSDr. David Alan Gilbert                                    migrate_is_not_pcie,
76220daa90aSDr. David Alan Gilbert                                    0, vmstate_info_pci_config,
763315a1350SMichael S. Tsirkin                                    PCI_CONFIG_SPACE_SIZE),
76420daa90aSDr. David Alan Gilbert         VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
76520daa90aSDr. David Alan Gilbert                                    migrate_is_pcie,
76620daa90aSDr. David Alan Gilbert                                    0, vmstate_info_pci_config,
767315a1350SMichael S. Tsirkin                                    PCIE_CONFIG_SPACE_SIZE),
768315a1350SMichael S. Tsirkin         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
769315a1350SMichael S. Tsirkin                                    vmstate_info_pci_irq_state,
770315a1350SMichael S. Tsirkin                                    PCI_NUM_PINS * sizeof(int32_t)),
771315a1350SMichael S. Tsirkin         VMSTATE_END_OF_LIST()
772315a1350SMichael S. Tsirkin     }
773315a1350SMichael S. Tsirkin };
774315a1350SMichael S. Tsirkin 
775315a1350SMichael S. Tsirkin 
pci_device_save(PCIDevice * s,QEMUFile * f)776315a1350SMichael S. Tsirkin void pci_device_save(PCIDevice *s, QEMUFile *f)
777315a1350SMichael S. Tsirkin {
778315a1350SMichael S. Tsirkin     /* Clear interrupt status bit: it is implicit
779315a1350SMichael S. Tsirkin      * in irq_state which we are saving.
780315a1350SMichael S. Tsirkin      * This makes us compatible with old devices
781315a1350SMichael S. Tsirkin      * which never set or clear this bit. */
782315a1350SMichael S. Tsirkin     s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
78320daa90aSDr. David Alan Gilbert     vmstate_save_state(f, &vmstate_pci_device, s, NULL);
784315a1350SMichael S. Tsirkin     /* Restore the interrupt status bit. */
785315a1350SMichael S. Tsirkin     pci_update_irq_status(s);
786315a1350SMichael S. Tsirkin }
787315a1350SMichael S. Tsirkin 
pci_device_load(PCIDevice * s,QEMUFile * f)788315a1350SMichael S. Tsirkin int pci_device_load(PCIDevice *s, QEMUFile *f)
789315a1350SMichael S. Tsirkin {
790315a1350SMichael S. Tsirkin     int ret;
79120daa90aSDr. David Alan Gilbert     ret = vmstate_load_state(f, &vmstate_pci_device, s, s->version_id);
792315a1350SMichael S. Tsirkin     /* Restore the interrupt status bit. */
793315a1350SMichael S. Tsirkin     pci_update_irq_status(s);
794315a1350SMichael S. Tsirkin     return ret;
795315a1350SMichael S. Tsirkin }
796315a1350SMichael S. Tsirkin 
pci_set_default_subsystem_id(PCIDevice * pci_dev)797315a1350SMichael S. Tsirkin static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
798315a1350SMichael S. Tsirkin {
799315a1350SMichael S. Tsirkin     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
800315a1350SMichael S. Tsirkin                  pci_default_sub_vendor_id);
801315a1350SMichael S. Tsirkin     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
802315a1350SMichael S. Tsirkin                  pci_default_sub_device_id);
803315a1350SMichael S. Tsirkin }
804315a1350SMichael S. Tsirkin 
805315a1350SMichael S. Tsirkin /*
806315a1350SMichael S. Tsirkin  * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
807315a1350SMichael S. Tsirkin  *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
808315a1350SMichael S. Tsirkin  */
pci_parse_devaddr(const char * addr,int * domp,int * busp,unsigned int * slotp,unsigned int * funcp)8096dbcb819SMarkus Armbruster static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
810315a1350SMichael S. Tsirkin                              unsigned int *slotp, unsigned int *funcp)
811315a1350SMichael S. Tsirkin {
812315a1350SMichael S. Tsirkin     const char *p;
813315a1350SMichael S. Tsirkin     char *e;
814315a1350SMichael S. Tsirkin     unsigned long val;
815315a1350SMichael S. Tsirkin     unsigned long dom = 0, bus = 0;
816315a1350SMichael S. Tsirkin     unsigned int slot = 0;
817315a1350SMichael S. Tsirkin     unsigned int func = 0;
818315a1350SMichael S. Tsirkin 
819315a1350SMichael S. Tsirkin     p = addr;
820315a1350SMichael S. Tsirkin     val = strtoul(p, &e, 16);
821315a1350SMichael S. Tsirkin     if (e == p)
822315a1350SMichael S. Tsirkin         return -1;
823315a1350SMichael S. Tsirkin     if (*e == ':') {
824315a1350SMichael S. Tsirkin         bus = val;
825315a1350SMichael S. Tsirkin         p = e + 1;
826315a1350SMichael S. Tsirkin         val = strtoul(p, &e, 16);
827315a1350SMichael S. Tsirkin         if (e == p)
828315a1350SMichael S. Tsirkin             return -1;
829315a1350SMichael S. Tsirkin         if (*e == ':') {
830315a1350SMichael S. Tsirkin             dom = bus;
831315a1350SMichael S. Tsirkin             bus = val;
832315a1350SMichael S. Tsirkin             p = e + 1;
833315a1350SMichael S. Tsirkin             val = strtoul(p, &e, 16);
834315a1350SMichael S. Tsirkin             if (e == p)
835315a1350SMichael S. Tsirkin                 return -1;
836315a1350SMichael S. Tsirkin         }
837315a1350SMichael S. Tsirkin     }
838315a1350SMichael S. Tsirkin 
839315a1350SMichael S. Tsirkin     slot = val;
840315a1350SMichael S. Tsirkin 
841315a1350SMichael S. Tsirkin     if (funcp != NULL) {
842315a1350SMichael S. Tsirkin         if (*e != '.')
843315a1350SMichael S. Tsirkin             return -1;
844315a1350SMichael S. Tsirkin 
845315a1350SMichael S. Tsirkin         p = e + 1;
846315a1350SMichael S. Tsirkin         val = strtoul(p, &e, 16);
847315a1350SMichael S. Tsirkin         if (e == p)
848315a1350SMichael S. Tsirkin             return -1;
849315a1350SMichael S. Tsirkin 
850315a1350SMichael S. Tsirkin         func = val;
851315a1350SMichael S. Tsirkin     }
852315a1350SMichael S. Tsirkin 
853315a1350SMichael S. Tsirkin     /* if funcp == NULL func is 0 */
854315a1350SMichael S. Tsirkin     if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
855315a1350SMichael S. Tsirkin         return -1;
856315a1350SMichael S. Tsirkin 
857315a1350SMichael S. Tsirkin     if (*e)
858315a1350SMichael S. Tsirkin         return -1;
859315a1350SMichael S. Tsirkin 
860315a1350SMichael S. Tsirkin     *domp = dom;
861315a1350SMichael S. Tsirkin     *busp = bus;
862315a1350SMichael S. Tsirkin     *slotp = slot;
863315a1350SMichael S. Tsirkin     if (funcp != NULL)
864315a1350SMichael S. Tsirkin         *funcp = func;
865315a1350SMichael S. Tsirkin     return 0;
866315a1350SMichael S. Tsirkin }
867315a1350SMichael S. Tsirkin 
pci_init_cmask(PCIDevice * dev)868315a1350SMichael S. Tsirkin static void pci_init_cmask(PCIDevice *dev)
869315a1350SMichael S. Tsirkin {
870315a1350SMichael S. Tsirkin     pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
871315a1350SMichael S. Tsirkin     pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
872315a1350SMichael S. Tsirkin     dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
873315a1350SMichael S. Tsirkin     dev->cmask[PCI_REVISION_ID] = 0xff;
874315a1350SMichael S. Tsirkin     dev->cmask[PCI_CLASS_PROG] = 0xff;
875315a1350SMichael S. Tsirkin     pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
876315a1350SMichael S. Tsirkin     dev->cmask[PCI_HEADER_TYPE] = 0xff;
877315a1350SMichael S. Tsirkin     dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
878315a1350SMichael S. Tsirkin }
879315a1350SMichael S. Tsirkin 
pci_init_wmask(PCIDevice * dev)880315a1350SMichael S. Tsirkin static void pci_init_wmask(PCIDevice *dev)
881315a1350SMichael S. Tsirkin {
882315a1350SMichael S. Tsirkin     int config_size = pci_config_size(dev);
883315a1350SMichael S. Tsirkin 
884315a1350SMichael S. Tsirkin     dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
885315a1350SMichael S. Tsirkin     dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
886315a1350SMichael S. Tsirkin     pci_set_word(dev->wmask + PCI_COMMAND,
887315a1350SMichael S. Tsirkin                  PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
888315a1350SMichael S. Tsirkin                  PCI_COMMAND_INTX_DISABLE);
889315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
890315a1350SMichael S. Tsirkin 
891315a1350SMichael S. Tsirkin     memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
892315a1350SMichael S. Tsirkin            config_size - PCI_CONFIG_HEADER_SIZE);
893315a1350SMichael S. Tsirkin }
894315a1350SMichael S. Tsirkin 
pci_init_w1cmask(PCIDevice * dev)895315a1350SMichael S. Tsirkin static void pci_init_w1cmask(PCIDevice *dev)
896315a1350SMichael S. Tsirkin {
897315a1350SMichael S. Tsirkin     /*
898315a1350SMichael S. Tsirkin      * Note: It's okay to set w1cmask even for readonly bits as
899315a1350SMichael S. Tsirkin      * long as their value is hardwired to 0.
900315a1350SMichael S. Tsirkin      */
901315a1350SMichael S. Tsirkin     pci_set_word(dev->w1cmask + PCI_STATUS,
902315a1350SMichael S. Tsirkin                  PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
903315a1350SMichael S. Tsirkin                  PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
904315a1350SMichael S. Tsirkin                  PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
905315a1350SMichael S. Tsirkin }
906315a1350SMichael S. Tsirkin 
pci_init_mask_bridge(PCIDevice * d)907315a1350SMichael S. Tsirkin static void pci_init_mask_bridge(PCIDevice *d)
908315a1350SMichael S. Tsirkin {
909315a1350SMichael S. Tsirkin     /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
9104565917bSMichael S. Tsirkin        PCI_SEC_LATENCY_TIMER */
911315a1350SMichael S. Tsirkin     memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
912315a1350SMichael S. Tsirkin 
913315a1350SMichael S. Tsirkin     /* base and limit */
914315a1350SMichael S. Tsirkin     d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
915315a1350SMichael S. Tsirkin     d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
916315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_MEMORY_BASE,
917315a1350SMichael S. Tsirkin                  PCI_MEMORY_RANGE_MASK & 0xffff);
918315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
919315a1350SMichael S. Tsirkin                  PCI_MEMORY_RANGE_MASK & 0xffff);
920315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
921315a1350SMichael S. Tsirkin                  PCI_PREF_RANGE_MASK & 0xffff);
922315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
923315a1350SMichael S. Tsirkin                  PCI_PREF_RANGE_MASK & 0xffff);
924315a1350SMichael S. Tsirkin 
925315a1350SMichael S. Tsirkin     /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
926315a1350SMichael S. Tsirkin     memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
927315a1350SMichael S. Tsirkin 
928315a1350SMichael S. Tsirkin     /* Supported memory and i/o types */
929315a1350SMichael S. Tsirkin     d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
930315a1350SMichael S. Tsirkin     d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
931315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
932315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_64);
933315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
934315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_64);
935315a1350SMichael S. Tsirkin 
936ba7d8515SAlex Williamson     /*
937ba7d8515SAlex Williamson      * TODO: Bridges default to 10-bit VGA decoding but we currently only
938ba7d8515SAlex Williamson      * implement 16-bit decoding (no alias support).
939ba7d8515SAlex Williamson      */
940315a1350SMichael S. Tsirkin     pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
941315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_PARITY |
942315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_SERR |
943315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_ISA |
944315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_VGA |
945315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_VGA_16BIT |
946315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_MASTER_ABORT |
947315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_BUS_RESET |
948315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_FAST_BACK |
949315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_DISCARD |
950315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_SEC_DISCARD |
951315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_DISCARD_SERR);
952315a1350SMichael S. Tsirkin     /* Below does not do anything as we never set this bit, put here for
953315a1350SMichael S. Tsirkin      * completeness. */
954315a1350SMichael S. Tsirkin     pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
955315a1350SMichael S. Tsirkin                  PCI_BRIDGE_CTL_DISCARD_STATUS);
956315a1350SMichael S. Tsirkin     d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
957315a1350SMichael S. Tsirkin     d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
958315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
959315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_MASK);
960315a1350SMichael S. Tsirkin     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
961315a1350SMichael S. Tsirkin                                PCI_PREF_RANGE_TYPE_MASK);
962315a1350SMichael S. Tsirkin }
963315a1350SMichael S. Tsirkin 
pci_init_multifunction(PCIBus * bus,PCIDevice * dev,Error ** errp)964133e9b22SMarkus Armbruster static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
965315a1350SMichael S. Tsirkin {
966315a1350SMichael S. Tsirkin     uint8_t slot = PCI_SLOT(dev->devfn);
967315a1350SMichael S. Tsirkin     uint8_t func;
968315a1350SMichael S. Tsirkin 
969315a1350SMichael S. Tsirkin     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
970315a1350SMichael S. Tsirkin         dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
971315a1350SMichael S. Tsirkin     }
972315a1350SMichael S. Tsirkin 
973aa01c491SMichael S. Tsirkin     /*
974aa01c491SMichael S. Tsirkin      * With SR/IOV and ARI, a device at function 0 need not be a multifunction
975aa01c491SMichael S. Tsirkin      * device, as it may just be a VF that ended up with function 0 in
976aa01c491SMichael S. Tsirkin      * the legacy PCI interpretation. Avoid failing in such cases:
977aa01c491SMichael S. Tsirkin      */
978aa01c491SMichael S. Tsirkin     if (pci_is_vf(dev) &&
979aa01c491SMichael S. Tsirkin         dev->exp.sriov_vf.pf->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
9807c0fa8dfSKnut Omang         return;
9817c0fa8dfSKnut Omang     }
9827c0fa8dfSKnut Omang 
9837c0fa8dfSKnut Omang     /*
984315a1350SMichael S. Tsirkin      * multifunction bit is interpreted in two ways as follows.
985315a1350SMichael S. Tsirkin      *   - all functions must set the bit to 1.
986315a1350SMichael S. Tsirkin      *     Example: Intel X53
987315a1350SMichael S. Tsirkin      *   - function 0 must set the bit, but the rest function (> 0)
988315a1350SMichael S. Tsirkin      *     is allowed to leave the bit to 0.
989315a1350SMichael S. Tsirkin      *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
990315a1350SMichael S. Tsirkin      *
991315a1350SMichael S. Tsirkin      * So OS (at least Linux) checks the bit of only function 0,
992315a1350SMichael S. Tsirkin      * and doesn't see the bit of function > 0.
993315a1350SMichael S. Tsirkin      *
994315a1350SMichael S. Tsirkin      * The below check allows both interpretation.
995315a1350SMichael S. Tsirkin      */
996315a1350SMichael S. Tsirkin     if (PCI_FUNC(dev->devfn)) {
997315a1350SMichael S. Tsirkin         PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
998315a1350SMichael S. Tsirkin         if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
999315a1350SMichael S. Tsirkin             /* function 0 should set multifunction bit */
1000133e9b22SMarkus Armbruster             error_setg(errp, "PCI: single function device can't be populated "
1001315a1350SMichael S. Tsirkin                        "in function %x.%x", slot, PCI_FUNC(dev->devfn));
1002133e9b22SMarkus Armbruster             return;
1003315a1350SMichael S. Tsirkin         }
1004133e9b22SMarkus Armbruster         return;
1005315a1350SMichael S. Tsirkin     }
1006315a1350SMichael S. Tsirkin 
1007315a1350SMichael S. Tsirkin     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
1008133e9b22SMarkus Armbruster         return;
1009315a1350SMichael S. Tsirkin     }
1010315a1350SMichael S. Tsirkin     /* function 0 indicates single function, so function > 0 must be NULL */
1011315a1350SMichael S. Tsirkin     for (func = 1; func < PCI_FUNC_MAX; ++func) {
1012aa01c491SMichael S. Tsirkin         if (bus->devices[PCI_DEVFN(slot, func)]) {
1013133e9b22SMarkus Armbruster             error_setg(errp, "PCI: %x.0 indicates single function, "
1014315a1350SMichael S. Tsirkin                        "but %x.%x is already populated.",
1015315a1350SMichael S. Tsirkin                        slot, slot, func);
1016133e9b22SMarkus Armbruster             return;
1017315a1350SMichael S. Tsirkin         }
1018315a1350SMichael S. Tsirkin     }
1019315a1350SMichael S. Tsirkin }
1020315a1350SMichael S. Tsirkin 
pci_config_alloc(PCIDevice * pci_dev)1021315a1350SMichael S. Tsirkin static void pci_config_alloc(PCIDevice *pci_dev)
1022315a1350SMichael S. Tsirkin {
1023315a1350SMichael S. Tsirkin     int config_size = pci_config_size(pci_dev);
1024315a1350SMichael S. Tsirkin 
1025315a1350SMichael S. Tsirkin     pci_dev->config = g_malloc0(config_size);
1026315a1350SMichael S. Tsirkin     pci_dev->cmask = g_malloc0(config_size);
1027315a1350SMichael S. Tsirkin     pci_dev->wmask = g_malloc0(config_size);
1028315a1350SMichael S. Tsirkin     pci_dev->w1cmask = g_malloc0(config_size);
1029315a1350SMichael S. Tsirkin     pci_dev->used = g_malloc0(config_size);
1030315a1350SMichael S. Tsirkin }
1031315a1350SMichael S. Tsirkin 
pci_config_free(PCIDevice * pci_dev)1032315a1350SMichael S. Tsirkin static void pci_config_free(PCIDevice *pci_dev)
1033315a1350SMichael S. Tsirkin {
1034315a1350SMichael S. Tsirkin     g_free(pci_dev->config);
1035315a1350SMichael S. Tsirkin     g_free(pci_dev->cmask);
1036315a1350SMichael S. Tsirkin     g_free(pci_dev->wmask);
1037315a1350SMichael S. Tsirkin     g_free(pci_dev->w1cmask);
1038315a1350SMichael S. Tsirkin     g_free(pci_dev->used);
1039315a1350SMichael S. Tsirkin }
1040315a1350SMichael S. Tsirkin 
do_pci_unregister_device(PCIDevice * pci_dev)104130607764SMarcel Apfelbaum static void do_pci_unregister_device(PCIDevice *pci_dev)
104230607764SMarcel Apfelbaum {
1043fd56e061SDavid Gibson     pci_get_bus(pci_dev)->devices[pci_dev->devfn] = NULL;
104430607764SMarcel Apfelbaum     pci_config_free(pci_dev);
104530607764SMarcel Apfelbaum 
10466096cf78SDavid Woodhouse     if (xen_mode == XEN_EMULATE) {
10476096cf78SDavid Woodhouse         xen_evtchn_remove_pci_device(pci_dev);
10486096cf78SDavid Woodhouse     }
1049193982c6SAlexey Kardashevskiy     if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {
1050c53598edSAlexey Kardashevskiy         memory_region_del_subregion(&pci_dev->bus_master_container_region,
1051c53598edSAlexey Kardashevskiy                                     &pci_dev->bus_master_enable_region);
1052193982c6SAlexey Kardashevskiy     }
105330607764SMarcel Apfelbaum     address_space_destroy(&pci_dev->bus_master_as);
105430607764SMarcel Apfelbaum }
105530607764SMarcel Apfelbaum 
10564a94b3aaSPeter Xu /* Extract PCIReqIDCache into BDF format */
pci_req_id_cache_extract(PCIReqIDCache * cache)10574a94b3aaSPeter Xu static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
10584a94b3aaSPeter Xu {
10594a94b3aaSPeter Xu     uint8_t bus_n;
10604a94b3aaSPeter Xu     uint16_t result;
10614a94b3aaSPeter Xu 
10624a94b3aaSPeter Xu     switch (cache->type) {
10634a94b3aaSPeter Xu     case PCI_REQ_ID_BDF:
10644a94b3aaSPeter Xu         result = pci_get_bdf(cache->dev);
10654a94b3aaSPeter Xu         break;
10664a94b3aaSPeter Xu     case PCI_REQ_ID_SECONDARY_BUS:
1067fd56e061SDavid Gibson         bus_n = pci_dev_bus_num(cache->dev);
10684a94b3aaSPeter Xu         result = PCI_BUILD_BDF(bus_n, 0);
10694a94b3aaSPeter Xu         break;
10704a94b3aaSPeter Xu     default:
1071eaf27fabSMarkus Armbruster         error_report("Invalid PCI requester ID cache type: %d",
10724a94b3aaSPeter Xu                      cache->type);
10734a94b3aaSPeter Xu         exit(1);
10744a94b3aaSPeter Xu         break;
10754a94b3aaSPeter Xu     }
10764a94b3aaSPeter Xu 
10774a94b3aaSPeter Xu     return result;
10784a94b3aaSPeter Xu }
10794a94b3aaSPeter Xu 
10804a94b3aaSPeter Xu /* Parse bridges up to the root complex and return requester ID
10814a94b3aaSPeter Xu  * cache for specific device.  For full PCIe topology, the cache
10824a94b3aaSPeter Xu  * result would be exactly the same as getting BDF of the device.
10834a94b3aaSPeter Xu  * However, several tricks are required when system mixed up with
10844a94b3aaSPeter Xu  * legacy PCI devices and PCIe-to-PCI bridges.
10854a94b3aaSPeter Xu  *
10864a94b3aaSPeter Xu  * Here we cache the proxy device (and type) not requester ID since
10874a94b3aaSPeter Xu  * bus number might change from time to time.
10884a94b3aaSPeter Xu  */
pci_req_id_cache_get(PCIDevice * dev)10894a94b3aaSPeter Xu static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
10904a94b3aaSPeter Xu {
10914a94b3aaSPeter Xu     PCIDevice *parent;
10924a94b3aaSPeter Xu     PCIReqIDCache cache = {
10934a94b3aaSPeter Xu         .dev = dev,
10944a94b3aaSPeter Xu         .type = PCI_REQ_ID_BDF,
10954a94b3aaSPeter Xu     };
10964a94b3aaSPeter Xu 
1097fd56e061SDavid Gibson     while (!pci_bus_is_root(pci_get_bus(dev))) {
10984a94b3aaSPeter Xu         /* We are under PCI/PCIe bridges */
1099fd56e061SDavid Gibson         parent = pci_get_bus(dev)->parent_dev;
11004a94b3aaSPeter Xu         if (pci_is_express(parent)) {
11014a94b3aaSPeter Xu             if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
11024a94b3aaSPeter Xu                 /* When we pass through PCIe-to-PCI/PCIX bridges, we
11034a94b3aaSPeter Xu                  * override the requester ID using secondary bus
11044a94b3aaSPeter Xu                  * number of parent bridge with zeroed devfn
11054a94b3aaSPeter Xu                  * (pcie-to-pci bridge spec chap 2.3). */
11064a94b3aaSPeter Xu                 cache.type = PCI_REQ_ID_SECONDARY_BUS;
11074a94b3aaSPeter Xu                 cache.dev = dev;
11084a94b3aaSPeter Xu             }
11094a94b3aaSPeter Xu         } else {
11104a94b3aaSPeter Xu             /* Legacy PCI, override requester ID with the bridge's
11114a94b3aaSPeter Xu              * BDF upstream.  When the root complex connects to
11124a94b3aaSPeter Xu              * legacy PCI devices (including buses), it can only
11134a94b3aaSPeter Xu              * obtain requester ID info from directly attached
11144a94b3aaSPeter Xu              * devices.  If devices are attached under bridges, only
11154a94b3aaSPeter Xu              * the requester ID of the bridge that is directly
11164a94b3aaSPeter Xu              * attached to the root complex can be recognized. */
11174a94b3aaSPeter Xu             cache.type = PCI_REQ_ID_BDF;
11184a94b3aaSPeter Xu             cache.dev = parent;
11194a94b3aaSPeter Xu         }
11204a94b3aaSPeter Xu         dev = parent;
11214a94b3aaSPeter Xu     }
11224a94b3aaSPeter Xu 
11234a94b3aaSPeter Xu     return cache;
11244a94b3aaSPeter Xu }
11254a94b3aaSPeter Xu 
pci_requester_id(PCIDevice * dev)11264a94b3aaSPeter Xu uint16_t pci_requester_id(PCIDevice *dev)
11274a94b3aaSPeter Xu {
11284a94b3aaSPeter Xu     return pci_req_id_cache_extract(&dev->requester_id_cache);
11294a94b3aaSPeter Xu }
11304a94b3aaSPeter Xu 
pci_bus_devfn_available(PCIBus * bus,int devfn)11319b717a3aSMark Cave-Ayland static bool pci_bus_devfn_available(PCIBus *bus, int devfn)
11329b717a3aSMark Cave-Ayland {
11339b717a3aSMark Cave-Ayland     return !(bus->devices[devfn]);
11349b717a3aSMark Cave-Ayland }
11359b717a3aSMark Cave-Ayland 
pci_bus_devfn_reserved(PCIBus * bus,int devfn)11368b884984SMark Cave-Ayland static bool pci_bus_devfn_reserved(PCIBus *bus, int devfn)
11378b884984SMark Cave-Ayland {
11388b884984SMark Cave-Ayland     return bus->slot_reserved_mask & (1UL << PCI_SLOT(devfn));
11398b884984SMark Cave-Ayland }
11408b884984SMark Cave-Ayland 
pci_bus_get_slot_reserved_mask(PCIBus * bus)1141b93fe7f2SChuck Zmudzinski uint32_t pci_bus_get_slot_reserved_mask(PCIBus *bus)
1142b93fe7f2SChuck Zmudzinski {
1143b93fe7f2SChuck Zmudzinski     return bus->slot_reserved_mask;
1144b93fe7f2SChuck Zmudzinski }
1145b93fe7f2SChuck Zmudzinski 
pci_bus_set_slot_reserved_mask(PCIBus * bus,uint32_t mask)1146b93fe7f2SChuck Zmudzinski void pci_bus_set_slot_reserved_mask(PCIBus *bus, uint32_t mask)
1147b93fe7f2SChuck Zmudzinski {
1148b93fe7f2SChuck Zmudzinski     bus->slot_reserved_mask |= mask;
1149b93fe7f2SChuck Zmudzinski }
1150b93fe7f2SChuck Zmudzinski 
pci_bus_clear_slot_reserved_mask(PCIBus * bus,uint32_t mask)1151b93fe7f2SChuck Zmudzinski void pci_bus_clear_slot_reserved_mask(PCIBus *bus, uint32_t mask)
1152b93fe7f2SChuck Zmudzinski {
1153b93fe7f2SChuck Zmudzinski     bus->slot_reserved_mask &= ~mask;
1154b93fe7f2SChuck Zmudzinski }
1155b93fe7f2SChuck Zmudzinski 
1156315a1350SMichael S. Tsirkin /* -1 for devfn means auto assign */
do_pci_register_device(PCIDevice * pci_dev,const char * name,int devfn,Error ** errp)1157fd56e061SDavid Gibson static PCIDevice *do_pci_register_device(PCIDevice *pci_dev,
1158133e9b22SMarkus Armbruster                                          const char *name, int devfn,
1159133e9b22SMarkus Armbruster                                          Error **errp)
1160315a1350SMichael S. Tsirkin {
1161315a1350SMichael S. Tsirkin     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1162315a1350SMichael S. Tsirkin     PCIConfigReadFunc *config_read = pc->config_read;
1163315a1350SMichael S. Tsirkin     PCIConfigWriteFunc *config_write = pc->config_write;
1164133e9b22SMarkus Armbruster     Error *local_err = NULL;
11653f1e1478SCao jin     DeviceState *dev = DEVICE(pci_dev);
1166fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
1167ad494274SIgor Mammedov     bool is_bridge = IS_PCI_BRIDGE(pci_dev);
11683f1e1478SCao jin 
11690144f6f1SMarcel Apfelbaum     /* Only pci bridges can be attached to extra PCI root buses */
1170ad494274SIgor Mammedov     if (pci_bus_is_root(bus) && bus->parent_dev && !is_bridge) {
11710144f6f1SMarcel Apfelbaum         error_setg(errp,
11720144f6f1SMarcel Apfelbaum                    "PCI: Only PCI/PCIe bridges can be plugged into %s",
11730144f6f1SMarcel Apfelbaum                     bus->parent_dev->name);
11740144f6f1SMarcel Apfelbaum         return NULL;
11750144f6f1SMarcel Apfelbaum     }
1176315a1350SMichael S. Tsirkin 
1177315a1350SMichael S. Tsirkin     if (devfn < 0) {
1178315a1350SMichael S. Tsirkin         for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
1179315a1350SMichael S. Tsirkin             devfn += PCI_FUNC_MAX) {
11808b884984SMark Cave-Ayland             if (pci_bus_devfn_available(bus, devfn) &&
11818b884984SMark Cave-Ayland                    !pci_bus_devfn_reserved(bus, devfn)) {
1182315a1350SMichael S. Tsirkin                 goto found;
1183315a1350SMichael S. Tsirkin             }
11849b717a3aSMark Cave-Ayland         }
11858b884984SMark Cave-Ayland         error_setg(errp, "PCI: no slot/function available for %s, all in use "
11868b884984SMark Cave-Ayland                    "or reserved", name);
1187315a1350SMichael S. Tsirkin         return NULL;
1188315a1350SMichael S. Tsirkin     found: ;
11898b884984SMark Cave-Ayland     } else if (pci_bus_devfn_reserved(bus, devfn)) {
11908b884984SMark Cave-Ayland         error_setg(errp, "PCI: slot %d function %d not available for %s,"
11918b884984SMark Cave-Ayland                    " reserved",
11928b884984SMark Cave-Ayland                    PCI_SLOT(devfn), PCI_FUNC(devfn), name);
11938b884984SMark Cave-Ayland         return NULL;
11949b717a3aSMark Cave-Ayland     } else if (!pci_bus_devfn_available(bus, devfn)) {
1195133e9b22SMarkus Armbruster         error_setg(errp, "PCI: slot %d function %d not available for %s,"
1196ad003b9eSZhenzhong Duan                    " in use by %s,id=%s",
1197133e9b22SMarkus Armbruster                    PCI_SLOT(devfn), PCI_FUNC(devfn), name,
1198ad003b9eSZhenzhong Duan                    bus->devices[devfn]->name, bus->devices[devfn]->qdev.id);
1199315a1350SMichael S. Tsirkin         return NULL;
1200e228d62bSDongli Zhang     }
1201e228d62bSDongli Zhang 
1202e228d62bSDongli Zhang     /*
120367d045a0SAni Sinha      * Populating function 0 triggers a scan from the guest that
120467d045a0SAni Sinha      * exposes other non-zero functions. Hence we need to ensure that
120567d045a0SAni Sinha      * function 0 wasn't added yet.
120667d045a0SAni Sinha      */
1207e228d62bSDongli Zhang     if (dev->hotplugged && !pci_is_vf(pci_dev) &&
12083f1e1478SCao jin         pci_get_function_0(pci_dev)) {
12093298bbceSJulia Suvorova         error_setg(errp, "PCI: slot %d function 0 already occupied by %s,"
12103f1e1478SCao jin                    " new func %s cannot be exposed to guest.",
1211d93ddfb1SMichael S. Tsirkin                    PCI_SLOT(pci_get_function_0(pci_dev)->devfn),
1212d93ddfb1SMichael S. Tsirkin                    pci_get_function_0(pci_dev)->name,
12133f1e1478SCao jin                    name);
12143f1e1478SCao jin 
12153f1e1478SCao jin        return NULL;
1216315a1350SMichael S. Tsirkin     }
1217e00387d5SAvi Kivity 
1218efc8188eSLe Tan     pci_dev->devfn = devfn;
12194a94b3aaSPeter Xu     pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
1220d06bce95SAlexey Kardashevskiy     pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
1221e00387d5SAvi Kivity 
12223716d590SJason Wang     memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),
12233716d590SJason Wang                        "bus master container", UINT64_MAX);
12243716d590SJason Wang     address_space_init(&pci_dev->bus_master_as,
12253716d590SJason Wang                        &pci_dev->bus_master_container_region, pci_dev->name);
1226637b0aa1SMattias Nissler     pci_dev->bus_master_as.max_bounce_buffer_size =
1227637b0aa1SMattias Nissler         pci_dev->max_bounce_buffer_size;
12283716d590SJason Wang 
12292f181fbdSPaolo Bonzini     if (phase_check(PHASE_MACHINE_READY)) {
1230b86eacb8SMarcel Apfelbaum         pci_init_bus_master(pci_dev);
1231b86eacb8SMarcel Apfelbaum     }
1232315a1350SMichael S. Tsirkin     pci_dev->irq_state = 0;
1233315a1350SMichael S. Tsirkin     pci_config_alloc(pci_dev);
1234315a1350SMichael S. Tsirkin 
1235315a1350SMichael S. Tsirkin     pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1236315a1350SMichael S. Tsirkin     pci_config_set_device_id(pci_dev->config, pc->device_id);
1237315a1350SMichael S. Tsirkin     pci_config_set_revision(pci_dev->config, pc->revision);
1238315a1350SMichael S. Tsirkin     pci_config_set_class(pci_dev->config, pc->class_id);
1239315a1350SMichael S. Tsirkin 
1240ad494274SIgor Mammedov     if (!is_bridge) {
1241315a1350SMichael S. Tsirkin         if (pc->subsystem_vendor_id || pc->subsystem_id) {
1242315a1350SMichael S. Tsirkin             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1243315a1350SMichael S. Tsirkin                          pc->subsystem_vendor_id);
1244315a1350SMichael S. Tsirkin             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1245315a1350SMichael S. Tsirkin                          pc->subsystem_id);
1246315a1350SMichael S. Tsirkin         } else {
1247315a1350SMichael S. Tsirkin             pci_set_default_subsystem_id(pci_dev);
1248315a1350SMichael S. Tsirkin         }
1249315a1350SMichael S. Tsirkin     } else {
1250315a1350SMichael S. Tsirkin         /* subsystem_vendor_id/subsystem_id are only for header type 0 */
1251315a1350SMichael S. Tsirkin         assert(!pc->subsystem_vendor_id);
1252315a1350SMichael S. Tsirkin         assert(!pc->subsystem_id);
1253315a1350SMichael S. Tsirkin     }
1254315a1350SMichael S. Tsirkin     pci_init_cmask(pci_dev);
1255315a1350SMichael S. Tsirkin     pci_init_wmask(pci_dev);
1256315a1350SMichael S. Tsirkin     pci_init_w1cmask(pci_dev);
1257ad494274SIgor Mammedov     if (is_bridge) {
1258315a1350SMichael S. Tsirkin         pci_init_mask_bridge(pci_dev);
1259315a1350SMichael S. Tsirkin     }
1260133e9b22SMarkus Armbruster     pci_init_multifunction(bus, pci_dev, &local_err);
1261133e9b22SMarkus Armbruster     if (local_err) {
1262133e9b22SMarkus Armbruster         error_propagate(errp, local_err);
126330607764SMarcel Apfelbaum         do_pci_unregister_device(pci_dev);
1264315a1350SMichael S. Tsirkin         return NULL;
1265315a1350SMichael S. Tsirkin     }
1266315a1350SMichael S. Tsirkin 
1267315a1350SMichael S. Tsirkin     if (!config_read)
1268315a1350SMichael S. Tsirkin         config_read = pci_default_read_config;
1269315a1350SMichael S. Tsirkin     if (!config_write)
1270315a1350SMichael S. Tsirkin         config_write = pci_default_write_config;
1271315a1350SMichael S. Tsirkin     pci_dev->config_read = config_read;
1272315a1350SMichael S. Tsirkin     pci_dev->config_write = config_write;
1273315a1350SMichael S. Tsirkin     bus->devices[devfn] = pci_dev;
1274315a1350SMichael S. Tsirkin     pci_dev->version_id = 2; /* Current pci device vmstate version */
1275315a1350SMichael S. Tsirkin     return pci_dev;
1276315a1350SMichael S. Tsirkin }
1277315a1350SMichael S. Tsirkin 
pci_unregister_io_regions(PCIDevice * pci_dev)1278315a1350SMichael S. Tsirkin static void pci_unregister_io_regions(PCIDevice *pci_dev)
1279315a1350SMichael S. Tsirkin {
1280315a1350SMichael S. Tsirkin     PCIIORegion *r;
1281315a1350SMichael S. Tsirkin     int i;
1282315a1350SMichael S. Tsirkin 
1283315a1350SMichael S. Tsirkin     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1284315a1350SMichael S. Tsirkin         r = &pci_dev->io_regions[i];
1285315a1350SMichael S. Tsirkin         if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1286315a1350SMichael S. Tsirkin             continue;
1287315a1350SMichael S. Tsirkin         memory_region_del_subregion(r->address_space, r->memory);
1288315a1350SMichael S. Tsirkin     }
1289e01fd687SAlex Williamson 
1290e01fd687SAlex Williamson     pci_unregister_vga(pci_dev);
1291315a1350SMichael S. Tsirkin }
1292315a1350SMichael S. Tsirkin 
pci_qdev_unrealize(DeviceState * dev)1293b69c3c21SMarkus Armbruster static void pci_qdev_unrealize(DeviceState *dev)
1294315a1350SMichael S. Tsirkin {
1295315a1350SMichael S. Tsirkin     PCIDevice *pci_dev = PCI_DEVICE(dev);
1296315a1350SMichael S. Tsirkin     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1297315a1350SMichael S. Tsirkin 
1298315a1350SMichael S. Tsirkin     pci_unregister_io_regions(pci_dev);
1299315a1350SMichael S. Tsirkin     pci_del_option_rom(pci_dev);
1300315a1350SMichael S. Tsirkin 
1301315a1350SMichael S. Tsirkin     if (pc->exit) {
1302315a1350SMichael S. Tsirkin         pc->exit(pci_dev);
1303315a1350SMichael S. Tsirkin     }
1304315a1350SMichael S. Tsirkin 
13053936161fSHerongguang (Stephen)     pci_device_deassert_intx(pci_dev);
1306315a1350SMichael S. Tsirkin     do_pci_unregister_device(pci_dev);
130708cf3dc6SJagannathan Raman 
130808cf3dc6SJagannathan Raman     pci_dev->msi_trigger = NULL;
1309041b1c40SIgor Mammedov 
1310041b1c40SIgor Mammedov     /*
1311041b1c40SIgor Mammedov      * clean up acpi-index so it could reused by another device
1312041b1c40SIgor Mammedov      */
1313041b1c40SIgor Mammedov     if (pci_dev->acpi_index) {
1314041b1c40SIgor Mammedov         GSequence *used_indexes = pci_acpi_index_list();
1315041b1c40SIgor Mammedov 
1316041b1c40SIgor Mammedov         g_sequence_remove(g_sequence_lookup(used_indexes,
1317041b1c40SIgor Mammedov                           GINT_TO_POINTER(pci_dev->acpi_index),
1318041b1c40SIgor Mammedov                           g_cmp_uint32, NULL));
1319041b1c40SIgor Mammedov     }
1320315a1350SMichael S. Tsirkin }
1321315a1350SMichael S. Tsirkin 
pci_register_bar(PCIDevice * pci_dev,int region_num,uint8_t type,MemoryRegion * memory)1322315a1350SMichael S. Tsirkin void pci_register_bar(PCIDevice *pci_dev, int region_num,
1323315a1350SMichael S. Tsirkin                       uint8_t type, MemoryRegion *memory)
1324315a1350SMichael S. Tsirkin {
1325315a1350SMichael S. Tsirkin     PCIIORegion *r;
13265178ecd8SCao jin     uint32_t addr; /* offset in pci config space */
1327315a1350SMichael S. Tsirkin     uint64_t wmask;
1328315a1350SMichael S. Tsirkin     pcibus_t size = memory_region_size(memory);
13296a5b19caSBen Widawsky     uint8_t hdr_type;
1330315a1350SMichael S. Tsirkin 
1331aa01c491SMichael S. Tsirkin     assert(!pci_is_vf(pci_dev)); /* VFs must use pcie_sriov_vf_register_bar */
1332315a1350SMichael S. Tsirkin     assert(region_num >= 0);
1333315a1350SMichael S. Tsirkin     assert(region_num < PCI_NUM_REGIONS);
13342c729dc8SBen Widawsky     assert(is_power_of_2(size));
1335315a1350SMichael S. Tsirkin 
13366a5b19caSBen Widawsky     /* A PCI bridge device (with Type 1 header) may only have at most 2 BARs */
13376a5b19caSBen Widawsky     hdr_type =
13386a5b19caSBen Widawsky         pci_dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
13396a5b19caSBen Widawsky     assert(hdr_type != PCI_HEADER_TYPE_BRIDGE || region_num < 2);
13406a5b19caSBen Widawsky 
1341315a1350SMichael S. Tsirkin     r = &pci_dev->io_regions[region_num];
1342aa01c491SMichael S. Tsirkin     r->addr = PCI_BAR_UNMAPPED;
1343315a1350SMichael S. Tsirkin     r->size = size;
1344315a1350SMichael S. Tsirkin     r->type = type;
13455178ecd8SCao jin     r->memory = memory;
13465178ecd8SCao jin     r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1347fd56e061SDavid Gibson                         ? pci_get_bus(pci_dev)->address_space_io
1348fd56e061SDavid Gibson                         : pci_get_bus(pci_dev)->address_space_mem;
1349315a1350SMichael S. Tsirkin 
1350315a1350SMichael S. Tsirkin     wmask = ~(size - 1);
1351315a1350SMichael S. Tsirkin     if (region_num == PCI_ROM_SLOT) {
1352315a1350SMichael S. Tsirkin         /* ROM enable bit is writable */
1353315a1350SMichael S. Tsirkin         wmask |= PCI_ROM_ADDRESS_ENABLE;
1354315a1350SMichael S. Tsirkin     }
13555178ecd8SCao jin 
13565178ecd8SCao jin     addr = pci_bar(pci_dev, region_num);
1357315a1350SMichael S. Tsirkin     pci_set_long(pci_dev->config + addr, type);
13585178ecd8SCao jin 
1359315a1350SMichael S. Tsirkin     if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1360315a1350SMichael S. Tsirkin         r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1361315a1350SMichael S. Tsirkin         pci_set_quad(pci_dev->wmask + addr, wmask);
1362315a1350SMichael S. Tsirkin         pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1363315a1350SMichael S. Tsirkin     } else {
1364315a1350SMichael S. Tsirkin         pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1365315a1350SMichael S. Tsirkin         pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1366315a1350SMichael S. Tsirkin     }
1367315a1350SMichael S. Tsirkin }
1368315a1350SMichael S. Tsirkin 
pci_update_vga(PCIDevice * pci_dev)1369e01fd687SAlex Williamson static void pci_update_vga(PCIDevice *pci_dev)
1370e01fd687SAlex Williamson {
1371e01fd687SAlex Williamson     uint16_t cmd;
1372e01fd687SAlex Williamson 
1373e01fd687SAlex Williamson     if (!pci_dev->has_vga) {
1374e01fd687SAlex Williamson         return;
1375e01fd687SAlex Williamson     }
1376e01fd687SAlex Williamson 
1377e01fd687SAlex Williamson     cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1378e01fd687SAlex Williamson 
1379e01fd687SAlex Williamson     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1380e01fd687SAlex Williamson                               cmd & PCI_COMMAND_MEMORY);
1381e01fd687SAlex Williamson     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1382e01fd687SAlex Williamson                               cmd & PCI_COMMAND_IO);
1383e01fd687SAlex Williamson     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1384e01fd687SAlex Williamson                               cmd & PCI_COMMAND_IO);
1385e01fd687SAlex Williamson }
1386e01fd687SAlex Williamson 
pci_register_vga(PCIDevice * pci_dev,MemoryRegion * mem,MemoryRegion * io_lo,MemoryRegion * io_hi)1387e01fd687SAlex Williamson void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1388e01fd687SAlex Williamson                       MemoryRegion *io_lo, MemoryRegion *io_hi)
1389e01fd687SAlex Williamson {
1390fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
1391fd56e061SDavid Gibson 
1392e01fd687SAlex Williamson     assert(!pci_dev->has_vga);
1393e01fd687SAlex Williamson 
1394e01fd687SAlex Williamson     assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1395e01fd687SAlex Williamson     pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1396fd56e061SDavid Gibson     memory_region_add_subregion_overlap(bus->address_space_mem,
1397e01fd687SAlex Williamson                                         QEMU_PCI_VGA_MEM_BASE, mem, 1);
1398e01fd687SAlex Williamson 
1399e01fd687SAlex Williamson     assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1400e01fd687SAlex Williamson     pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1401fd56e061SDavid Gibson     memory_region_add_subregion_overlap(bus->address_space_io,
1402e01fd687SAlex Williamson                                         QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1403e01fd687SAlex Williamson 
1404e01fd687SAlex Williamson     assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1405e01fd687SAlex Williamson     pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1406fd56e061SDavid Gibson     memory_region_add_subregion_overlap(bus->address_space_io,
1407e01fd687SAlex Williamson                                         QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1408e01fd687SAlex Williamson     pci_dev->has_vga = true;
1409e01fd687SAlex Williamson 
1410e01fd687SAlex Williamson     pci_update_vga(pci_dev);
1411e01fd687SAlex Williamson }
1412e01fd687SAlex Williamson 
pci_unregister_vga(PCIDevice * pci_dev)1413e01fd687SAlex Williamson void pci_unregister_vga(PCIDevice *pci_dev)
1414e01fd687SAlex Williamson {
1415fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
1416fd56e061SDavid Gibson 
1417e01fd687SAlex Williamson     if (!pci_dev->has_vga) {
1418e01fd687SAlex Williamson         return;
1419e01fd687SAlex Williamson     }
1420e01fd687SAlex Williamson 
1421fd56e061SDavid Gibson     memory_region_del_subregion(bus->address_space_mem,
1422e01fd687SAlex Williamson                                 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1423fd56e061SDavid Gibson     memory_region_del_subregion(bus->address_space_io,
1424e01fd687SAlex Williamson                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1425fd56e061SDavid Gibson     memory_region_del_subregion(bus->address_space_io,
1426e01fd687SAlex Williamson                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1427e01fd687SAlex Williamson     pci_dev->has_vga = false;
1428e01fd687SAlex Williamson }
1429e01fd687SAlex Williamson 
pci_get_bar_addr(PCIDevice * pci_dev,int region_num)1430315a1350SMichael S. Tsirkin pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1431315a1350SMichael S. Tsirkin {
1432315a1350SMichael S. Tsirkin     return pci_dev->io_regions[region_num].addr;
1433315a1350SMichael S. Tsirkin }
1434315a1350SMichael S. Tsirkin 
pci_config_get_bar_addr(PCIDevice * d,int reg,uint8_t type,pcibus_t size)14357c0fa8dfSKnut Omang static pcibus_t pci_config_get_bar_addr(PCIDevice *d, int reg,
14367c0fa8dfSKnut Omang                                         uint8_t type, pcibus_t size)
14377c0fa8dfSKnut Omang {
14387c0fa8dfSKnut Omang     pcibus_t new_addr;
14397c0fa8dfSKnut Omang     if (!pci_is_vf(d)) {
14407c0fa8dfSKnut Omang         int bar = pci_bar(d, reg);
14417c0fa8dfSKnut Omang         if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
14427c0fa8dfSKnut Omang             new_addr = pci_get_quad(d->config + bar);
14437c0fa8dfSKnut Omang         } else {
14447c0fa8dfSKnut Omang             new_addr = pci_get_long(d->config + bar);
14457c0fa8dfSKnut Omang         }
14467c0fa8dfSKnut Omang     } else {
14477c0fa8dfSKnut Omang         PCIDevice *pf = d->exp.sriov_vf.pf;
14487c0fa8dfSKnut Omang         uint16_t sriov_cap = pf->exp.sriov_cap;
14497c0fa8dfSKnut Omang         int bar = sriov_cap + PCI_SRIOV_BAR + reg * 4;
14507c0fa8dfSKnut Omang         uint16_t vf_offset =
14517c0fa8dfSKnut Omang             pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_OFFSET);
14527c0fa8dfSKnut Omang         uint16_t vf_stride =
14537c0fa8dfSKnut Omang             pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_STRIDE);
145455845251SMichael S. Tsirkin         uint32_t vf_num = (d->devfn - (pf->devfn + vf_offset)) / vf_stride;
14557c0fa8dfSKnut Omang 
14567c0fa8dfSKnut Omang         if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
14577c0fa8dfSKnut Omang             new_addr = pci_get_quad(pf->config + bar);
14587c0fa8dfSKnut Omang         } else {
14597c0fa8dfSKnut Omang             new_addr = pci_get_long(pf->config + bar);
14607c0fa8dfSKnut Omang         }
14617c0fa8dfSKnut Omang         new_addr += vf_num * size;
14627c0fa8dfSKnut Omang     }
14637c0fa8dfSKnut Omang     /* The ROM slot has a specific enable bit, keep it intact */
14647c0fa8dfSKnut Omang     if (reg != PCI_ROM_SLOT) {
14657c0fa8dfSKnut Omang         new_addr &= ~(size - 1);
14667c0fa8dfSKnut Omang     }
14677c0fa8dfSKnut Omang     return new_addr;
14687c0fa8dfSKnut Omang }
14697c0fa8dfSKnut Omang 
pci_bar_address(PCIDevice * d,int reg,uint8_t type,pcibus_t size)14707c0fa8dfSKnut Omang pcibus_t pci_bar_address(PCIDevice *d,
1471315a1350SMichael S. Tsirkin                          int reg, uint8_t type, pcibus_t size)
1472315a1350SMichael S. Tsirkin {
1473315a1350SMichael S. Tsirkin     pcibus_t new_addr, last_addr;
1474315a1350SMichael S. Tsirkin     uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1475271233f2SPhilippe Mathieu-Daudé     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
1476e4024630SLaurent Vivier     bool allow_0_address = mc->pci_allow_0_address;
1477315a1350SMichael S. Tsirkin 
1478315a1350SMichael S. Tsirkin     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1479315a1350SMichael S. Tsirkin         if (!(cmd & PCI_COMMAND_IO)) {
1480315a1350SMichael S. Tsirkin             return PCI_BAR_UNMAPPED;
1481315a1350SMichael S. Tsirkin         }
14827c0fa8dfSKnut Omang         new_addr = pci_config_get_bar_addr(d, reg, type, size);
1483315a1350SMichael S. Tsirkin         last_addr = new_addr + size - 1;
14849f1a029aSHervé Poussineau         /* Check if 32 bit BAR wraps around explicitly.
14859f1a029aSHervé Poussineau          * TODO: make priorities correct and remove this work around.
14869f1a029aSHervé Poussineau          */
1487e4024630SLaurent Vivier         if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1488e4024630SLaurent Vivier             (!allow_0_address && new_addr == 0)) {
1489315a1350SMichael S. Tsirkin             return PCI_BAR_UNMAPPED;
1490315a1350SMichael S. Tsirkin         }
1491315a1350SMichael S. Tsirkin         return new_addr;
1492315a1350SMichael S. Tsirkin     }
1493315a1350SMichael S. Tsirkin 
1494315a1350SMichael S. Tsirkin     if (!(cmd & PCI_COMMAND_MEMORY)) {
1495315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1496315a1350SMichael S. Tsirkin     }
14977c0fa8dfSKnut Omang     new_addr = pci_config_get_bar_addr(d, reg, type, size);
1498315a1350SMichael S. Tsirkin     /* the ROM slot has a specific enable bit */
1499315a1350SMichael S. Tsirkin     if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1500315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1501315a1350SMichael S. Tsirkin     }
1502315a1350SMichael S. Tsirkin     new_addr &= ~(size - 1);
1503315a1350SMichael S. Tsirkin     last_addr = new_addr + size - 1;
1504315a1350SMichael S. Tsirkin     /* NOTE: we do not support wrapping */
1505315a1350SMichael S. Tsirkin     /* XXX: as we cannot support really dynamic
1506315a1350SMichael S. Tsirkin        mappings, we handle specific values as invalid
1507315a1350SMichael S. Tsirkin        mappings. */
1508e4024630SLaurent Vivier     if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1509e4024630SLaurent Vivier         (!allow_0_address && new_addr == 0)) {
1510315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1511315a1350SMichael S. Tsirkin     }
1512315a1350SMichael S. Tsirkin 
1513315a1350SMichael S. Tsirkin     /* Now pcibus_t is 64bit.
1514315a1350SMichael S. Tsirkin      * Check if 32 bit BAR wraps around explicitly.
1515315a1350SMichael S. Tsirkin      * Without this, PC ide doesn't work well.
1516315a1350SMichael S. Tsirkin      * TODO: remove this work around.
1517315a1350SMichael S. Tsirkin      */
1518315a1350SMichael S. Tsirkin     if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1519315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1520315a1350SMichael S. Tsirkin     }
1521315a1350SMichael S. Tsirkin 
1522315a1350SMichael S. Tsirkin     /*
1523315a1350SMichael S. Tsirkin      * OS is allowed to set BAR beyond its addressable
1524315a1350SMichael S. Tsirkin      * bits. For example, 32 bit OS can set 64bit bar
1525315a1350SMichael S. Tsirkin      * to >4G. Check it. TODO: we might need to support
1526315a1350SMichael S. Tsirkin      * it in the future for e.g. PAE.
1527315a1350SMichael S. Tsirkin      */
1528315a1350SMichael S. Tsirkin     if (last_addr >= HWADDR_MAX) {
1529315a1350SMichael S. Tsirkin         return PCI_BAR_UNMAPPED;
1530315a1350SMichael S. Tsirkin     }
1531315a1350SMichael S. Tsirkin 
1532315a1350SMichael S. Tsirkin     return new_addr;
1533315a1350SMichael S. Tsirkin }
1534315a1350SMichael S. Tsirkin 
pci_update_mappings(PCIDevice * d)1535315a1350SMichael S. Tsirkin static void pci_update_mappings(PCIDevice *d)
1536315a1350SMichael S. Tsirkin {
1537315a1350SMichael S. Tsirkin     PCIIORegion *r;
1538315a1350SMichael S. Tsirkin     int i;
1539315a1350SMichael S. Tsirkin     pcibus_t new_addr;
1540315a1350SMichael S. Tsirkin 
1541315a1350SMichael S. Tsirkin     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1542315a1350SMichael S. Tsirkin         r = &d->io_regions[i];
1543315a1350SMichael S. Tsirkin 
1544315a1350SMichael S. Tsirkin         /* this region isn't registered */
1545315a1350SMichael S. Tsirkin         if (!r->size)
1546315a1350SMichael S. Tsirkin             continue;
1547315a1350SMichael S. Tsirkin 
1548315a1350SMichael S. Tsirkin         new_addr = pci_bar_address(d, i, r->type, r->size);
154993829009SMichael S. Tsirkin         if (!d->has_power) {
155023786d13SGerd Hoffmann             new_addr = PCI_BAR_UNMAPPED;
155123786d13SGerd Hoffmann         }
1552315a1350SMichael S. Tsirkin 
1553315a1350SMichael S. Tsirkin         /* This bar isn't changed */
1554315a1350SMichael S. Tsirkin         if (new_addr == r->addr)
1555315a1350SMichael S. Tsirkin             continue;
1556315a1350SMichael S. Tsirkin 
1557315a1350SMichael S. Tsirkin         /* now do the real mapping */
1558315a1350SMichael S. Tsirkin         if (r->addr != PCI_BAR_UNMAPPED) {
1559deeb956cSLaurent Vivier             trace_pci_update_mappings_del(d->name, pci_dev_bus_num(d),
15607828d750SDon Koch                                           PCI_SLOT(d->devfn),
15610f288f85SLaszlo Ersek                                           PCI_FUNC(d->devfn),
15627828d750SDon Koch                                           i, r->addr, r->size);
1563315a1350SMichael S. Tsirkin             memory_region_del_subregion(r->address_space, r->memory);
1564315a1350SMichael S. Tsirkin         }
1565315a1350SMichael S. Tsirkin         r->addr = new_addr;
1566315a1350SMichael S. Tsirkin         if (r->addr != PCI_BAR_UNMAPPED) {
1567deeb956cSLaurent Vivier             trace_pci_update_mappings_add(d->name, pci_dev_bus_num(d),
15687828d750SDon Koch                                           PCI_SLOT(d->devfn),
15690f288f85SLaszlo Ersek                                           PCI_FUNC(d->devfn),
15707828d750SDon Koch                                           i, r->addr, r->size);
1571315a1350SMichael S. Tsirkin             memory_region_add_subregion_overlap(r->address_space,
1572315a1350SMichael S. Tsirkin                                                 r->addr, r->memory, 1);
1573315a1350SMichael S. Tsirkin         }
1574315a1350SMichael S. Tsirkin     }
1575e01fd687SAlex Williamson 
1576e01fd687SAlex Williamson     pci_update_vga(d);
1577315a1350SMichael S. Tsirkin }
1578315a1350SMichael S. Tsirkin 
pci_irq_disabled(PCIDevice * d)1579315a1350SMichael S. Tsirkin static inline int pci_irq_disabled(PCIDevice *d)
1580315a1350SMichael S. Tsirkin {
1581315a1350SMichael S. Tsirkin     return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1582315a1350SMichael S. Tsirkin }
1583315a1350SMichael S. Tsirkin 
1584315a1350SMichael S. Tsirkin /* Called after interrupt disabled field update in config space,
1585315a1350SMichael S. Tsirkin  * assert/deassert interrupts if necessary.
1586315a1350SMichael S. Tsirkin  * Gets original interrupt disable bit value (before update). */
pci_update_irq_disabled(PCIDevice * d,int was_irq_disabled)1587315a1350SMichael S. Tsirkin static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1588315a1350SMichael S. Tsirkin {
1589315a1350SMichael S. Tsirkin     int i, disabled = pci_irq_disabled(d);
1590315a1350SMichael S. Tsirkin     if (disabled == was_irq_disabled)
1591315a1350SMichael S. Tsirkin         return;
1592315a1350SMichael S. Tsirkin     for (i = 0; i < PCI_NUM_PINS; ++i) {
1593315a1350SMichael S. Tsirkin         int state = pci_irq_state(d, i);
1594315a1350SMichael S. Tsirkin         pci_change_irq_level(d, i, disabled ? -state : state);
1595315a1350SMichael S. Tsirkin     }
1596315a1350SMichael S. Tsirkin }
1597315a1350SMichael S. Tsirkin 
pci_default_read_config(PCIDevice * d,uint32_t address,int len)1598315a1350SMichael S. Tsirkin uint32_t pci_default_read_config(PCIDevice *d,
1599315a1350SMichael S. Tsirkin                                  uint32_t address, int len)
1600315a1350SMichael S. Tsirkin {
1601315a1350SMichael S. Tsirkin     uint32_t val = 0;
1602315a1350SMichael S. Tsirkin 
1603f7d6a635SPrasad J Pandit     assert(address + len <= pci_config_size(d));
1604f7d6a635SPrasad J Pandit 
1605727b4866SAlex Williamson     if (pci_is_express_downstream_port(d) &&
1606727b4866SAlex Williamson         ranges_overlap(address, len, d->exp.exp_cap + PCI_EXP_LNKSTA, 2)) {
1607727b4866SAlex Williamson         pcie_sync_bridge_lnk(d);
1608727b4866SAlex Williamson     }
1609315a1350SMichael S. Tsirkin     memcpy(&val, d->config + address, len);
1610315a1350SMichael S. Tsirkin     return le32_to_cpu(val);
1611315a1350SMichael S. Tsirkin }
1612315a1350SMichael S. Tsirkin 
pci_default_write_config(PCIDevice * d,uint32_t addr,uint32_t val_in,int l)1613d7efb7e0SKnut Omang void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1614315a1350SMichael S. Tsirkin {
1615315a1350SMichael S. Tsirkin     int i, was_irq_disabled = pci_irq_disabled(d);
1616d7efb7e0SKnut Omang     uint32_t val = val_in;
1617315a1350SMichael S. Tsirkin 
1618f7d6a635SPrasad J Pandit     assert(addr + l <= pci_config_size(d));
1619f7d6a635SPrasad J Pandit 
1620315a1350SMichael S. Tsirkin     for (i = 0; i < l; val >>= 8, ++i) {
1621315a1350SMichael S. Tsirkin         uint8_t wmask = d->wmask[addr + i];
1622315a1350SMichael S. Tsirkin         uint8_t w1cmask = d->w1cmask[addr + i];
1623315a1350SMichael S. Tsirkin         assert(!(wmask & w1cmask));
1624315a1350SMichael S. Tsirkin         d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1625315a1350SMichael S. Tsirkin         d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1626315a1350SMichael S. Tsirkin     }
1627315a1350SMichael S. Tsirkin     if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1628315a1350SMichael S. Tsirkin         ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1629315a1350SMichael S. Tsirkin         ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1630315a1350SMichael S. Tsirkin         range_covers_byte(addr, l, PCI_COMMAND))
1631315a1350SMichael S. Tsirkin         pci_update_mappings(d);
1632315a1350SMichael S. Tsirkin 
16330f936247SGuoyi Tu     if (ranges_overlap(addr, l, PCI_COMMAND, 2)) {
1634315a1350SMichael S. Tsirkin         pci_update_irq_disabled(d, was_irq_disabled);
1635315a1350SMichael S. Tsirkin         memory_region_set_enabled(&d->bus_master_enable_region,
163623786d13SGerd Hoffmann                                   (pci_get_word(d->config + PCI_COMMAND)
163793829009SMichael S. Tsirkin                                    & PCI_COMMAND_MASTER) && d->has_power);
1638315a1350SMichael S. Tsirkin     }
1639315a1350SMichael S. Tsirkin 
1640d7efb7e0SKnut Omang     msi_write_config(d, addr, val_in, l);
1641d7efb7e0SKnut Omang     msix_write_config(d, addr, val_in, l);
16427c0fa8dfSKnut Omang     pcie_sriov_config_write(d, addr, val_in, l);
1643315a1350SMichael S. Tsirkin }
1644315a1350SMichael S. Tsirkin 
1645315a1350SMichael S. Tsirkin /***********************************************************/
1646315a1350SMichael S. Tsirkin /* generic PCI irq support */
1647315a1350SMichael S. Tsirkin 
1648315a1350SMichael S. Tsirkin /* 0 <= irq_num <= 3. level must be 0 or 1 */
pci_irq_handler(void * opaque,int irq_num,int level)1649d98f08f5SMarcel Apfelbaum static void pci_irq_handler(void *opaque, int irq_num, int level)
1650315a1350SMichael S. Tsirkin {
1651315a1350SMichael S. Tsirkin     PCIDevice *pci_dev = opaque;
1652315a1350SMichael S. Tsirkin     int change;
1653315a1350SMichael S. Tsirkin 
16548ddf5432SIsaku Yamahata     assert(0 <= irq_num && irq_num < PCI_NUM_PINS);
16558ddf5432SIsaku Yamahata     assert(level == 0 || level == 1);
1656315a1350SMichael S. Tsirkin     change = level - pci_irq_state(pci_dev, irq_num);
1657315a1350SMichael S. Tsirkin     if (!change)
1658315a1350SMichael S. Tsirkin         return;
1659315a1350SMichael S. Tsirkin 
1660315a1350SMichael S. Tsirkin     pci_set_irq_state(pci_dev, irq_num, level);
1661315a1350SMichael S. Tsirkin     pci_update_irq_status(pci_dev);
1662315a1350SMichael S. Tsirkin     if (pci_irq_disabled(pci_dev))
1663315a1350SMichael S. Tsirkin         return;
1664315a1350SMichael S. Tsirkin     pci_change_irq_level(pci_dev, irq_num, change);
1665315a1350SMichael S. Tsirkin }
1666315a1350SMichael S. Tsirkin 
pci_allocate_irq(PCIDevice * pci_dev)1667d98f08f5SMarcel Apfelbaum qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1668d98f08f5SMarcel Apfelbaum {
1669d98f08f5SMarcel Apfelbaum     int intx = pci_intx(pci_dev);
16708ddf5432SIsaku Yamahata     assert(0 <= intx && intx < PCI_NUM_PINS);
1671d98f08f5SMarcel Apfelbaum 
1672d98f08f5SMarcel Apfelbaum     return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1673d98f08f5SMarcel Apfelbaum }
1674d98f08f5SMarcel Apfelbaum 
pci_set_irq(PCIDevice * pci_dev,int level)1675d98f08f5SMarcel Apfelbaum void pci_set_irq(PCIDevice *pci_dev, int level)
1676d98f08f5SMarcel Apfelbaum {
1677d98f08f5SMarcel Apfelbaum     int intx = pci_intx(pci_dev);
1678d98f08f5SMarcel Apfelbaum     pci_irq_handler(pci_dev, intx, level);
1679d98f08f5SMarcel Apfelbaum }
1680d98f08f5SMarcel Apfelbaum 
1681315a1350SMichael S. Tsirkin /* Special hooks used by device assignment */
pci_bus_set_route_irq_fn(PCIBus * bus,pci_route_irq_fn route_intx_to_irq)1682315a1350SMichael S. Tsirkin void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1683315a1350SMichael S. Tsirkin {
16840889464aSAlex Williamson     assert(pci_bus_is_root(bus));
1685315a1350SMichael S. Tsirkin     bus->route_intx_to_irq = route_intx_to_irq;
1686315a1350SMichael S. Tsirkin }
1687315a1350SMichael S. Tsirkin 
pci_device_route_intx_to_irq(PCIDevice * dev,int pin)1688315a1350SMichael S. Tsirkin PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1689315a1350SMichael S. Tsirkin {
1690315a1350SMichael S. Tsirkin     PCIBus *bus;
1691315a1350SMichael S. Tsirkin 
1692315a1350SMichael S. Tsirkin     do {
169328566eabSPhilippe Mathieu-Daudé         int dev_irq = pin;
1694fd56e061SDavid Gibson         bus = pci_get_bus(dev);
1695315a1350SMichael S. Tsirkin         pin = bus->map_irq(dev, pin);
169628566eabSPhilippe Mathieu-Daudé         trace_pci_route_irq(dev_irq, DEVICE(dev)->canonical_path, pin,
169728566eabSPhilippe Mathieu-Daudé                             pci_bus_is_root(bus) ? "root-complex"
169828566eabSPhilippe Mathieu-Daudé                                     : DEVICE(bus->parent_dev)->canonical_path);
1699315a1350SMichael S. Tsirkin         dev = bus->parent_dev;
1700315a1350SMichael S. Tsirkin     } while (dev);
1701315a1350SMichael S. Tsirkin 
1702315a1350SMichael S. Tsirkin     if (!bus->route_intx_to_irq) {
1703312fd5f2SMarkus Armbruster         error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1704315a1350SMichael S. Tsirkin                      object_get_typename(OBJECT(bus->qbus.parent)));
1705315a1350SMichael S. Tsirkin         return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1706315a1350SMichael S. Tsirkin     }
1707315a1350SMichael S. Tsirkin 
1708315a1350SMichael S. Tsirkin     return bus->route_intx_to_irq(bus->irq_opaque, pin);
1709315a1350SMichael S. Tsirkin }
1710315a1350SMichael S. Tsirkin 
pci_intx_route_changed(PCIINTxRoute * old,PCIINTxRoute * new)1711315a1350SMichael S. Tsirkin bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1712315a1350SMichael S. Tsirkin {
1713315a1350SMichael S. Tsirkin     return old->mode != new->mode || old->irq != new->irq;
1714315a1350SMichael S. Tsirkin }
1715315a1350SMichael S. Tsirkin 
pci_bus_fire_intx_routing_notifier(PCIBus * bus)1716315a1350SMichael S. Tsirkin void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1717315a1350SMichael S. Tsirkin {
1718315a1350SMichael S. Tsirkin     PCIDevice *dev;
1719315a1350SMichael S. Tsirkin     PCIBus *sec;
1720315a1350SMichael S. Tsirkin     int i;
1721315a1350SMichael S. Tsirkin 
1722315a1350SMichael S. Tsirkin     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1723315a1350SMichael S. Tsirkin         dev = bus->devices[i];
1724315a1350SMichael S. Tsirkin         if (dev && dev->intx_routing_notifier) {
1725315a1350SMichael S. Tsirkin             dev->intx_routing_notifier(dev);
1726315a1350SMichael S. Tsirkin         }
1727e5368f0dSAlex Williamson     }
1728e5368f0dSAlex Williamson 
1729315a1350SMichael S. Tsirkin     QLIST_FOREACH(sec, &bus->child, sibling) {
1730315a1350SMichael S. Tsirkin         pci_bus_fire_intx_routing_notifier(sec);
1731315a1350SMichael S. Tsirkin     }
1732315a1350SMichael S. Tsirkin }
1733315a1350SMichael S. Tsirkin 
pci_device_set_intx_routing_notifier(PCIDevice * dev,PCIINTxRoutingNotifier notifier)1734315a1350SMichael S. Tsirkin void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1735315a1350SMichael S. Tsirkin                                           PCIINTxRoutingNotifier notifier)
1736315a1350SMichael S. Tsirkin {
1737315a1350SMichael S. Tsirkin     dev->intx_routing_notifier = notifier;
1738315a1350SMichael S. Tsirkin }
1739315a1350SMichael S. Tsirkin 
1740315a1350SMichael S. Tsirkin /*
1741315a1350SMichael S. Tsirkin  * PCI-to-PCI bridge specification
1742315a1350SMichael S. Tsirkin  * 9.1: Interrupt routing. Table 9-1
1743315a1350SMichael S. Tsirkin  *
1744315a1350SMichael S. Tsirkin  * the PCI Express Base Specification, Revision 2.1
17459d724e0bSPhilippe Mathieu-Daudé  * 2.2.8.1: INTx interrupt signaling - Rules
1746315a1350SMichael S. Tsirkin  *          the Implementation Note
1747315a1350SMichael S. Tsirkin  *          Table 2-20
1748315a1350SMichael S. Tsirkin  */
1749315a1350SMichael S. Tsirkin /*
1750315a1350SMichael S. Tsirkin  * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1751315a1350SMichael S. Tsirkin  * 0-origin unlike PCI interrupt pin register.
1752315a1350SMichael S. Tsirkin  */
pci_swizzle_map_irq_fn(PCIDevice * pci_dev,int pin)1753315a1350SMichael S. Tsirkin int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1754315a1350SMichael S. Tsirkin {
1755e8ec4adfSGreg Kurz     return pci_swizzle(PCI_SLOT(pci_dev->devfn), pin);
1756315a1350SMichael S. Tsirkin }
1757315a1350SMichael S. Tsirkin 
1758315a1350SMichael S. Tsirkin /***********************************************************/
1759315a1350SMichael S. Tsirkin /* monitor info on PCI */
1760315a1350SMichael S. Tsirkin 
1761315a1350SMichael S. Tsirkin static const pci_class_desc pci_class_descriptions[] =
1762315a1350SMichael S. Tsirkin {
1763315a1350SMichael S. Tsirkin     { 0x0001, "VGA controller", "display"},
1764315a1350SMichael S. Tsirkin     { 0x0100, "SCSI controller", "scsi"},
1765315a1350SMichael S. Tsirkin     { 0x0101, "IDE controller", "ide"},
1766315a1350SMichael S. Tsirkin     { 0x0102, "Floppy controller", "fdc"},
1767315a1350SMichael S. Tsirkin     { 0x0103, "IPI controller", "ipi"},
1768315a1350SMichael S. Tsirkin     { 0x0104, "RAID controller", "raid"},
1769315a1350SMichael S. Tsirkin     { 0x0106, "SATA controller"},
1770315a1350SMichael S. Tsirkin     { 0x0107, "SAS controller"},
1771315a1350SMichael S. Tsirkin     { 0x0180, "Storage controller"},
1772315a1350SMichael S. Tsirkin     { 0x0200, "Ethernet controller", "ethernet"},
1773315a1350SMichael S. Tsirkin     { 0x0201, "Token Ring controller", "token-ring"},
1774315a1350SMichael S. Tsirkin     { 0x0202, "FDDI controller", "fddi"},
1775315a1350SMichael S. Tsirkin     { 0x0203, "ATM controller", "atm"},
1776315a1350SMichael S. Tsirkin     { 0x0280, "Network controller"},
1777315a1350SMichael S. Tsirkin     { 0x0300, "VGA controller", "display", 0x00ff},
1778315a1350SMichael S. Tsirkin     { 0x0301, "XGA controller"},
1779315a1350SMichael S. Tsirkin     { 0x0302, "3D controller"},
1780315a1350SMichael S. Tsirkin     { 0x0380, "Display controller"},
1781315a1350SMichael S. Tsirkin     { 0x0400, "Video controller", "video"},
1782315a1350SMichael S. Tsirkin     { 0x0401, "Audio controller", "sound"},
1783315a1350SMichael S. Tsirkin     { 0x0402, "Phone"},
1784315a1350SMichael S. Tsirkin     { 0x0403, "Audio controller", "sound"},
1785315a1350SMichael S. Tsirkin     { 0x0480, "Multimedia controller"},
1786315a1350SMichael S. Tsirkin     { 0x0500, "RAM controller", "memory"},
1787315a1350SMichael S. Tsirkin     { 0x0501, "Flash controller", "flash"},
1788315a1350SMichael S. Tsirkin     { 0x0580, "Memory controller"},
1789315a1350SMichael S. Tsirkin     { 0x0600, "Host bridge", "host"},
1790315a1350SMichael S. Tsirkin     { 0x0601, "ISA bridge", "isa"},
1791315a1350SMichael S. Tsirkin     { 0x0602, "EISA bridge", "eisa"},
1792315a1350SMichael S. Tsirkin     { 0x0603, "MC bridge", "mca"},
17934c41425dSGerd Hoffmann     { 0x0604, "PCI bridge", "pci-bridge"},
1794315a1350SMichael S. Tsirkin     { 0x0605, "PCMCIA bridge", "pcmcia"},
1795315a1350SMichael S. Tsirkin     { 0x0606, "NUBUS bridge", "nubus"},
1796315a1350SMichael S. Tsirkin     { 0x0607, "CARDBUS bridge", "cardbus"},
1797315a1350SMichael S. Tsirkin     { 0x0608, "RACEWAY bridge"},
1798315a1350SMichael S. Tsirkin     { 0x0680, "Bridge"},
1799315a1350SMichael S. Tsirkin     { 0x0700, "Serial port", "serial"},
1800315a1350SMichael S. Tsirkin     { 0x0701, "Parallel port", "parallel"},
1801315a1350SMichael S. Tsirkin     { 0x0800, "Interrupt controller", "interrupt-controller"},
1802315a1350SMichael S. Tsirkin     { 0x0801, "DMA controller", "dma-controller"},
1803315a1350SMichael S. Tsirkin     { 0x0802, "Timer", "timer"},
1804315a1350SMichael S. Tsirkin     { 0x0803, "RTC", "rtc"},
1805315a1350SMichael S. Tsirkin     { 0x0900, "Keyboard", "keyboard"},
1806315a1350SMichael S. Tsirkin     { 0x0901, "Pen", "pen"},
1807315a1350SMichael S. Tsirkin     { 0x0902, "Mouse", "mouse"},
1808315a1350SMichael S. Tsirkin     { 0x0A00, "Dock station", "dock", 0x00ff},
1809315a1350SMichael S. Tsirkin     { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1810d1e9e646SRebecca Cran     { 0x0c00, "Firewire controller", "firewire"},
1811315a1350SMichael S. Tsirkin     { 0x0c01, "Access bus controller", "access-bus"},
1812315a1350SMichael S. Tsirkin     { 0x0c02, "SSA controller", "ssa"},
1813315a1350SMichael S. Tsirkin     { 0x0c03, "USB controller", "usb"},
1814315a1350SMichael S. Tsirkin     { 0x0c04, "Fibre channel controller", "fibre-channel"},
1815315a1350SMichael S. Tsirkin     { 0x0c05, "SMBus"},
1816315a1350SMichael S. Tsirkin     { 0, NULL}
1817315a1350SMichael S. Tsirkin };
1818315a1350SMichael S. Tsirkin 
pci_for_each_device_under_bus_reverse(PCIBus * bus,pci_bus_dev_fn fn,void * opaque)18192914fc61SPeter Xu void pci_for_each_device_under_bus_reverse(PCIBus *bus,
1820b3dcf94fSPeter Xu                                            pci_bus_dev_fn fn,
1821a8eeafdaSGreg Kurz                                            void *opaque)
1822a8eeafdaSGreg Kurz {
1823a8eeafdaSGreg Kurz     PCIDevice *d;
1824a8eeafdaSGreg Kurz     int devfn;
1825a8eeafdaSGreg Kurz 
1826a8eeafdaSGreg Kurz     for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1827a8eeafdaSGreg Kurz         d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
1828a8eeafdaSGreg Kurz         if (d) {
1829a8eeafdaSGreg Kurz             fn(bus, d, opaque);
1830a8eeafdaSGreg Kurz         }
1831a8eeafdaSGreg Kurz     }
1832a8eeafdaSGreg Kurz }
1833a8eeafdaSGreg Kurz 
pci_for_each_device_reverse(PCIBus * bus,int bus_num,pci_bus_dev_fn fn,void * opaque)1834a8eeafdaSGreg Kurz void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
1835b3dcf94fSPeter Xu                                  pci_bus_dev_fn fn, void *opaque)
1836a8eeafdaSGreg Kurz {
1837a8eeafdaSGreg Kurz     bus = pci_find_bus_nr(bus, bus_num);
1838a8eeafdaSGreg Kurz 
1839a8eeafdaSGreg Kurz     if (bus) {
1840a8eeafdaSGreg Kurz         pci_for_each_device_under_bus_reverse(bus, fn, opaque);
1841a8eeafdaSGreg Kurz     }
1842a8eeafdaSGreg Kurz }
1843a8eeafdaSGreg Kurz 
pci_for_each_device_under_bus(PCIBus * bus,pci_bus_dev_fn fn,void * opaque)18442914fc61SPeter Xu void pci_for_each_device_under_bus(PCIBus *bus,
1845b3dcf94fSPeter Xu                                    pci_bus_dev_fn fn, void *opaque)
1846315a1350SMichael S. Tsirkin {
1847315a1350SMichael S. Tsirkin     PCIDevice *d;
1848315a1350SMichael S. Tsirkin     int devfn;
1849315a1350SMichael S. Tsirkin 
1850315a1350SMichael S. Tsirkin     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1851315a1350SMichael S. Tsirkin         d = bus->devices[devfn];
1852315a1350SMichael S. Tsirkin         if (d) {
1853315a1350SMichael S. Tsirkin             fn(bus, d, opaque);
1854315a1350SMichael S. Tsirkin         }
1855315a1350SMichael S. Tsirkin     }
1856315a1350SMichael S. Tsirkin }
1857315a1350SMichael S. Tsirkin 
pci_for_each_device(PCIBus * bus,int bus_num,pci_bus_dev_fn fn,void * opaque)1858315a1350SMichael S. Tsirkin void pci_for_each_device(PCIBus *bus, int bus_num,
1859b3dcf94fSPeter Xu                          pci_bus_dev_fn fn, void *opaque)
1860315a1350SMichael S. Tsirkin {
1861315a1350SMichael S. Tsirkin     bus = pci_find_bus_nr(bus, bus_num);
1862315a1350SMichael S. Tsirkin 
1863315a1350SMichael S. Tsirkin     if (bus) {
1864315a1350SMichael S. Tsirkin         pci_for_each_device_under_bus(bus, fn, opaque);
1865315a1350SMichael S. Tsirkin     }
1866315a1350SMichael S. Tsirkin }
1867315a1350SMichael S. Tsirkin 
get_class_desc(int class)1868987b73b3SMarkus Armbruster const pci_class_desc *get_class_desc(int class)
1869315a1350SMichael S. Tsirkin {
1870315a1350SMichael S. Tsirkin     const pci_class_desc *desc;
1871315a1350SMichael S. Tsirkin 
1872315a1350SMichael S. Tsirkin     desc = pci_class_descriptions;
1873315a1350SMichael S. Tsirkin     while (desc->desc && class != desc->class) {
1874315a1350SMichael S. Tsirkin         desc++;
1875315a1350SMichael S. Tsirkin     }
1876315a1350SMichael S. Tsirkin 
1877315a1350SMichael S. Tsirkin     return desc;
1878315a1350SMichael S. Tsirkin }
1879315a1350SMichael S. Tsirkin 
pci_init_nic_devices(PCIBus * bus,const char * default_model)18801785ae69SDavid Woodhouse void pci_init_nic_devices(PCIBus *bus, const char *default_model)
18811785ae69SDavid Woodhouse {
18821785ae69SDavid Woodhouse     qemu_create_nic_bus_devices(&bus->qbus, TYPE_PCI_DEVICE, default_model,
18831785ae69SDavid Woodhouse                                 "virtio", "virtio-net-pci");
18841785ae69SDavid Woodhouse }
18851785ae69SDavid Woodhouse 
pci_init_nic_in_slot(PCIBus * rootbus,const char * model,const char * alias,const char * devaddr)18861785ae69SDavid Woodhouse bool pci_init_nic_in_slot(PCIBus *rootbus, const char *model,
18871785ae69SDavid Woodhouse                           const char *alias, const char *devaddr)
18881785ae69SDavid Woodhouse {
18891785ae69SDavid Woodhouse     NICInfo *nd = qemu_find_nic_info(model, true, alias);
18901785ae69SDavid Woodhouse     int dom, busnr, devfn;
18911785ae69SDavid Woodhouse     PCIDevice *pci_dev;
18921785ae69SDavid Woodhouse     unsigned slot;
18931785ae69SDavid Woodhouse     PCIBus *bus;
18941785ae69SDavid Woodhouse 
18951785ae69SDavid Woodhouse     if (!nd) {
18961785ae69SDavid Woodhouse         return false;
18971785ae69SDavid Woodhouse     }
18981785ae69SDavid Woodhouse 
18991785ae69SDavid Woodhouse     if (!devaddr || pci_parse_devaddr(devaddr, &dom, &busnr, &slot, NULL) < 0) {
19001785ae69SDavid Woodhouse         error_report("Invalid PCI device address %s for device %s",
19011785ae69SDavid Woodhouse                      devaddr, model);
19021785ae69SDavid Woodhouse         exit(1);
19031785ae69SDavid Woodhouse     }
19041785ae69SDavid Woodhouse 
19051785ae69SDavid Woodhouse     if (dom != 0) {
19061785ae69SDavid Woodhouse         error_report("No support for non-zero PCI domains");
19071785ae69SDavid Woodhouse         exit(1);
19081785ae69SDavid Woodhouse     }
19091785ae69SDavid Woodhouse 
19101785ae69SDavid Woodhouse     devfn = PCI_DEVFN(slot, 0);
19111785ae69SDavid Woodhouse 
19121785ae69SDavid Woodhouse     bus = pci_find_bus_nr(rootbus, busnr);
19131785ae69SDavid Woodhouse     if (!bus) {
19141785ae69SDavid Woodhouse         error_report("Invalid PCI device address %s for device %s",
19151785ae69SDavid Woodhouse                      devaddr, model);
19161785ae69SDavid Woodhouse         exit(1);
19171785ae69SDavid Woodhouse     }
19181785ae69SDavid Woodhouse 
19191785ae69SDavid Woodhouse     pci_dev = pci_new(devfn, model);
19201785ae69SDavid Woodhouse     qdev_set_nic_properties(&pci_dev->qdev, nd);
19211785ae69SDavid Woodhouse     pci_realize_and_unref(pci_dev, bus, &error_fatal);
19221785ae69SDavid Woodhouse     return true;
19231785ae69SDavid Woodhouse }
19241785ae69SDavid Woodhouse 
pci_vga_init(PCIBus * bus)1925315a1350SMichael S. Tsirkin PCIDevice *pci_vga_init(PCIBus *bus)
1926315a1350SMichael S. Tsirkin {
1927f9bcb2d6SGautam Agrawal     vga_interface_created = true;
1928315a1350SMichael S. Tsirkin     switch (vga_interface_type) {
1929315a1350SMichael S. Tsirkin     case VGA_CIRRUS:
1930315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "cirrus-vga");
1931315a1350SMichael S. Tsirkin     case VGA_QXL:
1932315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "qxl-vga");
1933315a1350SMichael S. Tsirkin     case VGA_STD:
1934315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "VGA");
1935315a1350SMichael S. Tsirkin     case VGA_VMWARE:
1936315a1350SMichael S. Tsirkin         return pci_create_simple(bus, -1, "vmware-svga");
1937a94f0c5cSGerd Hoffmann     case VGA_VIRTIO:
1938a94f0c5cSGerd Hoffmann         return pci_create_simple(bus, -1, "virtio-vga");
1939315a1350SMichael S. Tsirkin     case VGA_NONE:
1940315a1350SMichael S. Tsirkin     default: /* Other non-PCI types. Checking for unsupported types is already
1941315a1350SMichael S. Tsirkin                 done in vl.c. */
1942315a1350SMichael S. Tsirkin         return NULL;
1943315a1350SMichael S. Tsirkin     }
1944315a1350SMichael S. Tsirkin }
1945315a1350SMichael S. Tsirkin 
1946315a1350SMichael S. Tsirkin /* Whether a given bus number is in range of the secondary
1947315a1350SMichael S. Tsirkin  * bus of the given bridge device. */
pci_secondary_bus_in_range(PCIDevice * dev,int bus_num)1948315a1350SMichael S. Tsirkin static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1949315a1350SMichael S. Tsirkin {
1950315a1350SMichael S. Tsirkin     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1951315a1350SMichael S. Tsirkin              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
195209e5b819SMarcel Apfelbaum         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1953315a1350SMichael S. Tsirkin         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1954315a1350SMichael S. Tsirkin }
1955315a1350SMichael S. Tsirkin 
195609e5b819SMarcel Apfelbaum /* Whether a given bus number is in a range of a root bus */
pci_root_bus_in_range(PCIBus * bus,int bus_num)195709e5b819SMarcel Apfelbaum static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
195809e5b819SMarcel Apfelbaum {
195909e5b819SMarcel Apfelbaum     int i;
196009e5b819SMarcel Apfelbaum 
196109e5b819SMarcel Apfelbaum     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
196209e5b819SMarcel Apfelbaum         PCIDevice *dev = bus->devices[i];
196309e5b819SMarcel Apfelbaum 
1964ad494274SIgor Mammedov         if (dev && IS_PCI_BRIDGE(dev)) {
196509e5b819SMarcel Apfelbaum             if (pci_secondary_bus_in_range(dev, bus_num)) {
196609e5b819SMarcel Apfelbaum                 return true;
196709e5b819SMarcel Apfelbaum             }
196809e5b819SMarcel Apfelbaum         }
196909e5b819SMarcel Apfelbaum     }
197009e5b819SMarcel Apfelbaum 
197109e5b819SMarcel Apfelbaum     return false;
197209e5b819SMarcel Apfelbaum }
197309e5b819SMarcel Apfelbaum 
pci_find_bus_nr(PCIBus * bus,int bus_num)1974987b73b3SMarkus Armbruster PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1975315a1350SMichael S. Tsirkin {
1976315a1350SMichael S. Tsirkin     PCIBus *sec;
1977315a1350SMichael S. Tsirkin 
1978315a1350SMichael S. Tsirkin     if (!bus) {
1979315a1350SMichael S. Tsirkin         return NULL;
1980315a1350SMichael S. Tsirkin     }
1981315a1350SMichael S. Tsirkin 
1982315a1350SMichael S. Tsirkin     if (pci_bus_num(bus) == bus_num) {
1983315a1350SMichael S. Tsirkin         return bus;
1984315a1350SMichael S. Tsirkin     }
1985315a1350SMichael S. Tsirkin 
1986315a1350SMichael S. Tsirkin     /* Consider all bus numbers in range for the host pci bridge. */
19870889464aSAlex Williamson     if (!pci_bus_is_root(bus) &&
1988315a1350SMichael S. Tsirkin         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1989315a1350SMichael S. Tsirkin         return NULL;
1990315a1350SMichael S. Tsirkin     }
1991315a1350SMichael S. Tsirkin 
1992315a1350SMichael S. Tsirkin     /* try child bus */
1993315a1350SMichael S. Tsirkin     for (; bus; bus = sec) {
1994315a1350SMichael S. Tsirkin         QLIST_FOREACH(sec, &bus->child, sibling) {
199509e5b819SMarcel Apfelbaum             if (pci_bus_num(sec) == bus_num) {
1996315a1350SMichael S. Tsirkin                 return sec;
1997315a1350SMichael S. Tsirkin             }
199809e5b819SMarcel Apfelbaum             /* PXB buses assumed to be children of bus 0 */
199909e5b819SMarcel Apfelbaum             if (pci_bus_is_root(sec)) {
200009e5b819SMarcel Apfelbaum                 if (pci_root_bus_in_range(sec, bus_num)) {
200109e5b819SMarcel Apfelbaum                     break;
200209e5b819SMarcel Apfelbaum                 }
200309e5b819SMarcel Apfelbaum             } else {
2004315a1350SMichael S. Tsirkin                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
2005315a1350SMichael S. Tsirkin                     break;
2006315a1350SMichael S. Tsirkin                 }
2007315a1350SMichael S. Tsirkin             }
2008315a1350SMichael S. Tsirkin         }
200909e5b819SMarcel Apfelbaum     }
2010315a1350SMichael S. Tsirkin 
2011315a1350SMichael S. Tsirkin     return NULL;
2012315a1350SMichael S. Tsirkin }
2013315a1350SMichael S. Tsirkin 
pci_for_each_bus_depth_first(PCIBus * bus,pci_bus_ret_fn begin,pci_bus_fn end,void * parent_state)2014b3dcf94fSPeter Xu void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
2015b3dcf94fSPeter Xu                                   pci_bus_fn end, void *parent_state)
2016eb0acfddSMichael S. Tsirkin {
2017eb0acfddSMichael S. Tsirkin     PCIBus *sec;
2018eb0acfddSMichael S. Tsirkin     void *state;
2019eb0acfddSMichael S. Tsirkin 
2020eb0acfddSMichael S. Tsirkin     if (!bus) {
2021eb0acfddSMichael S. Tsirkin         return;
2022eb0acfddSMichael S. Tsirkin     }
2023eb0acfddSMichael S. Tsirkin 
2024eb0acfddSMichael S. Tsirkin     if (begin) {
2025eb0acfddSMichael S. Tsirkin         state = begin(bus, parent_state);
2026eb0acfddSMichael S. Tsirkin     } else {
2027eb0acfddSMichael S. Tsirkin         state = parent_state;
2028eb0acfddSMichael S. Tsirkin     }
2029eb0acfddSMichael S. Tsirkin 
2030eb0acfddSMichael S. Tsirkin     QLIST_FOREACH(sec, &bus->child, sibling) {
2031eb0acfddSMichael S. Tsirkin         pci_for_each_bus_depth_first(sec, begin, end, state);
2032eb0acfddSMichael S. Tsirkin     }
2033eb0acfddSMichael S. Tsirkin 
2034eb0acfddSMichael S. Tsirkin     if (end) {
2035eb0acfddSMichael S. Tsirkin         end(bus, state);
2036eb0acfddSMichael S. Tsirkin     }
2037eb0acfddSMichael S. Tsirkin }
2038eb0acfddSMichael S. Tsirkin 
2039eb0acfddSMichael S. Tsirkin 
pci_find_device(PCIBus * bus,int bus_num,uint8_t devfn)2040315a1350SMichael S. Tsirkin PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
2041315a1350SMichael S. Tsirkin {
2042315a1350SMichael S. Tsirkin     bus = pci_find_bus_nr(bus, bus_num);
2043315a1350SMichael S. Tsirkin 
2044315a1350SMichael S. Tsirkin     if (!bus)
2045315a1350SMichael S. Tsirkin         return NULL;
2046315a1350SMichael S. Tsirkin 
2047315a1350SMichael S. Tsirkin     return bus->devices[devfn];
2048315a1350SMichael S. Tsirkin }
2049315a1350SMichael S. Tsirkin 
2050041b1c40SIgor Mammedov #define ONBOARD_INDEX_MAX (16 * 1024 - 1)
2051041b1c40SIgor Mammedov 
pci_qdev_realize(DeviceState * qdev,Error ** errp)2052133e9b22SMarkus Armbruster static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2053315a1350SMichael S. Tsirkin {
2054315a1350SMichael S. Tsirkin     PCIDevice *pci_dev = (PCIDevice *)qdev;
2055315a1350SMichael S. Tsirkin     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2056d61a363dSYoni Bettan     ObjectClass *klass = OBJECT_CLASS(pc);
2057133e9b22SMarkus Armbruster     Error *local_err = NULL;
2058315a1350SMichael S. Tsirkin     bool is_default_rom;
20594f5b6a05SJens Freimann     uint16_t class_id;
2060315a1350SMichael S. Tsirkin 
2061041b1c40SIgor Mammedov     /*
2062041b1c40SIgor Mammedov      * capped by systemd (see: udev-builtin-net_id.c)
2063041b1c40SIgor Mammedov      * as it's the only known user honor it to avoid users
2064041b1c40SIgor Mammedov      * misconfigure QEMU and then wonder why acpi-index doesn't work
2065041b1c40SIgor Mammedov      */
2066041b1c40SIgor Mammedov     if (pci_dev->acpi_index > ONBOARD_INDEX_MAX) {
2067041b1c40SIgor Mammedov         error_setg(errp, "acpi-index should be less or equal to %u",
2068041b1c40SIgor Mammedov                    ONBOARD_INDEX_MAX);
2069041b1c40SIgor Mammedov         return;
2070041b1c40SIgor Mammedov     }
2071041b1c40SIgor Mammedov 
2072041b1c40SIgor Mammedov     /*
2073041b1c40SIgor Mammedov      * make sure that acpi-index is unique across all present PCI devices
2074041b1c40SIgor Mammedov      */
2075041b1c40SIgor Mammedov     if (pci_dev->acpi_index) {
2076041b1c40SIgor Mammedov         GSequence *used_indexes = pci_acpi_index_list();
2077041b1c40SIgor Mammedov 
2078041b1c40SIgor Mammedov         if (g_sequence_lookup(used_indexes,
2079041b1c40SIgor Mammedov                               GINT_TO_POINTER(pci_dev->acpi_index),
2080041b1c40SIgor Mammedov                               g_cmp_uint32, NULL)) {
2081041b1c40SIgor Mammedov             error_setg(errp, "a PCI device with acpi-index = %" PRIu32
2082041b1c40SIgor Mammedov                        " already exist", pci_dev->acpi_index);
2083041b1c40SIgor Mammedov             return;
2084041b1c40SIgor Mammedov         }
2085041b1c40SIgor Mammedov         g_sequence_insert_sorted(used_indexes,
2086041b1c40SIgor Mammedov                                  GINT_TO_POINTER(pci_dev->acpi_index),
2087041b1c40SIgor Mammedov                                  g_cmp_uint32, NULL);
2088041b1c40SIgor Mammedov     }
2089041b1c40SIgor Mammedov 
20906a67577dSAkihiko Odaki     if (pci_dev->romsize != UINT32_MAX && !is_power_of_2(pci_dev->romsize)) {
209108b1df8fSPaolo Bonzini         error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
209208b1df8fSPaolo Bonzini         return;
209308b1df8fSPaolo Bonzini     }
209408b1df8fSPaolo Bonzini 
2095d61a363dSYoni Bettan     /* initialize cap_present for pci_is_express() and pci_config_size(),
2096d61a363dSYoni Bettan      * Note that hybrid PCIs are not set automatically and need to manage
2097d61a363dSYoni Bettan      * QEMU_PCI_CAP_EXPRESS manually */
2098d61a363dSYoni Bettan     if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2099d61a363dSYoni Bettan        !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2100315a1350SMichael S. Tsirkin         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2101315a1350SMichael S. Tsirkin     }
2102315a1350SMichael S. Tsirkin 
2103cf04aba2SBen Widawsky     if (object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE)) {
2104cf04aba2SBen Widawsky         pci_dev->cap_present |= QEMU_PCIE_CAP_CXL;
2105cf04aba2SBen Widawsky     }
2106cf04aba2SBen Widawsky 
2107fd56e061SDavid Gibson     pci_dev = do_pci_register_device(pci_dev,
2108315a1350SMichael S. Tsirkin                                      object_get_typename(OBJECT(qdev)),
2109133e9b22SMarkus Armbruster                                      pci_dev->devfn, errp);
2110315a1350SMichael S. Tsirkin     if (pci_dev == NULL)
2111133e9b22SMarkus Armbruster         return;
21122897ae02SIgor Mammedov 
21137ee6c1e1SMarkus Armbruster     if (pc->realize) {
21147ee6c1e1SMarkus Armbruster         pc->realize(pci_dev, &local_err);
21157ee6c1e1SMarkus Armbruster         if (local_err) {
21167ee6c1e1SMarkus Armbruster             error_propagate(errp, local_err);
2117315a1350SMichael S. Tsirkin             do_pci_unregister_device(pci_dev);
2118133e9b22SMarkus Armbruster             return;
2119315a1350SMichael S. Tsirkin         }
2120315a1350SMichael S. Tsirkin     }
2121315a1350SMichael S. Tsirkin 
2122ca92eb5dSAni Sinha     /*
2123ca92eb5dSAni Sinha      * A PCIe Downstream Port that do not have ARI Forwarding enabled must
2124ca92eb5dSAni Sinha      * associate only Device 0 with the device attached to the bus
2125ca92eb5dSAni Sinha      * representing the Link from the Port (PCIe base spec rev 4.0 ver 0.3,
2126ca92eb5dSAni Sinha      * sec 7.3.1).
2127ca92eb5dSAni Sinha      * With ARI, PCI_SLOT() can return non-zero value as the traditional
2128ca92eb5dSAni Sinha      * 5-bit Device Number and 3-bit Function Number fields in its associated
2129ca92eb5dSAni Sinha      * Routing IDs, Requester IDs and Completer IDs are interpreted as a
2130ca92eb5dSAni Sinha      * single 8-bit Function Number. Hence, ignore ARI capable devices.
2131ca92eb5dSAni Sinha      */
2132ca92eb5dSAni Sinha     if (pci_is_express(pci_dev) &&
2133ca92eb5dSAni Sinha         !pcie_find_capability(pci_dev, PCI_EXT_CAP_ID_ARI) &&
2134ca92eb5dSAni Sinha         pcie_has_upstream_port(pci_dev) &&
2135ca92eb5dSAni Sinha         PCI_SLOT(pci_dev->devfn)) {
2136ca92eb5dSAni Sinha         warn_report("PCI: slot %d is not valid for %s,"
2137ca92eb5dSAni Sinha                     " parent device only allows plugging into slot 0.",
2138ca92eb5dSAni Sinha                     PCI_SLOT(pci_dev->devfn), pci_dev->name);
2139ca92eb5dSAni Sinha     }
2140ca92eb5dSAni Sinha 
21414f5b6a05SJens Freimann     if (pci_dev->failover_pair_id) {
21424f5b6a05SJens Freimann         if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
21434f5b6a05SJens Freimann             error_setg(errp, "failover primary device must be on "
21444f5b6a05SJens Freimann                              "PCIExpress bus");
2145b69c3c21SMarkus Armbruster             pci_qdev_unrealize(DEVICE(pci_dev));
21464f5b6a05SJens Freimann             return;
21474f5b6a05SJens Freimann         }
21484f5b6a05SJens Freimann         class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
21494f5b6a05SJens Freimann         if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
21504f5b6a05SJens Freimann             error_setg(errp, "failover primary device is not an "
21514f5b6a05SJens Freimann                              "Ethernet device");
2152b69c3c21SMarkus Armbruster             pci_qdev_unrealize(DEVICE(pci_dev));
21534f5b6a05SJens Freimann             return;
21544f5b6a05SJens Freimann         }
2155b01a4901SLaurent Vivier         if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2156b01a4901SLaurent Vivier             || (PCI_FUNC(pci_dev->devfn) != 0)) {
21574f5b6a05SJens Freimann             error_setg(errp, "failover: primary device must be in its own "
21584f5b6a05SJens Freimann                               "PCI slot");
2159b69c3c21SMarkus Armbruster             pci_qdev_unrealize(DEVICE(pci_dev));
21604f5b6a05SJens Freimann             return;
21614f5b6a05SJens Freimann         }
2162a1190ab6SJens Freimann         qdev->allow_unplug_during_migration = true;
21634f5b6a05SJens Freimann     }
21644f5b6a05SJens Freimann 
2165315a1350SMichael S. Tsirkin     /* rom loading */
2166315a1350SMichael S. Tsirkin     is_default_rom = false;
2167315a1350SMichael S. Tsirkin     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2168315a1350SMichael S. Tsirkin         pci_dev->romfile = g_strdup(pc->romfile);
2169315a1350SMichael S. Tsirkin         is_default_rom = true;
2170315a1350SMichael S. Tsirkin     }
2171178e785fSMarcel Apfelbaum 
2172133e9b22SMarkus Armbruster     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2173133e9b22SMarkus Armbruster     if (local_err) {
2174133e9b22SMarkus Armbruster         error_propagate(errp, local_err);
2175b69c3c21SMarkus Armbruster         pci_qdev_unrealize(DEVICE(pci_dev));
2176133e9b22SMarkus Armbruster         return;
2177178e785fSMarcel Apfelbaum     }
217823786d13SGerd Hoffmann 
217923786d13SGerd Hoffmann     pci_set_power(pci_dev, true);
218008cf3dc6SJagannathan Raman 
218108cf3dc6SJagannathan Raman     pci_dev->msi_trigger = pci_msi_trigger;
2182315a1350SMichael S. Tsirkin }
2183315a1350SMichael S. Tsirkin 
pci_new_internal(int devfn,bool multifunction,const char * name)2184c925f40aSBernhard Beschow static PCIDevice *pci_new_internal(int devfn, bool multifunction,
21857411aa63SMarkus Armbruster                                    const char *name)
21867411aa63SMarkus Armbruster {
21877411aa63SMarkus Armbruster     DeviceState *dev;
21887411aa63SMarkus Armbruster 
21897411aa63SMarkus Armbruster     dev = qdev_new(name);
21907411aa63SMarkus Armbruster     qdev_prop_set_int32(dev, "addr", devfn);
21917411aa63SMarkus Armbruster     qdev_prop_set_bit(dev, "multifunction", multifunction);
21927411aa63SMarkus Armbruster     return PCI_DEVICE(dev);
21937411aa63SMarkus Armbruster }
21947411aa63SMarkus Armbruster 
pci_new_multifunction(int devfn,const char * name)2195c925f40aSBernhard Beschow PCIDevice *pci_new_multifunction(int devfn, const char *name)
2196c925f40aSBernhard Beschow {
2197c925f40aSBernhard Beschow     return pci_new_internal(devfn, true, name);
2198c925f40aSBernhard Beschow }
2199c925f40aSBernhard Beschow 
pci_new(int devfn,const char * name)22007411aa63SMarkus Armbruster PCIDevice *pci_new(int devfn, const char *name)
22017411aa63SMarkus Armbruster {
2202c925f40aSBernhard Beschow     return pci_new_internal(devfn, false, name);
22037411aa63SMarkus Armbruster }
22047411aa63SMarkus Armbruster 
pci_realize_and_unref(PCIDevice * dev,PCIBus * bus,Error ** errp)22057411aa63SMarkus Armbruster bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
22067411aa63SMarkus Armbruster {
22077411aa63SMarkus Armbruster     return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
22087411aa63SMarkus Armbruster }
22097411aa63SMarkus Armbruster 
pci_create_simple_multifunction(PCIBus * bus,int devfn,const char * name)2210315a1350SMichael S. Tsirkin PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2211315a1350SMichael S. Tsirkin                                            const char *name)
2212315a1350SMichael S. Tsirkin {
2213c925f40aSBernhard Beschow     PCIDevice *dev = pci_new_multifunction(devfn, name);
22149307d06dSMarkus Armbruster     pci_realize_and_unref(dev, bus, &error_fatal);
2215315a1350SMichael S. Tsirkin     return dev;
2216315a1350SMichael S. Tsirkin }
2217315a1350SMichael S. Tsirkin 
pci_create_simple(PCIBus * bus,int devfn,const char * name)2218315a1350SMichael S. Tsirkin PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2219315a1350SMichael S. Tsirkin {
2220e052944aSBernhard Beschow     PCIDevice *dev = pci_new(devfn, name);
2221e052944aSBernhard Beschow     pci_realize_and_unref(dev, bus, &error_fatal);
2222e052944aSBernhard Beschow     return dev;
2223315a1350SMichael S. Tsirkin }
2224315a1350SMichael S. Tsirkin 
pci_find_space(PCIDevice * pdev,uint8_t size)2225315a1350SMichael S. Tsirkin static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2226315a1350SMichael S. Tsirkin {
2227315a1350SMichael S. Tsirkin     int offset = PCI_CONFIG_HEADER_SIZE;
2228315a1350SMichael S. Tsirkin     int i;
2229315a1350SMichael S. Tsirkin     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2230315a1350SMichael S. Tsirkin         if (pdev->used[i])
2231315a1350SMichael S. Tsirkin             offset = i + 1;
2232315a1350SMichael S. Tsirkin         else if (i - offset + 1 == size)
2233315a1350SMichael S. Tsirkin             return offset;
2234315a1350SMichael S. Tsirkin     }
2235315a1350SMichael S. Tsirkin     return 0;
2236315a1350SMichael S. Tsirkin }
2237315a1350SMichael S. Tsirkin 
pci_find_capability_list(PCIDevice * pdev,uint8_t cap_id,uint8_t * prev_p)2238315a1350SMichael S. Tsirkin static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2239315a1350SMichael S. Tsirkin                                         uint8_t *prev_p)
2240315a1350SMichael S. Tsirkin {
2241315a1350SMichael S. Tsirkin     uint8_t next, prev;
2242315a1350SMichael S. Tsirkin 
2243315a1350SMichael S. Tsirkin     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2244315a1350SMichael S. Tsirkin         return 0;
2245315a1350SMichael S. Tsirkin 
2246315a1350SMichael S. Tsirkin     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2247315a1350SMichael S. Tsirkin          prev = next + PCI_CAP_LIST_NEXT)
2248315a1350SMichael S. Tsirkin         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2249315a1350SMichael S. Tsirkin             break;
2250315a1350SMichael S. Tsirkin 
2251315a1350SMichael S. Tsirkin     if (prev_p)
2252315a1350SMichael S. Tsirkin         *prev_p = prev;
2253315a1350SMichael S. Tsirkin     return next;
2254315a1350SMichael S. Tsirkin }
2255315a1350SMichael S. Tsirkin 
pci_find_capability_at_offset(PCIDevice * pdev,uint8_t offset)2256315a1350SMichael S. Tsirkin static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2257315a1350SMichael S. Tsirkin {
2258315a1350SMichael S. Tsirkin     uint8_t next, prev, found = 0;
2259315a1350SMichael S. Tsirkin 
2260315a1350SMichael S. Tsirkin     if (!(pdev->used[offset])) {
2261315a1350SMichael S. Tsirkin         return 0;
2262315a1350SMichael S. Tsirkin     }
2263315a1350SMichael S. Tsirkin 
2264315a1350SMichael S. Tsirkin     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2265315a1350SMichael S. Tsirkin 
2266315a1350SMichael S. Tsirkin     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2267315a1350SMichael S. Tsirkin          prev = next + PCI_CAP_LIST_NEXT) {
2268315a1350SMichael S. Tsirkin         if (next <= offset && next > found) {
2269315a1350SMichael S. Tsirkin             found = next;
2270315a1350SMichael S. Tsirkin         }
2271315a1350SMichael S. Tsirkin     }
2272315a1350SMichael S. Tsirkin     return found;
2273315a1350SMichael S. Tsirkin }
2274315a1350SMichael S. Tsirkin 
2275315a1350SMichael S. Tsirkin /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2276315a1350SMichael S. Tsirkin    This is needed for an option rom which is used for more than one device. */
pci_patch_ids(PCIDevice * pdev,uint8_t * ptr,uint32_t size)22777c16b5bbSPaolo Bonzini static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2278315a1350SMichael S. Tsirkin {
2279315a1350SMichael S. Tsirkin     uint16_t vendor_id;
2280315a1350SMichael S. Tsirkin     uint16_t device_id;
2281315a1350SMichael S. Tsirkin     uint16_t rom_vendor_id;
2282315a1350SMichael S. Tsirkin     uint16_t rom_device_id;
2283315a1350SMichael S. Tsirkin     uint16_t rom_magic;
2284315a1350SMichael S. Tsirkin     uint16_t pcir_offset;
2285315a1350SMichael S. Tsirkin     uint8_t checksum;
2286315a1350SMichael S. Tsirkin 
2287315a1350SMichael S. Tsirkin     /* Words in rom data are little endian (like in PCI configuration),
2288315a1350SMichael S. Tsirkin        so they can be read / written with pci_get_word / pci_set_word. */
2289315a1350SMichael S. Tsirkin 
2290315a1350SMichael S. Tsirkin     /* Only a valid rom will be patched. */
2291315a1350SMichael S. Tsirkin     rom_magic = pci_get_word(ptr);
2292315a1350SMichael S. Tsirkin     if (rom_magic != 0xaa55) {
2293315a1350SMichael S. Tsirkin         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2294315a1350SMichael S. Tsirkin         return;
2295315a1350SMichael S. Tsirkin     }
2296315a1350SMichael S. Tsirkin     pcir_offset = pci_get_word(ptr + 0x18);
2297315a1350SMichael S. Tsirkin     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2298315a1350SMichael S. Tsirkin         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2299315a1350SMichael S. Tsirkin         return;
2300315a1350SMichael S. Tsirkin     }
2301315a1350SMichael S. Tsirkin 
2302315a1350SMichael S. Tsirkin     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2303315a1350SMichael S. Tsirkin     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2304315a1350SMichael S. Tsirkin     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2305315a1350SMichael S. Tsirkin     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2306315a1350SMichael S. Tsirkin 
2307315a1350SMichael S. Tsirkin     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2308315a1350SMichael S. Tsirkin                 vendor_id, device_id, rom_vendor_id, rom_device_id);
2309315a1350SMichael S. Tsirkin 
2310315a1350SMichael S. Tsirkin     checksum = ptr[6];
2311315a1350SMichael S. Tsirkin 
2312315a1350SMichael S. Tsirkin     if (vendor_id != rom_vendor_id) {
2313315a1350SMichael S. Tsirkin         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2314315a1350SMichael S. Tsirkin         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2315315a1350SMichael S. Tsirkin         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2316315a1350SMichael S. Tsirkin         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2317315a1350SMichael S. Tsirkin         ptr[6] = checksum;
2318315a1350SMichael S. Tsirkin         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2319315a1350SMichael S. Tsirkin     }
2320315a1350SMichael S. Tsirkin 
2321315a1350SMichael S. Tsirkin     if (device_id != rom_device_id) {
2322315a1350SMichael S. Tsirkin         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2323315a1350SMichael S. Tsirkin         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2324315a1350SMichael S. Tsirkin         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2325315a1350SMichael S. Tsirkin         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2326315a1350SMichael S. Tsirkin         ptr[6] = checksum;
2327315a1350SMichael S. Tsirkin         pci_set_word(ptr + pcir_offset + 6, device_id);
2328315a1350SMichael S. Tsirkin     }
2329315a1350SMichael S. Tsirkin }
2330315a1350SMichael S. Tsirkin 
2331315a1350SMichael S. Tsirkin /* Add an option rom for the device */
pci_add_option_rom(PCIDevice * pdev,bool is_default_rom,Error ** errp)2332133e9b22SMarkus Armbruster static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2333133e9b22SMarkus Armbruster                                Error **errp)
2334315a1350SMichael S. Tsirkin {
23358eb85fb5SVladimir Sementsov-Ogievskiy     int64_t size = 0;
23365b52692fSVladimir Sementsov-Ogievskiy     g_autofree char *path = NULL;
2337315a1350SMichael S. Tsirkin     char name[32];
2338315a1350SMichael S. Tsirkin     const VMStateDescription *vmsd;
2339315a1350SMichael S. Tsirkin 
23408eb85fb5SVladimir Sementsov-Ogievskiy     /*
23418eb85fb5SVladimir Sementsov-Ogievskiy      * In case of incoming migration ROM will come with migration stream, no
23428eb85fb5SVladimir Sementsov-Ogievskiy      * reason to load the file.  Neither we want to fail if local ROM file
23438eb85fb5SVladimir Sementsov-Ogievskiy      * mismatches with specified romsize.
23448eb85fb5SVladimir Sementsov-Ogievskiy      */
23458eb85fb5SVladimir Sementsov-Ogievskiy     bool load_file = !runstate_check(RUN_STATE_INMIGRATE);
23468eb85fb5SVladimir Sementsov-Ogievskiy 
23474ab049c7SVladimir Sementsov-Ogievskiy     if (!pdev->romfile || !strlen(pdev->romfile)) {
2348133e9b22SMarkus Armbruster         return;
23494ab049c7SVladimir Sementsov-Ogievskiy     }
2350315a1350SMichael S. Tsirkin 
2351315a1350SMichael S. Tsirkin     if (!pdev->rom_bar) {
2352315a1350SMichael S. Tsirkin         /*
2353315a1350SMichael S. Tsirkin          * Load rom via fw_cfg instead of creating a rom bar,
2354315a1350SMichael S. Tsirkin          * for 0.11 compatibility.
2355315a1350SMichael S. Tsirkin          */
2356315a1350SMichael S. Tsirkin         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2357db80c7b9SMarcel Apfelbaum 
2358db80c7b9SMarcel Apfelbaum         /*
2359db80c7b9SMarcel Apfelbaum          * Hot-plugged devices can't use the option ROM
2360db80c7b9SMarcel Apfelbaum          * if the rom bar is disabled.
2361db80c7b9SMarcel Apfelbaum          */
2362db80c7b9SMarcel Apfelbaum         if (DEVICE(pdev)->hotplugged) {
2363133e9b22SMarkus Armbruster             error_setg(errp, "Hot-plugged device without ROM bar"
2364133e9b22SMarkus Armbruster                        " can't have an option ROM");
2365133e9b22SMarkus Armbruster             return;
2366db80c7b9SMarcel Apfelbaum         }
2367db80c7b9SMarcel Apfelbaum 
2368315a1350SMichael S. Tsirkin         if (class == 0x0300) {
2369315a1350SMichael S. Tsirkin             rom_add_vga(pdev->romfile);
2370315a1350SMichael S. Tsirkin         } else {
2371315a1350SMichael S. Tsirkin             rom_add_option(pdev->romfile, -1);
2372315a1350SMichael S. Tsirkin         }
2373133e9b22SMarkus Armbruster         return;
2374315a1350SMichael S. Tsirkin     }
2375315a1350SMichael S. Tsirkin 
23766a67577dSAkihiko Odaki     if (load_file || pdev->romsize == UINT32_MAX) {
2377315a1350SMichael S. Tsirkin         path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2378315a1350SMichael S. Tsirkin         if (path == NULL) {
2379315a1350SMichael S. Tsirkin             path = g_strdup(pdev->romfile);
2380315a1350SMichael S. Tsirkin         }
2381315a1350SMichael S. Tsirkin 
2382315a1350SMichael S. Tsirkin         size = get_image_size(path);
2383315a1350SMichael S. Tsirkin         if (size < 0) {
2384133e9b22SMarkus Armbruster             error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2385133e9b22SMarkus Armbruster             return;
23868c7f3dd0SStefan Hajnoczi         } else if (size == 0) {
2387133e9b22SMarkus Armbruster             error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2388133e9b22SMarkus Armbruster             return;
23897c16b5bbSPaolo Bonzini         } else if (size > 2 * GiB) {
23908eb85fb5SVladimir Sementsov-Ogievskiy             error_setg(errp,
23918eb85fb5SVladimir Sementsov-Ogievskiy                        "romfile \"%s\" too large (size cannot exceed 2 GiB)",
23927c16b5bbSPaolo Bonzini                        pdev->romfile);
23937c16b5bbSPaolo Bonzini             return;
2394315a1350SMichael S. Tsirkin         }
23956a67577dSAkihiko Odaki         if (pdev->romsize != UINT_MAX) {
239608b1df8fSPaolo Bonzini             if (size > pdev->romsize) {
23974ab049c7SVladimir Sementsov-Ogievskiy                 error_setg(errp, "romfile \"%s\" (%u bytes) "
23984ab049c7SVladimir Sementsov-Ogievskiy                            "is too large for ROM size %u",
239908b1df8fSPaolo Bonzini                            pdev->romfile, (uint32_t)size, pdev->romsize);
240008b1df8fSPaolo Bonzini                 return;
240108b1df8fSPaolo Bonzini             }
240208b1df8fSPaolo Bonzini         } else {
240308b1df8fSPaolo Bonzini             pdev->romsize = pow2ceil(size);
240408b1df8fSPaolo Bonzini         }
24058eb85fb5SVladimir Sementsov-Ogievskiy     }
2406315a1350SMichael S. Tsirkin 
2407315a1350SMichael S. Tsirkin     vmsd = qdev_get_vmsd(DEVICE(pdev));
24084ab049c7SVladimir Sementsov-Ogievskiy     snprintf(name, sizeof(name), "%s.rom",
24094ab049c7SVladimir Sementsov-Ogievskiy              vmsd ? vmsd->name : object_get_typename(OBJECT(pdev)));
2410315a1350SMichael S. Tsirkin 
2411315a1350SMichael S. Tsirkin     pdev->has_rom = true;
24124ab049c7SVladimir Sementsov-Ogievskiy     memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize,
24134ab049c7SVladimir Sementsov-Ogievskiy                            &error_fatal);
24144ab049c7SVladimir Sementsov-Ogievskiy 
24158eb85fb5SVladimir Sementsov-Ogievskiy     if (load_file) {
24168eb85fb5SVladimir Sementsov-Ogievskiy         void *ptr = memory_region_get_ram_ptr(&pdev->rom);
24178eb85fb5SVladimir Sementsov-Ogievskiy 
241836bde091SPeter Maydell         if (load_image_size(path, ptr, size) < 0) {
241936bde091SPeter Maydell             error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
242036bde091SPeter Maydell             return;
242136bde091SPeter Maydell         }
2422315a1350SMichael S. Tsirkin 
2423315a1350SMichael S. Tsirkin         if (is_default_rom) {
2424315a1350SMichael S. Tsirkin             /* Only the default rom images will be patched (if needed). */
2425315a1350SMichael S. Tsirkin             pci_patch_ids(pdev, ptr, size);
2426315a1350SMichael S. Tsirkin         }
24278eb85fb5SVladimir Sementsov-Ogievskiy     }
2428315a1350SMichael S. Tsirkin 
2429315a1350SMichael S. Tsirkin     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2430315a1350SMichael S. Tsirkin }
2431315a1350SMichael S. Tsirkin 
pci_del_option_rom(PCIDevice * pdev)2432315a1350SMichael S. Tsirkin static void pci_del_option_rom(PCIDevice *pdev)
2433315a1350SMichael S. Tsirkin {
2434315a1350SMichael S. Tsirkin     if (!pdev->has_rom)
2435315a1350SMichael S. Tsirkin         return;
2436315a1350SMichael S. Tsirkin 
2437315a1350SMichael S. Tsirkin     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2438315a1350SMichael S. Tsirkin     pdev->has_rom = false;
2439315a1350SMichael S. Tsirkin }
2440315a1350SMichael S. Tsirkin 
2441315a1350SMichael S. Tsirkin /*
244227841278SMao Zhongyi  * On success, pci_add_capability() returns a positive value
2443eacbc632SMao Zhongyi  * that the offset of the pci capability.
2444eacbc632SMao Zhongyi  * On failure, it sets an error and returns a negative error
2445eacbc632SMao Zhongyi  * code.
2446eacbc632SMao Zhongyi  */
pci_add_capability(PCIDevice * pdev,uint8_t cap_id,uint8_t offset,uint8_t size,Error ** errp)244727841278SMao Zhongyi int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2448cd9aa33eSLaszlo Ersek                        uint8_t offset, uint8_t size,
2449cd9aa33eSLaszlo Ersek                        Error **errp)
2450cd9aa33eSLaszlo Ersek {
2451315a1350SMichael S. Tsirkin     uint8_t *config;
2452315a1350SMichael S. Tsirkin     int i, overlapping_cap;
2453315a1350SMichael S. Tsirkin 
2454315a1350SMichael S. Tsirkin     if (!offset) {
2455315a1350SMichael S. Tsirkin         offset = pci_find_space(pdev, size);
245697fe42f1SCao jin         /* out of PCI config space is programming error */
245797fe42f1SCao jin         assert(offset);
2458315a1350SMichael S. Tsirkin     } else {
2459315a1350SMichael S. Tsirkin         /* Verify that capabilities don't overlap.  Note: device assignment
2460315a1350SMichael S. Tsirkin          * depends on this check to verify that the device is not broken.
2461315a1350SMichael S. Tsirkin          * Should never trigger for emulated devices, but it's helpful
2462315a1350SMichael S. Tsirkin          * for debugging these. */
2463315a1350SMichael S. Tsirkin         for (i = offset; i < offset + size; i++) {
2464315a1350SMichael S. Tsirkin             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2465315a1350SMichael S. Tsirkin             if (overlapping_cap) {
2466cd9aa33eSLaszlo Ersek                 error_setg(errp, "%s:%02x:%02x.%x "
2467315a1350SMichael S. Tsirkin                            "Attempt to add PCI capability %x at offset "
2468cd9aa33eSLaszlo Ersek                            "%x overlaps existing capability %x at offset %x",
2469fd56e061SDavid Gibson                            pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2470315a1350SMichael S. Tsirkin                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2471315a1350SMichael S. Tsirkin                            cap_id, offset, overlapping_cap, i);
2472315a1350SMichael S. Tsirkin                 return -EINVAL;
2473315a1350SMichael S. Tsirkin             }
2474315a1350SMichael S. Tsirkin         }
2475315a1350SMichael S. Tsirkin     }
2476315a1350SMichael S. Tsirkin 
2477315a1350SMichael S. Tsirkin     config = pdev->config + offset;
2478315a1350SMichael S. Tsirkin     config[PCI_CAP_LIST_ID] = cap_id;
2479315a1350SMichael S. Tsirkin     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2480315a1350SMichael S. Tsirkin     pdev->config[PCI_CAPABILITY_LIST] = offset;
2481315a1350SMichael S. Tsirkin     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2482315a1350SMichael S. Tsirkin     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2483315a1350SMichael S. Tsirkin     /* Make capability read-only by default */
2484315a1350SMichael S. Tsirkin     memset(pdev->wmask + offset, 0, size);
2485315a1350SMichael S. Tsirkin     /* Check capability by default */
2486315a1350SMichael S. Tsirkin     memset(pdev->cmask + offset, 0xFF, size);
2487315a1350SMichael S. Tsirkin     return offset;
2488315a1350SMichael S. Tsirkin }
2489315a1350SMichael S. Tsirkin 
2490315a1350SMichael S. Tsirkin /* Unlink capability from the pci config space. */
pci_del_capability(PCIDevice * pdev,uint8_t cap_id,uint8_t size)2491315a1350SMichael S. Tsirkin void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2492315a1350SMichael S. Tsirkin {
2493315a1350SMichael S. Tsirkin     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2494315a1350SMichael S. Tsirkin     if (!offset)
2495315a1350SMichael S. Tsirkin         return;
2496315a1350SMichael S. Tsirkin     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2497315a1350SMichael S. Tsirkin     /* Make capability writable again */
2498315a1350SMichael S. Tsirkin     memset(pdev->wmask + offset, 0xff, size);
2499315a1350SMichael S. Tsirkin     memset(pdev->w1cmask + offset, 0, size);
2500315a1350SMichael S. Tsirkin     /* Clear cmask as device-specific registers can't be checked */
2501315a1350SMichael S. Tsirkin     memset(pdev->cmask + offset, 0, size);
2502315a1350SMichael S. Tsirkin     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2503315a1350SMichael S. Tsirkin 
2504315a1350SMichael S. Tsirkin     if (!pdev->config[PCI_CAPABILITY_LIST])
2505315a1350SMichael S. Tsirkin         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2506315a1350SMichael S. Tsirkin }
2507315a1350SMichael S. Tsirkin 
pci_find_capability(PCIDevice * pdev,uint8_t cap_id)2508315a1350SMichael S. Tsirkin uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2509315a1350SMichael S. Tsirkin {
2510315a1350SMichael S. Tsirkin     return pci_find_capability_list(pdev, cap_id, NULL);
2511315a1350SMichael S. Tsirkin }
2512315a1350SMichael S. Tsirkin 
pci_dev_fw_name(DeviceState * dev,char * buf,int len)2513315a1350SMichael S. Tsirkin static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2514315a1350SMichael S. Tsirkin {
2515315a1350SMichael S. Tsirkin     PCIDevice *d = (PCIDevice *)dev;
2516315a1350SMichael S. Tsirkin     const char *name = NULL;
2517315a1350SMichael S. Tsirkin     const pci_class_desc *desc =  pci_class_descriptions;
2518315a1350SMichael S. Tsirkin     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2519315a1350SMichael S. Tsirkin 
2520315a1350SMichael S. Tsirkin     while (desc->desc &&
2521315a1350SMichael S. Tsirkin           (class & ~desc->fw_ign_bits) !=
2522315a1350SMichael S. Tsirkin           (desc->class & ~desc->fw_ign_bits)) {
2523315a1350SMichael S. Tsirkin         desc++;
2524315a1350SMichael S. Tsirkin     }
2525315a1350SMichael S. Tsirkin 
2526315a1350SMichael S. Tsirkin     if (desc->desc) {
2527315a1350SMichael S. Tsirkin         name = desc->fw_name;
2528315a1350SMichael S. Tsirkin     }
2529315a1350SMichael S. Tsirkin 
2530315a1350SMichael S. Tsirkin     if (name) {
2531315a1350SMichael S. Tsirkin         pstrcpy(buf, len, name);
2532315a1350SMichael S. Tsirkin     } else {
2533315a1350SMichael S. Tsirkin         snprintf(buf, len, "pci%04x,%04x",
2534315a1350SMichael S. Tsirkin                  pci_get_word(d->config + PCI_VENDOR_ID),
2535315a1350SMichael S. Tsirkin                  pci_get_word(d->config + PCI_DEVICE_ID));
2536315a1350SMichael S. Tsirkin     }
2537315a1350SMichael S. Tsirkin 
2538315a1350SMichael S. Tsirkin     return buf;
2539315a1350SMichael S. Tsirkin }
2540315a1350SMichael S. Tsirkin 
pcibus_get_fw_dev_path(DeviceState * dev)2541315a1350SMichael S. Tsirkin static char *pcibus_get_fw_dev_path(DeviceState *dev)
2542315a1350SMichael S. Tsirkin {
2543315a1350SMichael S. Tsirkin     PCIDevice *d = (PCIDevice *)dev;
254436f18c69SClaudio Fontana     char name[33];
254536f18c69SClaudio Fontana     int has_func = !!PCI_FUNC(d->devfn);
2546315a1350SMichael S. Tsirkin 
254736f18c69SClaudio Fontana     return g_strdup_printf("%s@%x%s%.*x",
254836f18c69SClaudio Fontana                            pci_dev_fw_name(dev, name, sizeof(name)),
254936f18c69SClaudio Fontana                            PCI_SLOT(d->devfn),
255036f18c69SClaudio Fontana                            has_func ? "," : "",
255136f18c69SClaudio Fontana                            has_func,
255236f18c69SClaudio Fontana                            PCI_FUNC(d->devfn));
2553315a1350SMichael S. Tsirkin }
2554315a1350SMichael S. Tsirkin 
pcibus_get_dev_path(DeviceState * dev)2555315a1350SMichael S. Tsirkin static char *pcibus_get_dev_path(DeviceState *dev)
2556315a1350SMichael S. Tsirkin {
2557315a1350SMichael S. Tsirkin     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2558315a1350SMichael S. Tsirkin     PCIDevice *t;
2559315a1350SMichael S. Tsirkin     int slot_depth;
2560315a1350SMichael S. Tsirkin     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2561315a1350SMichael S. Tsirkin      * 00 is added here to make this format compatible with
2562315a1350SMichael S. Tsirkin      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2563315a1350SMichael S. Tsirkin      * Slot.Function list specifies the slot and function numbers for all
2564315a1350SMichael S. Tsirkin      * devices on the path from root to the specific device. */
2565568f0690SDavid Gibson     const char *root_bus_path;
2566568f0690SDavid Gibson     int root_bus_len;
2567315a1350SMichael S. Tsirkin     char slot[] = ":SS.F";
2568315a1350SMichael S. Tsirkin     int slot_len = sizeof slot - 1 /* For '\0' */;
2569315a1350SMichael S. Tsirkin     int path_len;
2570315a1350SMichael S. Tsirkin     char *path, *p;
2571315a1350SMichael S. Tsirkin     int s;
2572315a1350SMichael S. Tsirkin 
2573568f0690SDavid Gibson     root_bus_path = pci_root_bus_path(d);
2574568f0690SDavid Gibson     root_bus_len = strlen(root_bus_path);
2575568f0690SDavid Gibson 
2576315a1350SMichael S. Tsirkin     /* Calculate # of slots on path between device and root. */;
2577315a1350SMichael S. Tsirkin     slot_depth = 0;
2578fd56e061SDavid Gibson     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2579315a1350SMichael S. Tsirkin         ++slot_depth;
2580315a1350SMichael S. Tsirkin     }
2581315a1350SMichael S. Tsirkin 
2582568f0690SDavid Gibson     path_len = root_bus_len + slot_len * slot_depth;
2583315a1350SMichael S. Tsirkin 
2584315a1350SMichael S. Tsirkin     /* Allocate memory, fill in the terminating null byte. */
2585315a1350SMichael S. Tsirkin     path = g_malloc(path_len + 1 /* For '\0' */);
2586315a1350SMichael S. Tsirkin     path[path_len] = '\0';
2587315a1350SMichael S. Tsirkin 
2588568f0690SDavid Gibson     memcpy(path, root_bus_path, root_bus_len);
2589315a1350SMichael S. Tsirkin 
2590315a1350SMichael S. Tsirkin     /* Fill in slot numbers. We walk up from device to root, so need to print
2591315a1350SMichael S. Tsirkin      * them in the reverse order, last to first. */
2592315a1350SMichael S. Tsirkin     p = path + path_len;
2593fd56e061SDavid Gibson     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2594315a1350SMichael S. Tsirkin         p -= slot_len;
2595315a1350SMichael S. Tsirkin         s = snprintf(slot, sizeof slot, ":%02x.%x",
2596315a1350SMichael S. Tsirkin                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2597315a1350SMichael S. Tsirkin         assert(s == slot_len);
2598315a1350SMichael S. Tsirkin         memcpy(p, slot, slot_len);
2599315a1350SMichael S. Tsirkin     }
2600315a1350SMichael S. Tsirkin 
2601315a1350SMichael S. Tsirkin     return path;
2602315a1350SMichael S. Tsirkin }
2603315a1350SMichael S. Tsirkin 
pci_qdev_find_recursive(PCIBus * bus,const char * id,PCIDevice ** pdev)2604315a1350SMichael S. Tsirkin static int pci_qdev_find_recursive(PCIBus *bus,
2605315a1350SMichael S. Tsirkin                                    const char *id, PCIDevice **pdev)
2606315a1350SMichael S. Tsirkin {
2607315a1350SMichael S. Tsirkin     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2608315a1350SMichael S. Tsirkin     if (!qdev) {
2609315a1350SMichael S. Tsirkin         return -ENODEV;
2610315a1350SMichael S. Tsirkin     }
2611315a1350SMichael S. Tsirkin 
2612315a1350SMichael S. Tsirkin     /* roughly check if given qdev is pci device */
2613315a1350SMichael S. Tsirkin     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2614315a1350SMichael S. Tsirkin         *pdev = PCI_DEVICE(qdev);
2615315a1350SMichael S. Tsirkin         return 0;
2616315a1350SMichael S. Tsirkin     }
2617315a1350SMichael S. Tsirkin     return -EINVAL;
2618315a1350SMichael S. Tsirkin }
2619315a1350SMichael S. Tsirkin 
pci_qdev_find_device(const char * id,PCIDevice ** pdev)2620315a1350SMichael S. Tsirkin int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2621315a1350SMichael S. Tsirkin {
26227588e2b0SDavid Gibson     PCIHostState *host_bridge;
2623315a1350SMichael S. Tsirkin     int rc = -ENODEV;
2624315a1350SMichael S. Tsirkin 
26257588e2b0SDavid Gibson     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
26267588e2b0SDavid Gibson         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2627315a1350SMichael S. Tsirkin         if (!tmp) {
2628315a1350SMichael S. Tsirkin             rc = 0;
2629315a1350SMichael S. Tsirkin             break;
2630315a1350SMichael S. Tsirkin         }
2631315a1350SMichael S. Tsirkin         if (tmp != -ENODEV) {
2632315a1350SMichael S. Tsirkin             rc = tmp;
2633315a1350SMichael S. Tsirkin         }
2634315a1350SMichael S. Tsirkin     }
2635315a1350SMichael S. Tsirkin 
2636315a1350SMichael S. Tsirkin     return rc;
2637315a1350SMichael S. Tsirkin }
2638315a1350SMichael S. Tsirkin 
pci_address_space(PCIDevice * dev)2639315a1350SMichael S. Tsirkin MemoryRegion *pci_address_space(PCIDevice *dev)
2640315a1350SMichael S. Tsirkin {
2641fd56e061SDavid Gibson     return pci_get_bus(dev)->address_space_mem;
2642315a1350SMichael S. Tsirkin }
2643315a1350SMichael S. Tsirkin 
pci_address_space_io(PCIDevice * dev)2644315a1350SMichael S. Tsirkin MemoryRegion *pci_address_space_io(PCIDevice *dev)
2645315a1350SMichael S. Tsirkin {
2646fd56e061SDavid Gibson     return pci_get_bus(dev)->address_space_io;
2647315a1350SMichael S. Tsirkin }
2648315a1350SMichael S. Tsirkin 
pci_device_class_init(ObjectClass * klass,void * data)2649315a1350SMichael S. Tsirkin static void pci_device_class_init(ObjectClass *klass, void *data)
2650315a1350SMichael S. Tsirkin {
2651315a1350SMichael S. Tsirkin     DeviceClass *k = DEVICE_CLASS(klass);
26527ee6c1e1SMarkus Armbruster 
2653133e9b22SMarkus Armbruster     k->realize = pci_qdev_realize;
2654133e9b22SMarkus Armbruster     k->unrealize = pci_qdev_unrealize;
2655315a1350SMichael S. Tsirkin     k->bus_type = TYPE_PCI_BUS;
26564f67d30bSMarc-André Lureau     device_class_set_props(k, pci_props);
2657637b0aa1SMattias Nissler     object_class_property_set_description(
2658637b0aa1SMattias Nissler         klass, "x-max-bounce-buffer-size",
2659637b0aa1SMattias Nissler         "Maximum buffer size allocated for bounce buffers used for mapped "
2660637b0aa1SMattias Nissler         "access to indirect DMA memory");
2661315a1350SMichael S. Tsirkin }
2662315a1350SMichael S. Tsirkin 
pci_device_class_base_init(ObjectClass * klass,void * data)26632fefa16cSEduardo Habkost static void pci_device_class_base_init(ObjectClass *klass, void *data)
26642fefa16cSEduardo Habkost {
26652fefa16cSEduardo Habkost     if (!object_class_is_abstract(klass)) {
26662fefa16cSEduardo Habkost         ObjectClass *conventional =
26672fefa16cSEduardo Habkost             object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
26682fefa16cSEduardo Habkost         ObjectClass *pcie =
26692fefa16cSEduardo Habkost             object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2670d86d3019SBen Widawsky         ObjectClass *cxl =
2671d86d3019SBen Widawsky             object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE);
2672d86d3019SBen Widawsky         assert(conventional || pcie || cxl);
26732fefa16cSEduardo Habkost     }
26742fefa16cSEduardo Habkost }
26752fefa16cSEduardo Habkost 
26766c8ed5feSZhenzhong Duan /*
26776c8ed5feSZhenzhong Duan  * Get IOMMU root bus, aliased bus and devfn of a PCI device
26786c8ed5feSZhenzhong Duan  *
26796c8ed5feSZhenzhong Duan  * IOMMU root bus is needed by all call sites to call into iommu_ops.
26806c8ed5feSZhenzhong Duan  * For call sites which don't need aliased BDF, passing NULL to
26816c8ed5feSZhenzhong Duan  * aliased_[bus|devfn] is allowed.
26826c8ed5feSZhenzhong Duan  *
26836c8ed5feSZhenzhong Duan  * @piommu_bus: return root #PCIBus backed by an IOMMU for the PCI device.
26846c8ed5feSZhenzhong Duan  *
26856c8ed5feSZhenzhong Duan  * @aliased_bus: return aliased #PCIBus of the PCI device, optional.
26866c8ed5feSZhenzhong Duan  *
26876c8ed5feSZhenzhong Duan  * @aliased_devfn: return aliased devfn of the PCI device, optional.
26886c8ed5feSZhenzhong Duan  */
pci_device_get_iommu_bus_devfn(PCIDevice * dev,PCIBus ** piommu_bus,PCIBus ** aliased_bus,int * aliased_devfn)26896c8ed5feSZhenzhong Duan static void pci_device_get_iommu_bus_devfn(PCIDevice *dev,
26906c8ed5feSZhenzhong Duan                                            PCIBus **piommu_bus,
26916c8ed5feSZhenzhong Duan                                            PCIBus **aliased_bus,
26926c8ed5feSZhenzhong Duan                                            int *aliased_devfn)
26939eda7d37SAlexey Kardashevskiy {
2694fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(dev);
26955af2ae23SBenjamin Herrenschmidt     PCIBus *iommu_bus = bus;
26966c8ed5feSZhenzhong Duan     int devfn = dev->devfn;
26979eda7d37SAlexey Kardashevskiy 
2698ba7d12ebSYi Liu     while (iommu_bus && !iommu_bus->iommu_ops && iommu_bus->parent_dev) {
269977ef8f8dSAlex Williamson         PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
270077ef8f8dSAlex Williamson 
270177ef8f8dSAlex Williamson         /*
270277ef8f8dSAlex Williamson          * The requester ID of the provided device may be aliased, as seen from
270377ef8f8dSAlex Williamson          * the IOMMU, due to topology limitations.  The IOMMU relies on a
270477ef8f8dSAlex Williamson          * requester ID to provide a unique AddressSpace for devices, but
270577ef8f8dSAlex Williamson          * conventional PCI buses pre-date such concepts.  Instead, the PCIe-
270677ef8f8dSAlex Williamson          * to-PCI bridge creates and accepts transactions on behalf of down-
270777ef8f8dSAlex Williamson          * stream devices.  When doing so, all downstream devices are masked
270877ef8f8dSAlex Williamson          * (aliased) behind a single requester ID.  The requester ID used
270977ef8f8dSAlex Williamson          * depends on the format of the bridge devices.  Proper PCIe-to-PCI
271077ef8f8dSAlex Williamson          * bridges, with a PCIe capability indicating such, follow the
271177ef8f8dSAlex Williamson          * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
271277ef8f8dSAlex Williamson          * where the bridge uses the seconary bus as the bridge portion of the
271377ef8f8dSAlex Williamson          * requester ID and devfn of 00.0.  For other bridges, typically those
271477ef8f8dSAlex Williamson          * found on the root complex such as the dmi-to-pci-bridge, we follow
271577ef8f8dSAlex Williamson          * the convention of typical bare-metal hardware, which uses the
271677ef8f8dSAlex Williamson          * requester ID of the bridge itself.  There are device specific
271777ef8f8dSAlex Williamson          * exceptions to these rules, but these are the defaults that the
271877ef8f8dSAlex Williamson          * Linux kernel uses when determining DMA aliases itself and believed
271977ef8f8dSAlex Williamson          * to be true for the bare metal equivalents of the devices emulated
272077ef8f8dSAlex Williamson          * in QEMU.
272177ef8f8dSAlex Williamson          */
272277ef8f8dSAlex Williamson         if (!pci_bus_is_express(iommu_bus)) {
272377ef8f8dSAlex Williamson             PCIDevice *parent = iommu_bus->parent_dev;
272477ef8f8dSAlex Williamson 
272577ef8f8dSAlex Williamson             if (pci_is_express(parent) &&
272677ef8f8dSAlex Williamson                 pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
272777ef8f8dSAlex Williamson                 devfn = PCI_DEVFN(0, 0);
272877ef8f8dSAlex Williamson                 bus = iommu_bus;
272977ef8f8dSAlex Williamson             } else {
273077ef8f8dSAlex Williamson                 devfn = parent->devfn;
273177ef8f8dSAlex Williamson                 bus = parent_bus;
273277ef8f8dSAlex Williamson             }
273377ef8f8dSAlex Williamson         }
273477ef8f8dSAlex Williamson 
273577ef8f8dSAlex Williamson         iommu_bus = parent_bus;
27369eda7d37SAlexey Kardashevskiy     }
27376c8ed5feSZhenzhong Duan 
27386c8ed5feSZhenzhong Duan     assert(0 <= devfn && devfn < PCI_DEVFN_MAX);
27396c8ed5feSZhenzhong Duan     assert(iommu_bus);
27406c8ed5feSZhenzhong Duan 
27416c8ed5feSZhenzhong Duan     if (pci_bus_bypass_iommu(bus) || !iommu_bus->iommu_ops) {
27426c8ed5feSZhenzhong Duan         iommu_bus = NULL;
27436c8ed5feSZhenzhong Duan     }
27446c8ed5feSZhenzhong Duan 
27456c8ed5feSZhenzhong Duan     *piommu_bus = iommu_bus;
27466c8ed5feSZhenzhong Duan 
27476c8ed5feSZhenzhong Duan     if (aliased_bus) {
27486c8ed5feSZhenzhong Duan         *aliased_bus = bus;
27496c8ed5feSZhenzhong Duan     }
27506c8ed5feSZhenzhong Duan 
27516c8ed5feSZhenzhong Duan     if (aliased_devfn) {
27526c8ed5feSZhenzhong Duan         *aliased_devfn = devfn;
27536c8ed5feSZhenzhong Duan     }
27546c8ed5feSZhenzhong Duan }
27556c8ed5feSZhenzhong Duan 
pci_device_iommu_address_space(PCIDevice * dev)27566c8ed5feSZhenzhong Duan AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
27576c8ed5feSZhenzhong Duan {
27586c8ed5feSZhenzhong Duan     PCIBus *bus;
27596c8ed5feSZhenzhong Duan     PCIBus *iommu_bus;
27606c8ed5feSZhenzhong Duan     int devfn;
27616c8ed5feSZhenzhong Duan 
27626c8ed5feSZhenzhong Duan     pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
27636c8ed5feSZhenzhong Duan     if (iommu_bus) {
2764ba7d12ebSYi Liu         return iommu_bus->iommu_ops->get_address_space(bus,
2765ba7d12ebSYi Liu                                  iommu_bus->iommu_opaque, devfn);
27669eda7d37SAlexey Kardashevskiy     }
27679eda7d37SAlexey Kardashevskiy     return &address_space_memory;
27689eda7d37SAlexey Kardashevskiy }
27699eda7d37SAlexey Kardashevskiy 
pci_device_set_iommu_device(PCIDevice * dev,HostIOMMUDevice * hiod,Error ** errp)2770b025ea68SYi Liu bool pci_device_set_iommu_device(PCIDevice *dev, HostIOMMUDevice *hiod,
2771b025ea68SYi Liu                                  Error **errp)
2772b025ea68SYi Liu {
2773a9526419SEric Auger     PCIBus *iommu_bus, *aliased_bus;
2774a9526419SEric Auger     int aliased_devfn;
2775b025ea68SYi Liu 
2776b025ea68SYi Liu     /* set_iommu_device requires device's direct BDF instead of aliased BDF */
2777a9526419SEric Auger     pci_device_get_iommu_bus_devfn(dev, &iommu_bus,
2778a9526419SEric Auger                                    &aliased_bus, &aliased_devfn);
2779b025ea68SYi Liu     if (iommu_bus && iommu_bus->iommu_ops->set_iommu_device) {
2780a9526419SEric Auger         hiod->aliased_bus = aliased_bus;
2781a9526419SEric Auger         hiod->aliased_devfn = aliased_devfn;
2782b025ea68SYi Liu         return iommu_bus->iommu_ops->set_iommu_device(pci_get_bus(dev),
2783b025ea68SYi Liu                                                       iommu_bus->iommu_opaque,
2784b025ea68SYi Liu                                                       dev->devfn, hiod, errp);
2785b025ea68SYi Liu     }
2786b025ea68SYi Liu     return true;
2787b025ea68SYi Liu }
2788b025ea68SYi Liu 
pci_device_unset_iommu_device(PCIDevice * dev)2789b025ea68SYi Liu void pci_device_unset_iommu_device(PCIDevice *dev)
2790b025ea68SYi Liu {
2791b025ea68SYi Liu     PCIBus *iommu_bus;
2792b025ea68SYi Liu 
2793b025ea68SYi Liu     pci_device_get_iommu_bus_devfn(dev, &iommu_bus, NULL, NULL);
2794b025ea68SYi Liu     if (iommu_bus && iommu_bus->iommu_ops->unset_iommu_device) {
2795b025ea68SYi Liu         return iommu_bus->iommu_ops->unset_iommu_device(pci_get_bus(dev),
2796b025ea68SYi Liu                                                         iommu_bus->iommu_opaque,
2797b025ea68SYi Liu                                                         dev->devfn);
2798b025ea68SYi Liu     }
2799b025ea68SYi Liu }
2800b025ea68SYi Liu 
pci_setup_iommu(PCIBus * bus,const PCIIOMMUOps * ops,void * opaque)2801ba7d12ebSYi Liu void pci_setup_iommu(PCIBus *bus, const PCIIOMMUOps *ops, void *opaque)
2802315a1350SMichael S. Tsirkin {
2803ba7d12ebSYi Liu     /*
2804ba7d12ebSYi Liu      * If called, pci_setup_iommu() should provide a minimum set of
2805ba7d12ebSYi Liu      * useful callbacks for the bus.
2806ba7d12ebSYi Liu      */
2807ba7d12ebSYi Liu     assert(ops);
2808ba7d12ebSYi Liu     assert(ops->get_address_space);
2809ba7d12ebSYi Liu 
2810ba7d12ebSYi Liu     bus->iommu_ops = ops;
2811e00387d5SAvi Kivity     bus->iommu_opaque = opaque;
2812315a1350SMichael S. Tsirkin }
2813315a1350SMichael S. Tsirkin 
pci_dev_get_w64(PCIBus * b,PCIDevice * dev,void * opaque)281443864069SMichael S. Tsirkin static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
281543864069SMichael S. Tsirkin {
281643864069SMichael S. Tsirkin     Range *range = opaque;
281743864069SMichael S. Tsirkin     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
281877d6f4eaSMichael S. Tsirkin     int i;
281943864069SMichael S. Tsirkin 
282043864069SMichael S. Tsirkin     if (!(cmd & PCI_COMMAND_MEMORY)) {
282143864069SMichael S. Tsirkin         return;
282243864069SMichael S. Tsirkin     }
282343864069SMichael S. Tsirkin 
2824ad494274SIgor Mammedov     if (IS_PCI_BRIDGE(dev)) {
282543864069SMichael S. Tsirkin         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
282643864069SMichael S. Tsirkin         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
282743864069SMichael S. Tsirkin 
282843864069SMichael S. Tsirkin         base = MAX(base, 0x1ULL << 32);
282943864069SMichael S. Tsirkin 
283043864069SMichael S. Tsirkin         if (limit >= base) {
283143864069SMichael S. Tsirkin             Range pref_range;
2832a0efbf16SMarkus Armbruster             range_set_bounds(&pref_range, base, limit);
283343864069SMichael S. Tsirkin             range_extend(range, &pref_range);
283443864069SMichael S. Tsirkin         }
283543864069SMichael S. Tsirkin     }
283677d6f4eaSMichael S. Tsirkin     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
283777d6f4eaSMichael S. Tsirkin         PCIIORegion *r = &dev->io_regions[i];
2838a0efbf16SMarkus Armbruster         pcibus_t lob, upb;
283943864069SMichael S. Tsirkin         Range region_range;
284043864069SMichael S. Tsirkin 
284177d6f4eaSMichael S. Tsirkin         if (!r->size ||
284277d6f4eaSMichael S. Tsirkin             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
284377d6f4eaSMichael S. Tsirkin             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
284443864069SMichael S. Tsirkin             continue;
284543864069SMichael S. Tsirkin         }
284677d6f4eaSMichael S. Tsirkin 
2847a0efbf16SMarkus Armbruster         lob = pci_bar_address(dev, i, r->type, r->size);
2848a0efbf16SMarkus Armbruster         upb = lob + r->size - 1;
2849a0efbf16SMarkus Armbruster         if (lob == PCI_BAR_UNMAPPED) {
285077d6f4eaSMichael S. Tsirkin             continue;
285177d6f4eaSMichael S. Tsirkin         }
285243864069SMichael S. Tsirkin 
2853a0efbf16SMarkus Armbruster         lob = MAX(lob, 0x1ULL << 32);
285443864069SMichael S. Tsirkin 
2855a0efbf16SMarkus Armbruster         if (upb >= lob) {
2856a0efbf16SMarkus Armbruster             range_set_bounds(&region_range, lob, upb);
285743864069SMichael S. Tsirkin             range_extend(range, &region_range);
285843864069SMichael S. Tsirkin         }
285943864069SMichael S. Tsirkin     }
286043864069SMichael S. Tsirkin }
286143864069SMichael S. Tsirkin 
pci_bus_get_w64_range(PCIBus * bus,Range * range)286243864069SMichael S. Tsirkin void pci_bus_get_w64_range(PCIBus *bus, Range *range)
286343864069SMichael S. Tsirkin {
2864a0efbf16SMarkus Armbruster     range_make_empty(range);
286543864069SMichael S. Tsirkin     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
286643864069SMichael S. Tsirkin }
286743864069SMichael S. Tsirkin 
pcie_has_upstream_port(PCIDevice * dev)28683f1e1478SCao jin static bool pcie_has_upstream_port(PCIDevice *dev)
28693f1e1478SCao jin {
2870fd56e061SDavid Gibson     PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
28713f1e1478SCao jin 
28723f1e1478SCao jin     /* Device associated with an upstream port.
28733f1e1478SCao jin      * As there are several types of these, it's easier to check the
28743f1e1478SCao jin      * parent device: upstream ports are always connected to
28753f1e1478SCao jin      * root or downstream ports.
28763f1e1478SCao jin      */
28773f1e1478SCao jin     return parent_dev &&
28783f1e1478SCao jin         pci_is_express(parent_dev) &&
28793f1e1478SCao jin         parent_dev->exp.exp_cap &&
28803f1e1478SCao jin         (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
28813f1e1478SCao jin          pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
28823f1e1478SCao jin }
28833f1e1478SCao jin 
pci_get_function_0(PCIDevice * pci_dev)28843f1e1478SCao jin PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
28853f1e1478SCao jin {
2886fd56e061SDavid Gibson     PCIBus *bus = pci_get_bus(pci_dev);
2887fd56e061SDavid Gibson 
28883f1e1478SCao jin     if(pcie_has_upstream_port(pci_dev)) {
28893f1e1478SCao jin         /* With an upstream PCIe port, we only support 1 device at slot 0 */
2890fd56e061SDavid Gibson         return bus->devices[0];
28913f1e1478SCao jin     } else {
28923f1e1478SCao jin         /* Other bus types might support multiple devices at slots 0-31 */
2893fd56e061SDavid Gibson         return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
28943f1e1478SCao jin     }
28953f1e1478SCao jin }
28963f1e1478SCao jin 
pci_get_msi_message(PCIDevice * dev,int vector)2897e1d4fb2dSPeter Xu MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2898e1d4fb2dSPeter Xu {
2899e1d4fb2dSPeter Xu     MSIMessage msg;
2900e1d4fb2dSPeter Xu     if (msix_enabled(dev)) {
2901e1d4fb2dSPeter Xu         msg = msix_get_message(dev, vector);
2902e1d4fb2dSPeter Xu     } else if (msi_enabled(dev)) {
2903e1d4fb2dSPeter Xu         msg = msi_get_message(dev, vector);
2904e1d4fb2dSPeter Xu     } else {
2905e1d4fb2dSPeter Xu         /* Should never happen */
2906e1d4fb2dSPeter Xu         error_report("%s: unknown interrupt type", __func__);
2907e1d4fb2dSPeter Xu         abort();
2908e1d4fb2dSPeter Xu     }
2909e1d4fb2dSPeter Xu     return msg;
2910e1d4fb2dSPeter Xu }
2911e1d4fb2dSPeter Xu 
pci_set_power(PCIDevice * d,bool state)291293829009SMichael S. Tsirkin void pci_set_power(PCIDevice *d, bool state)
291323786d13SGerd Hoffmann {
291493829009SMichael S. Tsirkin     if (d->has_power == state) {
291523786d13SGerd Hoffmann         return;
291623786d13SGerd Hoffmann     }
291723786d13SGerd Hoffmann 
291893829009SMichael S. Tsirkin     d->has_power = state;
291923786d13SGerd Hoffmann     pci_update_mappings(d);
292023786d13SGerd Hoffmann     memory_region_set_enabled(&d->bus_master_enable_region,
292123786d13SGerd Hoffmann                               (pci_get_word(d->config + PCI_COMMAND)
292293829009SMichael S. Tsirkin                                & PCI_COMMAND_MASTER) && d->has_power);
292393829009SMichael S. Tsirkin     if (!d->has_power) {
292423786d13SGerd Hoffmann         pci_device_reset(d);
292523786d13SGerd Hoffmann     }
292623786d13SGerd Hoffmann }
292723786d13SGerd Hoffmann 
29288c43a6f0SAndreas Färber static const TypeInfo pci_device_type_info = {
2929315a1350SMichael S. Tsirkin     .name = TYPE_PCI_DEVICE,
2930315a1350SMichael S. Tsirkin     .parent = TYPE_DEVICE,
2931315a1350SMichael S. Tsirkin     .instance_size = sizeof(PCIDevice),
2932315a1350SMichael S. Tsirkin     .abstract = true,
2933315a1350SMichael S. Tsirkin     .class_size = sizeof(PCIDeviceClass),
2934315a1350SMichael S. Tsirkin     .class_init = pci_device_class_init,
29352fefa16cSEduardo Habkost     .class_base_init = pci_device_class_base_init,
2936315a1350SMichael S. Tsirkin };
2937315a1350SMichael S. Tsirkin 
pci_register_types(void)2938315a1350SMichael S. Tsirkin static void pci_register_types(void)
2939315a1350SMichael S. Tsirkin {
2940315a1350SMichael S. Tsirkin     type_register_static(&pci_bus_info);
29413a861c46SAlex Williamson     type_register_static(&pcie_bus_info);
29424f8db871SBen Widawsky     type_register_static(&cxl_bus_info);
2943619f02aeSEduardo Habkost     type_register_static(&conventional_pci_interface_info);
2944cf04aba2SBen Widawsky     type_register_static(&cxl_interface_info);
2945619f02aeSEduardo Habkost     type_register_static(&pcie_interface_info);
2946315a1350SMichael S. Tsirkin     type_register_static(&pci_device_type_info);
2947315a1350SMichael S. Tsirkin }
2948315a1350SMichael S. Tsirkin 
2949315a1350SMichael S. Tsirkin type_init(pci_register_types)
2950