1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) Microsoft Corporation.
6 * Jake Oshins <jakeo@microsoft.com>
8 * This driver acts as a paravirtual front-end for PCI Express root buses.
9 * When a PCI Express function (either an entire device or an SR-IOV
10 * Virtual Function) is being passed through to the VM, this driver exposes
11 * a new bus to the guest VM. This is modeled as a root PCI bus because
12 * no bridges are being exposed to the VM. In fact, with a "Generation 2"
13 * VM within Hyper-V, there may seem to be no PCI bus at all in the VM
14 * until a device as been exposed using this driver.
16 * Each root PCI bus has its own PCI domain, which is called "Segment" in
17 * the PCI Firmware Specifications. Thus while each device passed through
18 * to the VM using this front-end will appear at "device 0", the domain will
19 * be unique. Typically, each bus will have one PCI function on it, though
20 * this driver does support more than one.
22 * In order to map the interrupts from the device through to the guest VM,
23 * this driver also implements an IRQ Domain, which handles interrupts (either
24 * MSI or MSI-X) associated with the functions on the bus. As interrupts are
25 * set up, torn down, or reaffined, this driver communicates with the
26 * underlying hypervisor to adjust the mappings in the I/O MMU so that each
27 * interrupt will be delivered to the correct virtual processor at the right
28 * vector. This driver does not support level-triggered (line-based)
29 * interrupts, and will report that the Interrupt Line register in the
30 * function's configuration space is zero.
32 * The rest of this driver mostly maps PCI concepts onto underlying Hyper-V
33 * facilities. For instance, the configuration space of a function exposed
34 * by Hyper-V is mapped into a single page of memory space, and the
35 * read and write handlers for config space must be aware of this mechanism.
36 * Similarly, device setup and teardown involves messages sent to and from
37 * the PCI back-end driver in Hyper-V.
40 #include <linux/kernel.h>
41 #include <linux/module.h>
42 #include <linux/pci.h>
43 #include <linux/pci-ecam.h>
44 #include <linux/delay.h>
45 #include <linux/semaphore.h>
46 #include <linux/irq.h>
47 #include <linux/msi.h>
48 #include <linux/hyperv.h>
49 #include <linux/refcount.h>
50 #include <linux/irqdomain.h>
51 #include <linux/acpi.h>
52 #include <asm/mshyperv.h>
55 * Protocol versions. The low word is the minor version, the high word the
59 #define PCI_MAKE_VERSION(major, minor) ((u32)(((major) << 16) | (minor)))
60 #define PCI_MAJOR_VERSION(version) ((u32)(version) >> 16)
61 #define PCI_MINOR_VERSION(version) ((u32)(version) & 0xff)
63 enum pci_protocol_version_t {
64 PCI_PROTOCOL_VERSION_1_1 = PCI_MAKE_VERSION(1, 1), /* Win10 */
65 PCI_PROTOCOL_VERSION_1_2 = PCI_MAKE_VERSION(1, 2), /* RS1 */
66 PCI_PROTOCOL_VERSION_1_3 = PCI_MAKE_VERSION(1, 3), /* Vibranium */
67 PCI_PROTOCOL_VERSION_1_4 = PCI_MAKE_VERSION(1, 4), /* WS2022 */
70 #define CPU_AFFINITY_ALL -1ULL
73 * Supported protocol versions in the order of probing - highest go
76 static enum pci_protocol_version_t pci_protocol_versions[] = {
77 PCI_PROTOCOL_VERSION_1_4,
78 PCI_PROTOCOL_VERSION_1_3,
79 PCI_PROTOCOL_VERSION_1_2,
80 PCI_PROTOCOL_VERSION_1_1,
83 #define PCI_CONFIG_MMIO_LENGTH 0x2000
84 #define CFG_PAGE_OFFSET 0x1000
85 #define CFG_PAGE_SIZE (PCI_CONFIG_MMIO_LENGTH - CFG_PAGE_OFFSET)
87 #define MAX_SUPPORTED_MSI_MESSAGES 0x400
89 #define STATUS_REVISION_MISMATCH 0xC0000059
91 /* space for 32bit serial number as string */
92 #define SLOT_NAME_SIZE 11
95 * Size of requestor for VMbus; the value is based on the observation
96 * that having more than one request outstanding is 'rare', and so 64
97 * should be generous in ensuring that we don't ever run out.
99 #define HV_PCI_RQSTOR_SIZE 64
105 enum pci_message_type {
109 PCI_MESSAGE_BASE = 0x42490000,
110 PCI_BUS_RELATIONS = PCI_MESSAGE_BASE + 0,
111 PCI_QUERY_BUS_RELATIONS = PCI_MESSAGE_BASE + 1,
112 PCI_POWER_STATE_CHANGE = PCI_MESSAGE_BASE + 4,
113 PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5,
114 PCI_QUERY_RESOURCE_RESOURCES = PCI_MESSAGE_BASE + 6,
115 PCI_BUS_D0ENTRY = PCI_MESSAGE_BASE + 7,
116 PCI_BUS_D0EXIT = PCI_MESSAGE_BASE + 8,
117 PCI_READ_BLOCK = PCI_MESSAGE_BASE + 9,
118 PCI_WRITE_BLOCK = PCI_MESSAGE_BASE + 0xA,
119 PCI_EJECT = PCI_MESSAGE_BASE + 0xB,
120 PCI_QUERY_STOP = PCI_MESSAGE_BASE + 0xC,
121 PCI_REENABLE = PCI_MESSAGE_BASE + 0xD,
122 PCI_QUERY_STOP_FAILED = PCI_MESSAGE_BASE + 0xE,
123 PCI_EJECTION_COMPLETE = PCI_MESSAGE_BASE + 0xF,
124 PCI_RESOURCES_ASSIGNED = PCI_MESSAGE_BASE + 0x10,
125 PCI_RESOURCES_RELEASED = PCI_MESSAGE_BASE + 0x11,
126 PCI_INVALIDATE_BLOCK = PCI_MESSAGE_BASE + 0x12,
127 PCI_QUERY_PROTOCOL_VERSION = PCI_MESSAGE_BASE + 0x13,
128 PCI_CREATE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x14,
129 PCI_DELETE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x15,
130 PCI_RESOURCES_ASSIGNED2 = PCI_MESSAGE_BASE + 0x16,
131 PCI_CREATE_INTERRUPT_MESSAGE2 = PCI_MESSAGE_BASE + 0x17,
132 PCI_DELETE_INTERRUPT_MESSAGE2 = PCI_MESSAGE_BASE + 0x18, /* unused */
133 PCI_BUS_RELATIONS2 = PCI_MESSAGE_BASE + 0x19,
134 PCI_RESOURCES_ASSIGNED3 = PCI_MESSAGE_BASE + 0x1A,
135 PCI_CREATE_INTERRUPT_MESSAGE3 = PCI_MESSAGE_BASE + 0x1B,
140 * Structures defining the virtual PCI Express protocol.
152 * Function numbers are 8-bits wide on Express, as interpreted through ARI,
153 * which is all this driver does. This representation is the one used in
154 * Windows, which is what is expected when sending this back and forth with
155 * the Hyper-V parent partition.
157 union win_slot_encoding {
167 * Pretty much as defined in the PCI Specifications.
169 struct pci_function_description {
170 u16 v_id; /* vendor ID */
171 u16 d_id; /* device ID */
177 union win_slot_encoding win_slot;
178 u32 ser; /* serial number */
181 enum pci_device_description_flags {
182 HV_PCI_DEVICE_FLAG_NONE = 0x0,
183 HV_PCI_DEVICE_FLAG_NUMA_AFFINITY = 0x1,
186 struct pci_function_description2 {
187 u16 v_id; /* vendor ID */
188 u16 d_id; /* device ID */
194 union win_slot_encoding win_slot;
195 u32 ser; /* serial number */
197 u16 virtual_numa_node;
204 * @delivery_mode: As defined in Intel's Programmer's
205 * Reference Manual, Volume 3, Chapter 8.
206 * @vector_count: Number of contiguous entries in the
207 * Interrupt Descriptor Table that are
208 * occupied by this Message-Signaled
209 * Interrupt. For "MSI", as first defined
210 * in PCI 2.2, this can be between 1 and
211 * 32. For "MSI-X," as first defined in PCI
212 * 3.0, this must be 1, as each MSI-X table
213 * entry would have its own descriptor.
214 * @reserved: Empty space
215 * @cpu_mask: All the target virtual processors.
226 * struct hv_msi_desc2 - 1.2 version of hv_msi_desc
228 * @delivery_mode: As defined in Intel's Programmer's
229 * Reference Manual, Volume 3, Chapter 8.
230 * @vector_count: Number of contiguous entries in the
231 * Interrupt Descriptor Table that are
232 * occupied by this Message-Signaled
233 * Interrupt. For "MSI", as first defined
234 * in PCI 2.2, this can be between 1 and
235 * 32. For "MSI-X," as first defined in PCI
236 * 3.0, this must be 1, as each MSI-X table
237 * entry would have its own descriptor.
238 * @processor_count: number of bits enabled in array.
239 * @processor_array: All the target virtual processors.
241 struct hv_msi_desc2 {
246 u16 processor_array[32];
250 * struct hv_msi_desc3 - 1.3 version of hv_msi_desc
251 * Everything is the same as in 'hv_msi_desc2' except that the size of the
252 * 'vector' field is larger to support bigger vector values. For ex: LPI
255 struct hv_msi_desc3 {
261 u16 processor_array[32];
265 * struct tran_int_desc
266 * @reserved: unused, padding
267 * @vector_count: same as in hv_msi_desc
268 * @data: This is the "data payload" value that is
269 * written by the device when it generates
270 * a message-signaled interrupt, either MSI
272 * @address: This is the address to which the data
273 * payload is written on interrupt
276 struct tran_int_desc {
284 * A generic message format for virtual PCI.
285 * Specific message formats are defined later in the file.
292 struct pci_child_message {
293 struct pci_message message_type;
294 union win_slot_encoding wslot;
297 struct pci_incoming_message {
298 struct vmpacket_descriptor hdr;
299 struct pci_message message_type;
302 struct pci_response {
303 struct vmpacket_descriptor hdr;
304 s32 status; /* negative values are failures */
308 void (*completion_func)(void *context, struct pci_response *resp,
309 int resp_packet_size);
312 struct pci_message message[];
316 * Specific message types supporting the PCI protocol.
320 * Version negotiation message. Sent from the guest to the host.
321 * The guest is free to try different versions until the host
322 * accepts the version.
324 * pci_version: The protocol version requested.
325 * is_last_attempt: If TRUE, this is the last version guest will request.
326 * reservedz: Reserved field, set to zero.
329 struct pci_version_request {
330 struct pci_message message_type;
331 u32 protocol_version;
335 * Bus D0 Entry. This is sent from the guest to the host when the virtual
336 * bus (PCI Express port) is ready for action.
339 struct pci_bus_d0_entry {
340 struct pci_message message_type;
345 struct pci_bus_relations {
346 struct pci_incoming_message incoming;
348 struct pci_function_description func[];
351 struct pci_bus_relations2 {
352 struct pci_incoming_message incoming;
354 struct pci_function_description2 func[];
357 struct pci_q_res_req_response {
358 struct vmpacket_descriptor hdr;
359 s32 status; /* negative values are failures */
360 u32 probed_bar[PCI_STD_NUM_BARS];
363 struct pci_set_power {
364 struct pci_message message_type;
365 union win_slot_encoding wslot;
366 u32 power_state; /* In Windows terms */
370 struct pci_set_power_response {
371 struct vmpacket_descriptor hdr;
372 s32 status; /* negative values are failures */
373 union win_slot_encoding wslot;
374 u32 resultant_state; /* In Windows terms */
378 struct pci_resources_assigned {
379 struct pci_message message_type;
380 union win_slot_encoding wslot;
381 u8 memory_range[0x14][6]; /* not used here */
386 struct pci_resources_assigned2 {
387 struct pci_message message_type;
388 union win_slot_encoding wslot;
389 u8 memory_range[0x14][6]; /* not used here */
390 u32 msi_descriptor_count;
394 struct pci_create_interrupt {
395 struct pci_message message_type;
396 union win_slot_encoding wslot;
397 struct hv_msi_desc int_desc;
400 struct pci_create_int_response {
401 struct pci_response response;
403 struct tran_int_desc int_desc;
406 struct pci_create_interrupt2 {
407 struct pci_message message_type;
408 union win_slot_encoding wslot;
409 struct hv_msi_desc2 int_desc;
412 struct pci_create_interrupt3 {
413 struct pci_message message_type;
414 union win_slot_encoding wslot;
415 struct hv_msi_desc3 int_desc;
418 struct pci_delete_interrupt {
419 struct pci_message message_type;
420 union win_slot_encoding wslot;
421 struct tran_int_desc int_desc;
425 * Note: the VM must pass a valid block id, wslot and bytes_requested.
427 struct pci_read_block {
428 struct pci_message message_type;
430 union win_slot_encoding wslot;
434 struct pci_read_block_response {
435 struct vmpacket_descriptor hdr;
437 u8 bytes[HV_CONFIG_BLOCK_SIZE_MAX];
441 * Note: the VM must pass a valid block id, wslot and byte_count.
443 struct pci_write_block {
444 struct pci_message message_type;
446 union win_slot_encoding wslot;
448 u8 bytes[HV_CONFIG_BLOCK_SIZE_MAX];
451 struct pci_dev_inval_block {
452 struct pci_incoming_message incoming;
453 union win_slot_encoding wslot;
457 struct pci_dev_incoming {
458 struct pci_incoming_message incoming;
459 union win_slot_encoding wslot;
462 struct pci_eject_response {
463 struct pci_message message_type;
464 union win_slot_encoding wslot;
468 static int pci_ring_size = (4 * PAGE_SIZE);
471 * Driver specific state.
474 enum hv_pcibus_state {
482 struct hv_pcibus_device {
484 struct pci_sysdata sysdata;
485 #elif defined(CONFIG_ARM64)
486 struct pci_config_window sysdata;
488 struct pci_host_bridge *bridge;
489 struct fwnode_handle *fwnode;
490 /* Protocol version negotiated with the host */
491 enum pci_protocol_version_t protocol_version;
493 struct mutex state_lock;
494 enum hv_pcibus_state state;
496 struct hv_device *hdev;
497 resource_size_t low_mmio_space;
498 resource_size_t high_mmio_space;
499 struct resource *mem_config;
500 struct resource *low_mmio_res;
501 struct resource *high_mmio_res;
502 struct completion *survey_event;
503 struct pci_bus *pci_bus;
504 spinlock_t config_lock; /* Avoid two threads writing index page */
505 spinlock_t device_list_lock; /* Protect lists below */
506 void __iomem *cfg_addr;
508 struct list_head children;
509 struct list_head dr_list;
511 struct msi_domain_info msi_info;
512 struct irq_domain *irq_domain;
514 struct workqueue_struct *wq;
516 /* Highest slot of child device with resources allocated */
517 int wslot_res_allocated;
518 bool use_calls; /* Use hypercalls to access mmio cfg space */
522 * Tracks "Device Relations" messages from the host, which must be both
523 * processed in order and deferred so that they don't run in the context
524 * of the incoming packet callback.
527 struct work_struct wrk;
528 struct hv_pcibus_device *bus;
531 struct hv_pcidev_description {
532 u16 v_id; /* vendor ID */
533 u16 d_id; /* device ID */
539 union win_slot_encoding win_slot;
540 u32 ser; /* serial number */
542 u16 virtual_numa_node;
546 struct list_head list_entry;
548 struct hv_pcidev_description func[];
552 /* List protected by pci_rescan_remove_lock */
553 struct list_head list_entry;
555 struct pci_slot *pci_slot;
556 struct hv_pcidev_description desc;
557 bool reported_missing;
558 struct hv_pcibus_device *hbus;
559 struct work_struct wrk;
561 void (*block_invalidate)(void *context, u64 block_mask);
562 void *invalidate_context;
565 * What would be observed if one wrote 0xFFFFFFFF to a BAR and then
566 * read it back, for each of the BAR offsets within config space.
568 u32 probed_bar[PCI_STD_NUM_BARS];
571 struct hv_pci_compl {
572 struct completion host_event;
573 s32 completion_status;
576 static void hv_pci_onchannelcallback(void *context);
579 #define DELIVERY_MODE APIC_DELIVERY_MODE_FIXED
580 #define FLOW_HANDLER handle_edge_irq
581 #define FLOW_NAME "edge"
583 static int hv_pci_irqchip_init(void)
588 static struct irq_domain *hv_pci_get_root_domain(void)
590 return x86_vector_domain;
593 static unsigned int hv_msi_get_int_vector(struct irq_data *data)
595 struct irq_cfg *cfg = irqd_cfg(data);
600 #define hv_msi_prepare pci_msi_prepare
603 * hv_arch_irq_unmask() - "Unmask" the IRQ by setting its current
605 * @data: Describes the IRQ
607 * Build new a destination for the MSI and make a hypercall to
608 * update the Interrupt Redirection Table. "Device Logical ID"
609 * is built out of this PCI bus's instance GUID and the function
610 * number of the device.
612 static void hv_arch_irq_unmask(struct irq_data *data)
614 struct msi_desc *msi_desc = irq_data_get_msi_desc(data);
615 struct hv_retarget_device_interrupt *params;
616 struct tran_int_desc *int_desc;
617 struct hv_pcibus_device *hbus;
618 const struct cpumask *dest;
620 struct pci_bus *pbus;
621 struct pci_dev *pdev;
627 dest = irq_data_get_effective_affinity_mask(data);
628 pdev = msi_desc_to_pci_dev(msi_desc);
630 hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
631 int_desc = data->chip_data;
633 dev_warn(&hbus->hdev->device, "%s() can not unmask irq %u\n",
634 __func__, data->irq);
638 local_irq_save(flags);
640 params = *this_cpu_ptr(hyperv_pcpu_input_arg);
641 memset(params, 0, sizeof(*params));
642 params->partition_id = HV_PARTITION_ID_SELF;
643 params->int_entry.source = HV_INTERRUPT_SOURCE_MSI;
644 params->int_entry.msi_entry.address.as_uint32 = int_desc->address & 0xffffffff;
645 params->int_entry.msi_entry.data.as_uint32 = int_desc->data;
646 params->device_id = (hbus->hdev->dev_instance.b[5] << 24) |
647 (hbus->hdev->dev_instance.b[4] << 16) |
648 (hbus->hdev->dev_instance.b[7] << 8) |
649 (hbus->hdev->dev_instance.b[6] & 0xf8) |
650 PCI_FUNC(pdev->devfn);
651 params->int_target.vector = hv_msi_get_int_vector(data);
654 * Honoring apic->delivery_mode set to APIC_DELIVERY_MODE_FIXED by
655 * setting the HV_DEVICE_INTERRUPT_TARGET_MULTICAST flag results in a
656 * spurious interrupt storm. Not doing so does not seem to have a
657 * negative effect (yet?).
660 if (hbus->protocol_version >= PCI_PROTOCOL_VERSION_1_2) {
662 * PCI_PROTOCOL_VERSION_1_2 supports the VP_SET version of the
663 * HVCALL_RETARGET_INTERRUPT hypercall, which also coincides
664 * with >64 VP support.
665 * ms_hyperv.hints & HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED
666 * is not sufficient for this hypercall.
668 params->int_target.flags |=
669 HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET;
671 if (!alloc_cpumask_var(&tmp, GFP_ATOMIC)) {
676 cpumask_and(tmp, dest, cpu_online_mask);
677 nr_bank = cpumask_to_vpset(¶ms->int_target.vp_set, tmp);
678 free_cpumask_var(tmp);
686 * var-sized hypercall, var-size starts after vp_mask (thus
687 * vp_set.format does not count, but vp_set.valid_bank_mask
690 var_size = 1 + nr_bank;
692 for_each_cpu_and(cpu, dest, cpu_online_mask) {
693 params->int_target.vp_mask |=
694 (1ULL << hv_cpu_number_to_vp_number(cpu));
698 res = hv_do_hypercall(HVCALL_RETARGET_INTERRUPT | (var_size << 17),
702 local_irq_restore(flags);
705 * During hibernation, when a CPU is offlined, the kernel tries
706 * to move the interrupt to the remaining CPUs that haven't
707 * been offlined yet. In this case, the below hv_do_hypercall()
708 * always fails since the vmbus channel has been closed:
709 * refer to cpu_disable_common() -> fixup_irqs() ->
710 * irq_migrate_all_off_this_cpu() -> migrate_one_irq().
712 * Suppress the error message for hibernation because the failure
713 * during hibernation does not matter (at this time all the devices
714 * have been frozen). Note: the correct affinity info is still updated
715 * into the irqdata data structure in migrate_one_irq() ->
716 * irq_do_set_affinity(), so later when the VM resumes,
717 * hv_pci_restore_msi_state() is able to correctly restore the
718 * interrupt with the correct affinity.
720 if (!hv_result_success(res) && hbus->state != hv_pcibus_removing)
721 dev_err(&hbus->hdev->device,
722 "%s() failed: %#llx", __func__, res);
724 #elif defined(CONFIG_ARM64)
726 * SPI vectors to use for vPCI; arch SPIs range is [32, 1019], but leaving a bit
727 * of room at the start to allow for SPIs to be specified through ACPI and
728 * starting with a power of two to satisfy power of 2 multi-MSI requirement.
730 #define HV_PCI_MSI_SPI_START 64
731 #define HV_PCI_MSI_SPI_NR (1020 - HV_PCI_MSI_SPI_START)
732 #define DELIVERY_MODE 0
733 #define FLOW_HANDLER NULL
734 #define FLOW_NAME NULL
735 #define hv_msi_prepare NULL
737 struct hv_pci_chip_data {
738 DECLARE_BITMAP(spi_map, HV_PCI_MSI_SPI_NR);
739 struct mutex map_lock;
742 /* Hyper-V vPCI MSI GIC IRQ domain */
743 static struct irq_domain *hv_msi_gic_irq_domain;
745 /* Hyper-V PCI MSI IRQ chip */
746 static struct irq_chip hv_arm64_msi_irq_chip = {
748 .irq_set_affinity = irq_chip_set_affinity_parent,
749 .irq_eoi = irq_chip_eoi_parent,
750 .irq_mask = irq_chip_mask_parent,
751 .irq_unmask = irq_chip_unmask_parent
754 static unsigned int hv_msi_get_int_vector(struct irq_data *irqd)
756 return irqd->parent_data->hwirq;
760 * @nr_bm_irqs: Indicates the number of IRQs that were allocated from
762 * @nr_dom_irqs: Indicates the number of IRQs that were allocated from
765 static void hv_pci_vec_irq_free(struct irq_domain *domain,
767 unsigned int nr_bm_irqs,
768 unsigned int nr_dom_irqs)
770 struct hv_pci_chip_data *chip_data = domain->host_data;
771 struct irq_data *d = irq_domain_get_irq_data(domain, virq);
772 int first = d->hwirq - HV_PCI_MSI_SPI_START;
775 mutex_lock(&chip_data->map_lock);
776 bitmap_release_region(chip_data->spi_map,
778 get_count_order(nr_bm_irqs));
779 mutex_unlock(&chip_data->map_lock);
780 for (i = 0; i < nr_dom_irqs; i++) {
782 d = irq_domain_get_irq_data(domain, virq + i);
783 irq_domain_reset_irq_data(d);
786 irq_domain_free_irqs_parent(domain, virq, nr_dom_irqs);
789 static void hv_pci_vec_irq_domain_free(struct irq_domain *domain,
791 unsigned int nr_irqs)
793 hv_pci_vec_irq_free(domain, virq, nr_irqs, nr_irqs);
796 static int hv_pci_vec_alloc_device_irq(struct irq_domain *domain,
797 unsigned int nr_irqs,
798 irq_hw_number_t *hwirq)
800 struct hv_pci_chip_data *chip_data = domain->host_data;
803 /* Find and allocate region from the SPI bitmap */
804 mutex_lock(&chip_data->map_lock);
805 index = bitmap_find_free_region(chip_data->spi_map,
807 get_count_order(nr_irqs));
808 mutex_unlock(&chip_data->map_lock);
812 *hwirq = index + HV_PCI_MSI_SPI_START;
817 static int hv_pci_vec_irq_gic_domain_alloc(struct irq_domain *domain,
819 irq_hw_number_t hwirq)
821 struct irq_fwspec fwspec;
825 fwspec.fwnode = domain->parent->fwnode;
826 fwspec.param_count = 2;
827 fwspec.param[0] = hwirq;
828 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
830 ret = irq_domain_alloc_irqs_parent(domain, virq, 1, &fwspec);
835 * Since the interrupt specifier is not coming from ACPI or DT, the
836 * trigger type will need to be set explicitly. Otherwise, it will be
837 * set to whatever is in the GIC configuration.
839 d = irq_domain_get_irq_data(domain->parent, virq);
841 return d->chip->irq_set_type(d, IRQ_TYPE_EDGE_RISING);
844 static int hv_pci_vec_irq_domain_alloc(struct irq_domain *domain,
845 unsigned int virq, unsigned int nr_irqs,
848 irq_hw_number_t hwirq;
852 ret = hv_pci_vec_alloc_device_irq(domain, nr_irqs, &hwirq);
856 for (i = 0; i < nr_irqs; i++) {
857 ret = hv_pci_vec_irq_gic_domain_alloc(domain, virq + i,
860 hv_pci_vec_irq_free(domain, virq, nr_irqs, i);
864 irq_domain_set_hwirq_and_chip(domain, virq + i,
866 &hv_arm64_msi_irq_chip,
868 pr_debug("pID:%d vID:%u\n", (int)(hwirq + i), virq + i);
875 * Pick the first cpu as the irq affinity that can be temporarily used for
876 * composing MSI from the hypervisor. GIC will eventually set the right
877 * affinity for the irq and the 'unmask' will retarget the interrupt to that
880 static int hv_pci_vec_irq_domain_activate(struct irq_domain *domain,
881 struct irq_data *irqd, bool reserve)
883 int cpu = cpumask_first(cpu_present_mask);
885 irq_data_update_effective_affinity(irqd, cpumask_of(cpu));
890 static const struct irq_domain_ops hv_pci_domain_ops = {
891 .alloc = hv_pci_vec_irq_domain_alloc,
892 .free = hv_pci_vec_irq_domain_free,
893 .activate = hv_pci_vec_irq_domain_activate,
896 static int hv_pci_irqchip_init(void)
898 static struct hv_pci_chip_data *chip_data;
899 struct fwnode_handle *fn = NULL;
902 chip_data = kzalloc(sizeof(*chip_data), GFP_KERNEL);
906 mutex_init(&chip_data->map_lock);
907 fn = irq_domain_alloc_named_fwnode("hv_vpci_arm64");
912 * IRQ domain once enabled, should not be removed since there is no
913 * way to ensure that all the corresponding devices are also gone and
914 * no interrupts will be generated.
916 hv_msi_gic_irq_domain = acpi_irq_create_hierarchy(0, HV_PCI_MSI_SPI_NR,
917 fn, &hv_pci_domain_ops,
920 if (!hv_msi_gic_irq_domain) {
921 pr_err("Failed to create Hyper-V arm64 vPCI MSI IRQ domain\n");
930 irq_domain_free_fwnode(fn);
935 static struct irq_domain *hv_pci_get_root_domain(void)
937 return hv_msi_gic_irq_domain;
941 * SPIs are used for interrupts of PCI devices and SPIs is managed via GICD
942 * registers which Hyper-V already supports, so no hypercall needed.
944 static void hv_arch_irq_unmask(struct irq_data *data) { }
945 #endif /* CONFIG_ARM64 */
948 * hv_pci_generic_compl() - Invoked for a completion packet
949 * @context: Set up by the sender of the packet.
950 * @resp: The response packet
951 * @resp_packet_size: Size in bytes of the packet
953 * This function is used to trigger an event and report status
954 * for any message for which the completion packet contains a
955 * status and nothing else.
957 static void hv_pci_generic_compl(void *context, struct pci_response *resp,
958 int resp_packet_size)
960 struct hv_pci_compl *comp_pkt = context;
962 comp_pkt->completion_status = resp->status;
963 complete(&comp_pkt->host_event);
966 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
969 static void get_pcichild(struct hv_pci_dev *hpdev)
971 refcount_inc(&hpdev->refs);
974 static void put_pcichild(struct hv_pci_dev *hpdev)
976 if (refcount_dec_and_test(&hpdev->refs))
981 * There is no good way to get notified from vmbus_onoffer_rescind(),
982 * so let's use polling here, since this is not a hot path.
984 static int wait_for_response(struct hv_device *hdev,
985 struct completion *comp)
988 if (hdev->channel->rescind) {
989 dev_warn_once(&hdev->device, "The device is gone.\n");
993 if (wait_for_completion_timeout(comp, HZ / 10))
1001 * devfn_to_wslot() - Convert from Linux PCI slot to Windows
1002 * @devfn: The Linux representation of PCI slot
1004 * Windows uses a slightly different representation of PCI slot.
1006 * Return: The Windows representation
1008 static u32 devfn_to_wslot(int devfn)
1010 union win_slot_encoding wslot;
1013 wslot.bits.dev = PCI_SLOT(devfn);
1014 wslot.bits.func = PCI_FUNC(devfn);
1020 * wslot_to_devfn() - Convert from Windows PCI slot to Linux
1021 * @wslot: The Windows representation of PCI slot
1023 * Windows uses a slightly different representation of PCI slot.
1025 * Return: The Linux representation
1027 static int wslot_to_devfn(u32 wslot)
1029 union win_slot_encoding slot_no;
1031 slot_no.slot = wslot;
1032 return PCI_DEVFN(slot_no.bits.dev, slot_no.bits.func);
1035 static void hv_pci_read_mmio(struct device *dev, phys_addr_t gpa, int size, u32 *val)
1037 struct hv_mmio_read_input *in;
1038 struct hv_mmio_read_output *out;
1042 * Must be called with interrupts disabled so it is safe
1043 * to use the per-cpu input argument page. Use it for
1044 * both input and output.
1046 in = *this_cpu_ptr(hyperv_pcpu_input_arg);
1047 out = *this_cpu_ptr(hyperv_pcpu_input_arg) + sizeof(*in);
1051 ret = hv_do_hypercall(HVCALL_MMIO_READ, in, out);
1052 if (hv_result_success(ret)) {
1055 *val = *(u8 *)(out->data);
1058 *val = *(u16 *)(out->data);
1061 *val = *(u32 *)(out->data);
1065 dev_err(dev, "MMIO read hypercall error %llx addr %llx size %d\n",
1069 static void hv_pci_write_mmio(struct device *dev, phys_addr_t gpa, int size, u32 val)
1071 struct hv_mmio_write_input *in;
1075 * Must be called with interrupts disabled so it is safe
1076 * to use the per-cpu input argument memory.
1078 in = *this_cpu_ptr(hyperv_pcpu_input_arg);
1083 *(u8 *)(in->data) = val;
1086 *(u16 *)(in->data) = val;
1089 *(u32 *)(in->data) = val;
1093 ret = hv_do_hypercall(HVCALL_MMIO_WRITE, in, NULL);
1094 if (!hv_result_success(ret))
1095 dev_err(dev, "MMIO write hypercall error %llx addr %llx size %d\n",
1100 * PCI Configuration Space for these root PCI buses is implemented as a pair
1101 * of pages in memory-mapped I/O space. Writing to the first page chooses
1102 * the PCI function being written or read. Once the first page has been
1103 * written to, the following page maps in the entire configuration space of
1108 * _hv_pcifront_read_config() - Internal PCI config read
1109 * @hpdev: The PCI driver's representation of the device
1110 * @where: Offset within config space
1111 * @size: Size of the transfer
1112 * @val: Pointer to the buffer receiving the data
1114 static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where,
1117 struct hv_pcibus_device *hbus = hpdev->hbus;
1118 struct device *dev = &hbus->hdev->device;
1119 int offset = where + CFG_PAGE_OFFSET;
1120 unsigned long flags;
1123 * If the attempt is to read the IDs or the ROM BAR, simulate that.
1125 if (where + size <= PCI_COMMAND) {
1126 memcpy(val, ((u8 *)&hpdev->desc.v_id) + where, size);
1127 } else if (where >= PCI_CLASS_REVISION && where + size <=
1128 PCI_CACHE_LINE_SIZE) {
1129 memcpy(val, ((u8 *)&hpdev->desc.rev) + where -
1130 PCI_CLASS_REVISION, size);
1131 } else if (where >= PCI_SUBSYSTEM_VENDOR_ID && where + size <=
1133 memcpy(val, (u8 *)&hpdev->desc.subsystem_id + where -
1134 PCI_SUBSYSTEM_VENDOR_ID, size);
1135 } else if (where >= PCI_ROM_ADDRESS && where + size <=
1136 PCI_CAPABILITY_LIST) {
1137 /* ROM BARs are unimplemented */
1139 } else if (where >= PCI_INTERRUPT_LINE && where + size <=
1140 PCI_INTERRUPT_PIN) {
1142 * Interrupt Line and Interrupt PIN are hard-wired to zero
1143 * because this front-end only supports message-signaled
1147 } else if (where + size <= CFG_PAGE_SIZE) {
1149 spin_lock_irqsave(&hbus->config_lock, flags);
1150 if (hbus->use_calls) {
1151 phys_addr_t addr = hbus->mem_config->start + offset;
1153 hv_pci_write_mmio(dev, hbus->mem_config->start, 4,
1154 hpdev->desc.win_slot.slot);
1155 hv_pci_read_mmio(dev, addr, size, val);
1157 void __iomem *addr = hbus->cfg_addr + offset;
1159 /* Choose the function to be read. (See comment above) */
1160 writel(hpdev->desc.win_slot.slot, hbus->cfg_addr);
1161 /* Make sure the function was chosen before reading. */
1163 /* Read from that function's config space. */
1176 * Make sure the read was done before we release the
1177 * spinlock allowing consecutive reads/writes.
1181 spin_unlock_irqrestore(&hbus->config_lock, flags);
1183 dev_err(dev, "Attempt to read beyond a function's config space.\n");
1187 static u16 hv_pcifront_get_vendor_id(struct hv_pci_dev *hpdev)
1189 struct hv_pcibus_device *hbus = hpdev->hbus;
1190 struct device *dev = &hbus->hdev->device;
1193 unsigned long flags;
1195 spin_lock_irqsave(&hbus->config_lock, flags);
1197 if (hbus->use_calls) {
1198 phys_addr_t addr = hbus->mem_config->start +
1199 CFG_PAGE_OFFSET + PCI_VENDOR_ID;
1201 hv_pci_write_mmio(dev, hbus->mem_config->start, 4,
1202 hpdev->desc.win_slot.slot);
1203 hv_pci_read_mmio(dev, addr, 2, &val);
1204 ret = val; /* Truncates to 16 bits */
1206 void __iomem *addr = hbus->cfg_addr + CFG_PAGE_OFFSET +
1208 /* Choose the function to be read. (See comment above) */
1209 writel(hpdev->desc.win_slot.slot, hbus->cfg_addr);
1210 /* Make sure the function was chosen before we start reading. */
1212 /* Read from that function's config space. */
1215 * mb() is not required here, because the
1216 * spin_unlock_irqrestore() is a barrier.
1220 spin_unlock_irqrestore(&hbus->config_lock, flags);
1226 * _hv_pcifront_write_config() - Internal PCI config write
1227 * @hpdev: The PCI driver's representation of the device
1228 * @where: Offset within config space
1229 * @size: Size of the transfer
1230 * @val: The data being transferred
1232 static void _hv_pcifront_write_config(struct hv_pci_dev *hpdev, int where,
1235 struct hv_pcibus_device *hbus = hpdev->hbus;
1236 struct device *dev = &hbus->hdev->device;
1237 int offset = where + CFG_PAGE_OFFSET;
1238 unsigned long flags;
1240 if (where >= PCI_SUBSYSTEM_VENDOR_ID &&
1241 where + size <= PCI_CAPABILITY_LIST) {
1242 /* SSIDs and ROM BARs are read-only */
1243 } else if (where >= PCI_COMMAND && where + size <= CFG_PAGE_SIZE) {
1244 spin_lock_irqsave(&hbus->config_lock, flags);
1246 if (hbus->use_calls) {
1247 phys_addr_t addr = hbus->mem_config->start + offset;
1249 hv_pci_write_mmio(dev, hbus->mem_config->start, 4,
1250 hpdev->desc.win_slot.slot);
1251 hv_pci_write_mmio(dev, addr, size, val);
1253 void __iomem *addr = hbus->cfg_addr + offset;
1255 /* Choose the function to write. (See comment above) */
1256 writel(hpdev->desc.win_slot.slot, hbus->cfg_addr);
1257 /* Make sure the function was chosen before writing. */
1259 /* Write to that function's config space. */
1272 * Make sure the write was done before we release the
1273 * spinlock allowing consecutive reads/writes.
1277 spin_unlock_irqrestore(&hbus->config_lock, flags);
1279 dev_err(dev, "Attempt to write beyond a function's config space.\n");
1284 * hv_pcifront_read_config() - Read configuration space
1285 * @bus: PCI Bus structure
1286 * @devfn: Device/function
1287 * @where: Offset from base
1288 * @size: Byte/word/dword
1289 * @val: Value to be read
1291 * Return: PCIBIOS_SUCCESSFUL on success
1292 * PCIBIOS_DEVICE_NOT_FOUND on failure
1294 static int hv_pcifront_read_config(struct pci_bus *bus, unsigned int devfn,
1295 int where, int size, u32 *val)
1297 struct hv_pcibus_device *hbus =
1298 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
1299 struct hv_pci_dev *hpdev;
1301 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
1303 return PCIBIOS_DEVICE_NOT_FOUND;
1305 _hv_pcifront_read_config(hpdev, where, size, val);
1307 put_pcichild(hpdev);
1308 return PCIBIOS_SUCCESSFUL;
1312 * hv_pcifront_write_config() - Write configuration space
1313 * @bus: PCI Bus structure
1314 * @devfn: Device/function
1315 * @where: Offset from base
1316 * @size: Byte/word/dword
1317 * @val: Value to be written to device
1319 * Return: PCIBIOS_SUCCESSFUL on success
1320 * PCIBIOS_DEVICE_NOT_FOUND on failure
1322 static int hv_pcifront_write_config(struct pci_bus *bus, unsigned int devfn,
1323 int where, int size, u32 val)
1325 struct hv_pcibus_device *hbus =
1326 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
1327 struct hv_pci_dev *hpdev;
1329 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
1331 return PCIBIOS_DEVICE_NOT_FOUND;
1333 _hv_pcifront_write_config(hpdev, where, size, val);
1335 put_pcichild(hpdev);
1336 return PCIBIOS_SUCCESSFUL;
1339 /* PCIe operations */
1340 static struct pci_ops hv_pcifront_ops = {
1341 .read = hv_pcifront_read_config,
1342 .write = hv_pcifront_write_config,
1346 * Paravirtual backchannel
1348 * Hyper-V SR-IOV provides a backchannel mechanism in software for
1349 * communication between a VF driver and a PF driver. These
1350 * "configuration blocks" are similar in concept to PCI configuration space,
1351 * but instead of doing reads and writes in 32-bit chunks through a very slow
1352 * path, packets of up to 128 bytes can be sent or received asynchronously.
1354 * Nearly every SR-IOV device contains just such a communications channel in
1355 * hardware, so using this one in software is usually optional. Using the
1356 * software channel, however, allows driver implementers to leverage software
1357 * tools that fuzz the communications channel looking for vulnerabilities.
1359 * The usage model for these packets puts the responsibility for reading or
1360 * writing on the VF driver. The VF driver sends a read or a write packet,
1361 * indicating which "block" is being referred to by number.
1363 * If the PF driver wishes to initiate communication, it can "invalidate" one or
1364 * more of the first 64 blocks. This invalidation is delivered via a callback
1365 * supplied by the VF driver by this driver.
1367 * No protocol is implied, except that supplied by the PF and VF drivers.
1370 struct hv_read_config_compl {
1371 struct hv_pci_compl comp_pkt;
1374 unsigned int bytes_returned;
1378 * hv_pci_read_config_compl() - Invoked when a response packet
1379 * for a read config block operation arrives.
1380 * @context: Identifies the read config operation
1381 * @resp: The response packet itself
1382 * @resp_packet_size: Size in bytes of the response packet
1384 static void hv_pci_read_config_compl(void *context, struct pci_response *resp,
1385 int resp_packet_size)
1387 struct hv_read_config_compl *comp = context;
1388 struct pci_read_block_response *read_resp =
1389 (struct pci_read_block_response *)resp;
1390 unsigned int data_len, hdr_len;
1392 hdr_len = offsetof(struct pci_read_block_response, bytes);
1393 if (resp_packet_size < hdr_len) {
1394 comp->comp_pkt.completion_status = -1;
1398 data_len = resp_packet_size - hdr_len;
1399 if (data_len > 0 && read_resp->status == 0) {
1400 comp->bytes_returned = min(comp->len, data_len);
1401 memcpy(comp->buf, read_resp->bytes, comp->bytes_returned);
1403 comp->bytes_returned = 0;
1406 comp->comp_pkt.completion_status = read_resp->status;
1408 complete(&comp->comp_pkt.host_event);
1412 * hv_read_config_block() - Sends a read config block request to
1413 * the back-end driver running in the Hyper-V parent partition.
1414 * @pdev: The PCI driver's representation for this device.
1415 * @buf: Buffer into which the config block will be copied.
1416 * @len: Size in bytes of buf.
1417 * @block_id: Identifies the config block which has been requested.
1418 * @bytes_returned: Size which came back from the back-end driver.
1420 * Return: 0 on success, -errno on failure
1422 static int hv_read_config_block(struct pci_dev *pdev, void *buf,
1423 unsigned int len, unsigned int block_id,
1424 unsigned int *bytes_returned)
1426 struct hv_pcibus_device *hbus =
1427 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1430 struct pci_packet pkt;
1431 char buf[sizeof(struct pci_read_block)];
1433 struct hv_read_config_compl comp_pkt;
1434 struct pci_read_block *read_blk;
1437 if (len == 0 || len > HV_CONFIG_BLOCK_SIZE_MAX)
1440 init_completion(&comp_pkt.comp_pkt.host_event);
1444 memset(&pkt, 0, sizeof(pkt));
1445 pkt.pkt.completion_func = hv_pci_read_config_compl;
1446 pkt.pkt.compl_ctxt = &comp_pkt;
1447 read_blk = (struct pci_read_block *)&pkt.pkt.message;
1448 read_blk->message_type.type = PCI_READ_BLOCK;
1449 read_blk->wslot.slot = devfn_to_wslot(pdev->devfn);
1450 read_blk->block_id = block_id;
1451 read_blk->bytes_requested = len;
1453 ret = vmbus_sendpacket(hbus->hdev->channel, read_blk,
1454 sizeof(*read_blk), (unsigned long)&pkt.pkt,
1456 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1460 ret = wait_for_response(hbus->hdev, &comp_pkt.comp_pkt.host_event);
1464 if (comp_pkt.comp_pkt.completion_status != 0 ||
1465 comp_pkt.bytes_returned == 0) {
1466 dev_err(&hbus->hdev->device,
1467 "Read Config Block failed: 0x%x, bytes_returned=%d\n",
1468 comp_pkt.comp_pkt.completion_status,
1469 comp_pkt.bytes_returned);
1473 *bytes_returned = comp_pkt.bytes_returned;
1478 * hv_pci_write_config_compl() - Invoked when a response packet for a write
1479 * config block operation arrives.
1480 * @context: Identifies the write config operation
1481 * @resp: The response packet itself
1482 * @resp_packet_size: Size in bytes of the response packet
1484 static void hv_pci_write_config_compl(void *context, struct pci_response *resp,
1485 int resp_packet_size)
1487 struct hv_pci_compl *comp_pkt = context;
1489 comp_pkt->completion_status = resp->status;
1490 complete(&comp_pkt->host_event);
1494 * hv_write_config_block() - Sends a write config block request to the
1495 * back-end driver running in the Hyper-V parent partition.
1496 * @pdev: The PCI driver's representation for this device.
1497 * @buf: Buffer from which the config block will be copied.
1498 * @len: Size in bytes of buf.
1499 * @block_id: Identifies the config block which is being written.
1501 * Return: 0 on success, -errno on failure
1503 static int hv_write_config_block(struct pci_dev *pdev, void *buf,
1504 unsigned int len, unsigned int block_id)
1506 struct hv_pcibus_device *hbus =
1507 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1510 struct pci_packet pkt;
1511 char buf[sizeof(struct pci_write_block)];
1514 struct hv_pci_compl comp_pkt;
1515 struct pci_write_block *write_blk;
1519 if (len == 0 || len > HV_CONFIG_BLOCK_SIZE_MAX)
1522 init_completion(&comp_pkt.host_event);
1524 memset(&pkt, 0, sizeof(pkt));
1525 pkt.pkt.completion_func = hv_pci_write_config_compl;
1526 pkt.pkt.compl_ctxt = &comp_pkt;
1527 write_blk = (struct pci_write_block *)&pkt.pkt.message;
1528 write_blk->message_type.type = PCI_WRITE_BLOCK;
1529 write_blk->wslot.slot = devfn_to_wslot(pdev->devfn);
1530 write_blk->block_id = block_id;
1531 write_blk->byte_count = len;
1532 memcpy(write_blk->bytes, buf, len);
1533 pkt_size = offsetof(struct pci_write_block, bytes) + len;
1535 * This quirk is required on some hosts shipped around 2018, because
1536 * these hosts don't check the pkt_size correctly (new hosts have been
1537 * fixed since early 2019). The quirk is also safe on very old hosts
1538 * and new hosts, because, on them, what really matters is the length
1539 * specified in write_blk->byte_count.
1541 pkt_size += sizeof(pkt.reserved);
1543 ret = vmbus_sendpacket(hbus->hdev->channel, write_blk, pkt_size,
1544 (unsigned long)&pkt.pkt, VM_PKT_DATA_INBAND,
1545 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1549 ret = wait_for_response(hbus->hdev, &comp_pkt.host_event);
1553 if (comp_pkt.completion_status != 0) {
1554 dev_err(&hbus->hdev->device,
1555 "Write Config Block failed: 0x%x\n",
1556 comp_pkt.completion_status);
1564 * hv_register_block_invalidate() - Invoked when a config block invalidation
1565 * arrives from the back-end driver.
1566 * @pdev: The PCI driver's representation for this device.
1567 * @context: Identifies the device.
1568 * @block_invalidate: Identifies all of the blocks being invalidated.
1570 * Return: 0 on success, -errno on failure
1572 static int hv_register_block_invalidate(struct pci_dev *pdev, void *context,
1573 void (*block_invalidate)(void *context,
1576 struct hv_pcibus_device *hbus =
1577 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1579 struct hv_pci_dev *hpdev;
1581 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1585 hpdev->block_invalidate = block_invalidate;
1586 hpdev->invalidate_context = context;
1588 put_pcichild(hpdev);
1593 /* Interrupt management hooks */
1594 static void hv_int_desc_free(struct hv_pci_dev *hpdev,
1595 struct tran_int_desc *int_desc)
1597 struct pci_delete_interrupt *int_pkt;
1599 struct pci_packet pkt;
1600 u8 buffer[sizeof(struct pci_delete_interrupt)];
1603 if (!int_desc->vector_count) {
1607 memset(&ctxt, 0, sizeof(ctxt));
1608 int_pkt = (struct pci_delete_interrupt *)&ctxt.pkt.message;
1609 int_pkt->message_type.type =
1610 PCI_DELETE_INTERRUPT_MESSAGE;
1611 int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
1612 int_pkt->int_desc = *int_desc;
1613 vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt, sizeof(*int_pkt),
1614 0, VM_PKT_DATA_INBAND, 0);
1619 * hv_msi_free() - Free the MSI.
1620 * @domain: The interrupt domain pointer
1621 * @info: Extra MSI-related context
1622 * @irq: Identifies the IRQ.
1624 * The Hyper-V parent partition and hypervisor are tracking the
1625 * messages that are in use, keeping the interrupt redirection
1626 * table up to date. This callback sends a message that frees
1627 * the IRT entry and related tracking nonsense.
1629 static void hv_msi_free(struct irq_domain *domain, struct msi_domain_info *info,
1632 struct hv_pcibus_device *hbus;
1633 struct hv_pci_dev *hpdev;
1634 struct pci_dev *pdev;
1635 struct tran_int_desc *int_desc;
1636 struct irq_data *irq_data = irq_domain_get_irq_data(domain, irq);
1637 struct msi_desc *msi = irq_data_get_msi_desc(irq_data);
1639 pdev = msi_desc_to_pci_dev(msi);
1641 int_desc = irq_data_get_irq_chip_data(irq_data);
1645 irq_data->chip_data = NULL;
1646 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1652 hv_int_desc_free(hpdev, int_desc);
1653 put_pcichild(hpdev);
1656 static void hv_irq_mask(struct irq_data *data)
1658 pci_msi_mask_irq(data);
1659 if (data->parent_data->chip->irq_mask)
1660 irq_chip_mask_parent(data);
1663 static void hv_irq_unmask(struct irq_data *data)
1665 hv_arch_irq_unmask(data);
1667 if (data->parent_data->chip->irq_unmask)
1668 irq_chip_unmask_parent(data);
1669 pci_msi_unmask_irq(data);
1672 struct compose_comp_ctxt {
1673 struct hv_pci_compl comp_pkt;
1674 struct tran_int_desc int_desc;
1677 static void hv_pci_compose_compl(void *context, struct pci_response *resp,
1678 int resp_packet_size)
1680 struct compose_comp_ctxt *comp_pkt = context;
1681 struct pci_create_int_response *int_resp =
1682 (struct pci_create_int_response *)resp;
1684 if (resp_packet_size < sizeof(*int_resp)) {
1685 comp_pkt->comp_pkt.completion_status = -1;
1688 comp_pkt->comp_pkt.completion_status = resp->status;
1689 comp_pkt->int_desc = int_resp->int_desc;
1691 complete(&comp_pkt->comp_pkt.host_event);
1694 static u32 hv_compose_msi_req_v1(
1695 struct pci_create_interrupt *int_pkt,
1696 u32 slot, u8 vector, u16 vector_count)
1698 int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE;
1699 int_pkt->wslot.slot = slot;
1700 int_pkt->int_desc.vector = vector;
1701 int_pkt->int_desc.vector_count = vector_count;
1702 int_pkt->int_desc.delivery_mode = DELIVERY_MODE;
1705 * Create MSI w/ dummy vCPU set, overwritten by subsequent retarget in
1708 int_pkt->int_desc.cpu_mask = CPU_AFFINITY_ALL;
1710 return sizeof(*int_pkt);
1714 * The vCPU selected by hv_compose_multi_msi_req_get_cpu() and
1715 * hv_compose_msi_req_get_cpu() is a "dummy" vCPU because the final vCPU to be
1716 * interrupted is specified later in hv_irq_unmask() and communicated to Hyper-V
1717 * via the HVCALL_RETARGET_INTERRUPT hypercall. But the choice of dummy vCPU is
1718 * not irrelevant because Hyper-V chooses the physical CPU to handle the
1719 * interrupts based on the vCPU specified in message sent to the vPCI VSP in
1720 * hv_compose_msi_msg(). Hyper-V's choice of pCPU is not visible to the guest,
1721 * but assigning too many vPCI device interrupts to the same pCPU can cause a
1722 * performance bottleneck. So we spread out the dummy vCPUs to influence Hyper-V
1723 * to spread out the pCPUs that it selects.
1725 * For the single-MSI and MSI-X cases, it's OK for hv_compose_msi_req_get_cpu()
1726 * to always return the same dummy vCPU, because a second call to
1727 * hv_compose_msi_msg() contains the "real" vCPU, causing Hyper-V to choose a
1728 * new pCPU for the interrupt. But for the multi-MSI case, the second call to
1729 * hv_compose_msi_msg() exits without sending a message to the vPCI VSP, so the
1730 * original dummy vCPU is used. This dummy vCPU must be round-robin'ed so that
1731 * the pCPUs are spread out. All interrupts for a multi-MSI device end up using
1732 * the same pCPU, even though the vCPUs will be spread out by later calls
1733 * to hv_irq_unmask(), but that is the best we can do now.
1735 * With Hyper-V in Nov 2022, the HVCALL_RETARGET_INTERRUPT hypercall does *not*
1736 * cause Hyper-V to reselect the pCPU based on the specified vCPU. Such an
1737 * enhancement is planned for a future version. With that enhancement, the
1738 * dummy vCPU selection won't matter, and interrupts for the same multi-MSI
1739 * device will be spread across multiple pCPUs.
1743 * Create MSI w/ dummy vCPU set targeting just one vCPU, overwritten
1744 * by subsequent retarget in hv_irq_unmask().
1746 static int hv_compose_msi_req_get_cpu(const struct cpumask *affinity)
1748 return cpumask_first_and(affinity, cpu_online_mask);
1752 * Make sure the dummy vCPU values for multi-MSI don't all point to vCPU0.
1754 static int hv_compose_multi_msi_req_get_cpu(void)
1756 static DEFINE_SPINLOCK(multi_msi_cpu_lock);
1758 /* -1 means starting with CPU 0 */
1759 static int cpu_next = -1;
1761 unsigned long flags;
1764 spin_lock_irqsave(&multi_msi_cpu_lock, flags);
1766 cpu_next = cpumask_next_wrap(cpu_next, cpu_online_mask, nr_cpu_ids,
1770 spin_unlock_irqrestore(&multi_msi_cpu_lock, flags);
1775 static u32 hv_compose_msi_req_v2(
1776 struct pci_create_interrupt2 *int_pkt, int cpu,
1777 u32 slot, u8 vector, u16 vector_count)
1779 int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE2;
1780 int_pkt->wslot.slot = slot;
1781 int_pkt->int_desc.vector = vector;
1782 int_pkt->int_desc.vector_count = vector_count;
1783 int_pkt->int_desc.delivery_mode = DELIVERY_MODE;
1784 int_pkt->int_desc.processor_array[0] =
1785 hv_cpu_number_to_vp_number(cpu);
1786 int_pkt->int_desc.processor_count = 1;
1788 return sizeof(*int_pkt);
1791 static u32 hv_compose_msi_req_v3(
1792 struct pci_create_interrupt3 *int_pkt, int cpu,
1793 u32 slot, u32 vector, u16 vector_count)
1795 int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE3;
1796 int_pkt->wslot.slot = slot;
1797 int_pkt->int_desc.vector = vector;
1798 int_pkt->int_desc.reserved = 0;
1799 int_pkt->int_desc.vector_count = vector_count;
1800 int_pkt->int_desc.delivery_mode = DELIVERY_MODE;
1801 int_pkt->int_desc.processor_array[0] =
1802 hv_cpu_number_to_vp_number(cpu);
1803 int_pkt->int_desc.processor_count = 1;
1805 return sizeof(*int_pkt);
1809 * hv_compose_msi_msg() - Supplies a valid MSI address/data
1810 * @data: Everything about this MSI
1811 * @msg: Buffer that is filled in by this function
1813 * This function unpacks the IRQ looking for target CPU set, IDT
1814 * vector and mode and sends a message to the parent partition
1815 * asking for a mapping for that tuple in this partition. The
1816 * response supplies a data value and address to which that data
1817 * should be written to trigger that interrupt.
1819 static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
1821 struct hv_pcibus_device *hbus;
1822 struct vmbus_channel *channel;
1823 struct hv_pci_dev *hpdev;
1824 struct pci_bus *pbus;
1825 struct pci_dev *pdev;
1826 const struct cpumask *dest;
1827 struct compose_comp_ctxt comp;
1828 struct tran_int_desc *int_desc;
1829 struct msi_desc *msi_desc;
1831 * vector_count should be u16: see hv_msi_desc, hv_msi_desc2
1832 * and hv_msi_desc3. vector must be u32: see hv_msi_desc3.
1837 struct pci_packet pci_pkt;
1839 struct pci_create_interrupt v1;
1840 struct pci_create_interrupt2 v2;
1841 struct pci_create_interrupt3 v3;
1850 msi_desc = irq_data_get_msi_desc(data);
1851 multi_msi = !msi_desc->pci.msi_attrib.is_msix &&
1852 msi_desc->nvec_used > 1;
1854 /* Reuse the previous allocation */
1855 if (data->chip_data && multi_msi) {
1856 int_desc = data->chip_data;
1857 msg->address_hi = int_desc->address >> 32;
1858 msg->address_lo = int_desc->address & 0xffffffff;
1859 msg->data = int_desc->data;
1863 pdev = msi_desc_to_pci_dev(msi_desc);
1864 dest = irq_data_get_effective_affinity_mask(data);
1866 hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
1867 channel = hbus->hdev->channel;
1868 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1870 goto return_null_message;
1872 /* Free any previous message that might have already been composed. */
1873 if (data->chip_data && !multi_msi) {
1874 int_desc = data->chip_data;
1875 data->chip_data = NULL;
1876 hv_int_desc_free(hpdev, int_desc);
1879 int_desc = kzalloc(sizeof(*int_desc), GFP_ATOMIC);
1881 goto drop_reference;
1885 * If this is not the first MSI of Multi MSI, we already have
1886 * a mapping. Can exit early.
1888 if (msi_desc->irq != data->irq) {
1889 data->chip_data = int_desc;
1890 int_desc->address = msi_desc->msg.address_lo |
1891 (u64)msi_desc->msg.address_hi << 32;
1892 int_desc->data = msi_desc->msg.data +
1893 (data->irq - msi_desc->irq);
1894 msg->address_hi = msi_desc->msg.address_hi;
1895 msg->address_lo = msi_desc->msg.address_lo;
1896 msg->data = int_desc->data;
1897 put_pcichild(hpdev);
1901 * The vector we select here is a dummy value. The correct
1902 * value gets sent to the hypervisor in unmask(). This needs
1903 * to be aligned with the count, and also not zero. Multi-msi
1904 * is powers of 2 up to 32, so 32 will always work here.
1907 vector_count = msi_desc->nvec_used;
1908 cpu = hv_compose_multi_msi_req_get_cpu();
1910 vector = hv_msi_get_int_vector(data);
1912 cpu = hv_compose_msi_req_get_cpu(dest);
1916 * hv_compose_msi_req_v1 and v2 are for x86 only, meaning 'vector'
1917 * can't exceed u8. Cast 'vector' down to u8 for v1/v2 explicitly
1918 * for better readability.
1920 memset(&ctxt, 0, sizeof(ctxt));
1921 init_completion(&comp.comp_pkt.host_event);
1922 ctxt.pci_pkt.completion_func = hv_pci_compose_compl;
1923 ctxt.pci_pkt.compl_ctxt = ∁
1925 switch (hbus->protocol_version) {
1926 case PCI_PROTOCOL_VERSION_1_1:
1927 size = hv_compose_msi_req_v1(&ctxt.int_pkts.v1,
1928 hpdev->desc.win_slot.slot,
1933 case PCI_PROTOCOL_VERSION_1_2:
1934 case PCI_PROTOCOL_VERSION_1_3:
1935 size = hv_compose_msi_req_v2(&ctxt.int_pkts.v2,
1937 hpdev->desc.win_slot.slot,
1942 case PCI_PROTOCOL_VERSION_1_4:
1943 size = hv_compose_msi_req_v3(&ctxt.int_pkts.v3,
1945 hpdev->desc.win_slot.slot,
1951 /* As we only negotiate protocol versions known to this driver,
1952 * this path should never hit. However, this is it not a hot
1953 * path so we print a message to aid future updates.
1955 dev_err(&hbus->hdev->device,
1956 "Unexpected vPCI protocol, update driver.");
1960 ret = vmbus_sendpacket_getid(hpdev->hbus->hdev->channel, &ctxt.int_pkts,
1961 size, (unsigned long)&ctxt.pci_pkt,
1962 &trans_id, VM_PKT_DATA_INBAND,
1963 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1965 dev_err(&hbus->hdev->device,
1966 "Sending request for interrupt failed: 0x%x",
1967 comp.comp_pkt.completion_status);
1972 * Prevents hv_pci_onchannelcallback() from running concurrently
1975 tasklet_disable_in_atomic(&channel->callback_event);
1978 * Since this function is called with IRQ locks held, can't
1979 * do normal wait for completion; instead poll.
1981 while (!try_wait_for_completion(&comp.comp_pkt.host_event)) {
1982 unsigned long flags;
1984 /* 0xFFFF means an invalid PCI VENDOR ID. */
1985 if (hv_pcifront_get_vendor_id(hpdev) == 0xFFFF) {
1986 dev_err_once(&hbus->hdev->device,
1987 "the device has gone\n");
1988 goto enable_tasklet;
1992 * Make sure that the ring buffer data structure doesn't get
1993 * freed while we dereference the ring buffer pointer. Test
1994 * for the channel's onchannel_callback being NULL within a
1995 * sched_lock critical section. See also the inline comments
1996 * in vmbus_reset_channel_cb().
1998 spin_lock_irqsave(&channel->sched_lock, flags);
1999 if (unlikely(channel->onchannel_callback == NULL)) {
2000 spin_unlock_irqrestore(&channel->sched_lock, flags);
2001 goto enable_tasklet;
2003 hv_pci_onchannelcallback(hbus);
2004 spin_unlock_irqrestore(&channel->sched_lock, flags);
2009 tasklet_enable(&channel->callback_event);
2011 if (comp.comp_pkt.completion_status < 0) {
2012 dev_err(&hbus->hdev->device,
2013 "Request for interrupt failed: 0x%x",
2014 comp.comp_pkt.completion_status);
2019 * Record the assignment so that this can be unwound later. Using
2020 * irq_set_chip_data() here would be appropriate, but the lock it takes
2023 *int_desc = comp.int_desc;
2024 data->chip_data = int_desc;
2026 /* Pass up the result. */
2027 msg->address_hi = comp.int_desc.address >> 32;
2028 msg->address_lo = comp.int_desc.address & 0xffffffff;
2029 msg->data = comp.int_desc.data;
2031 put_pcichild(hpdev);
2035 tasklet_enable(&channel->callback_event);
2037 * The completion packet on the stack becomes invalid after 'return';
2038 * remove the ID from the VMbus requestor if the identifier is still
2039 * mapped to/associated with the packet. (The identifier could have
2040 * been 're-used', i.e., already removed and (re-)mapped.)
2042 * Cf. hv_pci_onchannelcallback().
2044 vmbus_request_addr_match(channel, trans_id, (unsigned long)&ctxt.pci_pkt);
2048 put_pcichild(hpdev);
2049 return_null_message:
2050 msg->address_hi = 0;
2051 msg->address_lo = 0;
2055 /* HW Interrupt Chip Descriptor */
2056 static struct irq_chip hv_msi_irq_chip = {
2057 .name = "Hyper-V PCIe MSI",
2058 .irq_compose_msi_msg = hv_compose_msi_msg,
2059 .irq_set_affinity = irq_chip_set_affinity_parent,
2061 .irq_ack = irq_chip_ack_parent,
2062 #elif defined(CONFIG_ARM64)
2063 .irq_eoi = irq_chip_eoi_parent,
2065 .irq_mask = hv_irq_mask,
2066 .irq_unmask = hv_irq_unmask,
2069 static struct msi_domain_ops hv_msi_ops = {
2070 .msi_prepare = hv_msi_prepare,
2071 .msi_free = hv_msi_free,
2075 * hv_pcie_init_irq_domain() - Initialize IRQ domain
2076 * @hbus: The root PCI bus
2078 * This function creates an IRQ domain which will be used for
2079 * interrupts from devices that have been passed through. These
2080 * devices only support MSI and MSI-X, not line-based interrupts
2081 * or simulations of line-based interrupts through PCIe's
2082 * fabric-layer messages. Because interrupts are remapped, we
2083 * can support multi-message MSI here.
2085 * Return: '0' on success and error value on failure
2087 static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus)
2089 hbus->msi_info.chip = &hv_msi_irq_chip;
2090 hbus->msi_info.ops = &hv_msi_ops;
2091 hbus->msi_info.flags = (MSI_FLAG_USE_DEF_DOM_OPS |
2092 MSI_FLAG_USE_DEF_CHIP_OPS | MSI_FLAG_MULTI_PCI_MSI |
2094 hbus->msi_info.handler = FLOW_HANDLER;
2095 hbus->msi_info.handler_name = FLOW_NAME;
2096 hbus->msi_info.data = hbus;
2097 hbus->irq_domain = pci_msi_create_irq_domain(hbus->fwnode,
2099 hv_pci_get_root_domain());
2100 if (!hbus->irq_domain) {
2101 dev_err(&hbus->hdev->device,
2102 "Failed to build an MSI IRQ domain\n");
2106 dev_set_msi_domain(&hbus->bridge->dev, hbus->irq_domain);
2112 * get_bar_size() - Get the address space consumed by a BAR
2113 * @bar_val: Value that a BAR returned after -1 was written
2116 * This function returns the size of the BAR, rounded up to 1
2117 * page. It has to be rounded up because the hypervisor's page
2118 * table entry that maps the BAR into the VM can't specify an
2119 * offset within a page. The invariant is that the hypervisor
2120 * must place any BARs of smaller than page length at the
2121 * beginning of a page.
2123 * Return: Size in bytes of the consumed MMIO space.
2125 static u64 get_bar_size(u64 bar_val)
2127 return round_up((1 + ~(bar_val & PCI_BASE_ADDRESS_MEM_MASK)),
2132 * survey_child_resources() - Total all MMIO requirements
2133 * @hbus: Root PCI bus, as understood by this driver
2135 static void survey_child_resources(struct hv_pcibus_device *hbus)
2137 struct hv_pci_dev *hpdev;
2138 resource_size_t bar_size = 0;
2139 unsigned long flags;
2140 struct completion *event;
2144 /* If nobody is waiting on the answer, don't compute it. */
2145 event = xchg(&hbus->survey_event, NULL);
2149 /* If the answer has already been computed, go with it. */
2150 if (hbus->low_mmio_space || hbus->high_mmio_space) {
2155 spin_lock_irqsave(&hbus->device_list_lock, flags);
2158 * Due to an interesting quirk of the PCI spec, all memory regions
2159 * for a child device are a power of 2 in size and aligned in memory,
2160 * so it's sufficient to just add them up without tracking alignment.
2162 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2163 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
2164 if (hpdev->probed_bar[i] & PCI_BASE_ADDRESS_SPACE_IO)
2165 dev_err(&hbus->hdev->device,
2166 "There's an I/O BAR in this list!\n");
2168 if (hpdev->probed_bar[i] != 0) {
2170 * A probed BAR has all the upper bits set that
2174 bar_val = hpdev->probed_bar[i];
2175 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
2177 ((u64)hpdev->probed_bar[++i] << 32);
2179 bar_val |= 0xffffffff00000000ULL;
2181 bar_size = get_bar_size(bar_val);
2183 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
2184 hbus->high_mmio_space += bar_size;
2186 hbus->low_mmio_space += bar_size;
2191 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2196 * prepopulate_bars() - Fill in BARs with defaults
2197 * @hbus: Root PCI bus, as understood by this driver
2199 * The core PCI driver code seems much, much happier if the BARs
2200 * for a device have values upon first scan. So fill them in.
2201 * The algorithm below works down from large sizes to small,
2202 * attempting to pack the assignments optimally. The assumption,
2203 * enforced in other parts of the code, is that the beginning of
2204 * the memory-mapped I/O space will be aligned on the largest
2207 static void prepopulate_bars(struct hv_pcibus_device *hbus)
2209 resource_size_t high_size = 0;
2210 resource_size_t low_size = 0;
2211 resource_size_t high_base = 0;
2212 resource_size_t low_base = 0;
2213 resource_size_t bar_size;
2214 struct hv_pci_dev *hpdev;
2215 unsigned long flags;
2221 if (hbus->low_mmio_space) {
2222 low_size = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
2223 low_base = hbus->low_mmio_res->start;
2226 if (hbus->high_mmio_space) {
2228 (63 - __builtin_clzll(hbus->high_mmio_space));
2229 high_base = hbus->high_mmio_res->start;
2232 spin_lock_irqsave(&hbus->device_list_lock, flags);
2235 * Clear the memory enable bit, in case it's already set. This occurs
2236 * in the suspend path of hibernation, where the device is suspended,
2237 * resumed and suspended again: see hibernation_snapshot() and
2238 * hibernation_platform_enter().
2240 * If the memory enable bit is already set, Hyper-V silently ignores
2241 * the below BAR updates, and the related PCI device driver can not
2242 * work, because reading from the device register(s) always returns
2243 * 0xFFFFFFFF (PCI_ERROR_RESPONSE).
2245 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2246 _hv_pcifront_read_config(hpdev, PCI_COMMAND, 2, &command);
2247 command &= ~PCI_COMMAND_MEMORY;
2248 _hv_pcifront_write_config(hpdev, PCI_COMMAND, 2, command);
2251 /* Pick addresses for the BARs. */
2253 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2254 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
2255 bar_val = hpdev->probed_bar[i];
2258 high = bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64;
2261 ((u64)hpdev->probed_bar[i + 1]
2264 bar_val |= 0xffffffffULL << 32;
2266 bar_size = get_bar_size(bar_val);
2268 if (high_size != bar_size) {
2272 _hv_pcifront_write_config(hpdev,
2273 PCI_BASE_ADDRESS_0 + (4 * i),
2275 (u32)(high_base & 0xffffff00));
2277 _hv_pcifront_write_config(hpdev,
2278 PCI_BASE_ADDRESS_0 + (4 * i),
2279 4, (u32)(high_base >> 32));
2280 high_base += bar_size;
2282 if (low_size != bar_size)
2284 _hv_pcifront_write_config(hpdev,
2285 PCI_BASE_ADDRESS_0 + (4 * i),
2287 (u32)(low_base & 0xffffff00));
2288 low_base += bar_size;
2291 if (high_size <= 1 && low_size <= 1) {
2293 * No need to set the PCI_COMMAND_MEMORY bit as
2294 * the core PCI driver doesn't require the bit
2295 * to be pre-set. Actually here we intentionally
2296 * keep the bit off so that the PCI BAR probing
2297 * in the core PCI driver doesn't cause Hyper-V
2298 * to unnecessarily unmap/map the virtual BARs
2299 * from/to the physical BARs multiple times.
2300 * This reduces the VM boot time significantly
2301 * if the BAR sizes are huge.
2309 } while (high_size || low_size);
2311 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2315 * Assign entries in sysfs pci slot directory.
2317 * Note that this function does not need to lock the children list
2318 * because it is called from pci_devices_present_work which
2319 * is serialized with hv_eject_device_work because they are on the
2320 * same ordered workqueue. Therefore hbus->children list will not change
2321 * even when pci_create_slot sleeps.
2323 static void hv_pci_assign_slots(struct hv_pcibus_device *hbus)
2325 struct hv_pci_dev *hpdev;
2326 char name[SLOT_NAME_SIZE];
2329 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2330 if (hpdev->pci_slot)
2333 slot_nr = PCI_SLOT(wslot_to_devfn(hpdev->desc.win_slot.slot));
2334 snprintf(name, SLOT_NAME_SIZE, "%u", hpdev->desc.ser);
2335 hpdev->pci_slot = pci_create_slot(hbus->bridge->bus, slot_nr,
2337 if (IS_ERR(hpdev->pci_slot)) {
2338 pr_warn("pci_create slot %s failed\n", name);
2339 hpdev->pci_slot = NULL;
2345 * Remove entries in sysfs pci slot directory.
2347 static void hv_pci_remove_slots(struct hv_pcibus_device *hbus)
2349 struct hv_pci_dev *hpdev;
2351 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2352 if (!hpdev->pci_slot)
2354 pci_destroy_slot(hpdev->pci_slot);
2355 hpdev->pci_slot = NULL;
2360 * Set NUMA node for the devices on the bus
2362 static void hv_pci_assign_numa_node(struct hv_pcibus_device *hbus)
2364 struct pci_dev *dev;
2365 struct pci_bus *bus = hbus->bridge->bus;
2366 struct hv_pci_dev *hv_dev;
2368 list_for_each_entry(dev, &bus->devices, bus_list) {
2369 hv_dev = get_pcichild_wslot(hbus, devfn_to_wslot(dev->devfn));
2373 if (hv_dev->desc.flags & HV_PCI_DEVICE_FLAG_NUMA_AFFINITY &&
2374 hv_dev->desc.virtual_numa_node < num_possible_nodes())
2376 * The kernel may boot with some NUMA nodes offline
2377 * (e.g. in a KDUMP kernel) or with NUMA disabled via
2378 * "numa=off". In those cases, adjust the host provided
2379 * NUMA node to a valid NUMA node used by the kernel.
2381 set_dev_node(&dev->dev,
2382 numa_map_to_online_node(
2383 hv_dev->desc.virtual_numa_node));
2385 put_pcichild(hv_dev);
2390 * create_root_hv_pci_bus() - Expose a new root PCI bus
2391 * @hbus: Root PCI bus, as understood by this driver
2393 * Return: 0 on success, -errno on failure
2395 static int create_root_hv_pci_bus(struct hv_pcibus_device *hbus)
2398 struct pci_host_bridge *bridge = hbus->bridge;
2400 bridge->dev.parent = &hbus->hdev->device;
2401 bridge->sysdata = &hbus->sysdata;
2402 bridge->ops = &hv_pcifront_ops;
2404 error = pci_scan_root_bus_bridge(bridge);
2408 pci_lock_rescan_remove();
2409 hv_pci_assign_numa_node(hbus);
2410 pci_bus_assign_resources(bridge->bus);
2411 hv_pci_assign_slots(hbus);
2412 pci_bus_add_devices(bridge->bus);
2413 pci_unlock_rescan_remove();
2414 hbus->state = hv_pcibus_installed;
2418 struct q_res_req_compl {
2419 struct completion host_event;
2420 struct hv_pci_dev *hpdev;
2424 * q_resource_requirements() - Query Resource Requirements
2425 * @context: The completion context.
2426 * @resp: The response that came from the host.
2427 * @resp_packet_size: The size in bytes of resp.
2429 * This function is invoked on completion of a Query Resource
2430 * Requirements packet.
2432 static void q_resource_requirements(void *context, struct pci_response *resp,
2433 int resp_packet_size)
2435 struct q_res_req_compl *completion = context;
2436 struct pci_q_res_req_response *q_res_req =
2437 (struct pci_q_res_req_response *)resp;
2441 status = (resp_packet_size < sizeof(*q_res_req)) ? -1 : resp->status;
2443 dev_err(&completion->hpdev->hbus->hdev->device,
2444 "query resource requirements failed: %x\n",
2447 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
2448 completion->hpdev->probed_bar[i] =
2449 q_res_req->probed_bar[i];
2453 complete(&completion->host_event);
2457 * new_pcichild_device() - Create a new child device
2458 * @hbus: The internal struct tracking this root PCI bus.
2459 * @desc: The information supplied so far from the host
2462 * This function creates the tracking structure for a new child
2463 * device and kicks off the process of figuring out what it is.
2465 * Return: Pointer to the new tracking struct
2467 static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
2468 struct hv_pcidev_description *desc)
2470 struct hv_pci_dev *hpdev;
2471 struct pci_child_message *res_req;
2472 struct q_res_req_compl comp_pkt;
2474 struct pci_packet init_packet;
2475 u8 buffer[sizeof(struct pci_child_message)];
2477 unsigned long flags;
2480 hpdev = kzalloc(sizeof(*hpdev), GFP_KERNEL);
2486 memset(&pkt, 0, sizeof(pkt));
2487 init_completion(&comp_pkt.host_event);
2488 comp_pkt.hpdev = hpdev;
2489 pkt.init_packet.compl_ctxt = &comp_pkt;
2490 pkt.init_packet.completion_func = q_resource_requirements;
2491 res_req = (struct pci_child_message *)&pkt.init_packet.message;
2492 res_req->message_type.type = PCI_QUERY_RESOURCE_REQUIREMENTS;
2493 res_req->wslot.slot = desc->win_slot.slot;
2495 ret = vmbus_sendpacket(hbus->hdev->channel, res_req,
2496 sizeof(struct pci_child_message),
2497 (unsigned long)&pkt.init_packet,
2499 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2503 if (wait_for_response(hbus->hdev, &comp_pkt.host_event))
2506 hpdev->desc = *desc;
2507 refcount_set(&hpdev->refs, 1);
2508 get_pcichild(hpdev);
2509 spin_lock_irqsave(&hbus->device_list_lock, flags);
2511 list_add_tail(&hpdev->list_entry, &hbus->children);
2512 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2521 * get_pcichild_wslot() - Find device from slot
2522 * @hbus: Root PCI bus, as understood by this driver
2523 * @wslot: Location on the bus
2525 * This function looks up a PCI device and returns the internal
2526 * representation of it. It acquires a reference on it, so that
2527 * the device won't be deleted while somebody is using it. The
2528 * caller is responsible for calling put_pcichild() to release
2531 * Return: Internal representation of a PCI device
2533 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
2536 unsigned long flags;
2537 struct hv_pci_dev *iter, *hpdev = NULL;
2539 spin_lock_irqsave(&hbus->device_list_lock, flags);
2540 list_for_each_entry(iter, &hbus->children, list_entry) {
2541 if (iter->desc.win_slot.slot == wslot) {
2543 get_pcichild(hpdev);
2547 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2553 * pci_devices_present_work() - Handle new list of child devices
2554 * @work: Work struct embedded in struct hv_dr_work
2556 * "Bus Relations" is the Windows term for "children of this
2557 * bus." The terminology is preserved here for people trying to
2558 * debug the interaction between Hyper-V and Linux. This
2559 * function is called when the parent partition reports a list
2560 * of functions that should be observed under this PCI Express
2563 * This function updates the list, and must tolerate being
2564 * called multiple times with the same information. The typical
2565 * number of child devices is one, with very atypical cases
2566 * involving three or four, so the algorithms used here can be
2567 * simple and inefficient.
2569 * It must also treat the omission of a previously observed device as
2570 * notification that the device no longer exists.
2572 * Note that this function is serialized with hv_eject_device_work(),
2573 * because both are pushed to the ordered workqueue hbus->wq.
2575 static void pci_devices_present_work(struct work_struct *work)
2579 struct hv_pcidev_description *new_desc;
2580 struct hv_pci_dev *hpdev;
2581 struct hv_pcibus_device *hbus;
2582 struct list_head removed;
2583 struct hv_dr_work *dr_wrk;
2584 struct hv_dr_state *dr = NULL;
2585 unsigned long flags;
2587 dr_wrk = container_of(work, struct hv_dr_work, wrk);
2591 INIT_LIST_HEAD(&removed);
2593 /* Pull this off the queue and process it if it was the last one. */
2594 spin_lock_irqsave(&hbus->device_list_lock, flags);
2595 while (!list_empty(&hbus->dr_list)) {
2596 dr = list_first_entry(&hbus->dr_list, struct hv_dr_state,
2598 list_del(&dr->list_entry);
2600 /* Throw this away if the list still has stuff in it. */
2601 if (!list_empty(&hbus->dr_list)) {
2606 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2611 mutex_lock(&hbus->state_lock);
2613 /* First, mark all existing children as reported missing. */
2614 spin_lock_irqsave(&hbus->device_list_lock, flags);
2615 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2616 hpdev->reported_missing = true;
2618 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2620 /* Next, add back any reported devices. */
2621 for (child_no = 0; child_no < dr->device_count; child_no++) {
2623 new_desc = &dr->func[child_no];
2625 spin_lock_irqsave(&hbus->device_list_lock, flags);
2626 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2627 if ((hpdev->desc.win_slot.slot == new_desc->win_slot.slot) &&
2628 (hpdev->desc.v_id == new_desc->v_id) &&
2629 (hpdev->desc.d_id == new_desc->d_id) &&
2630 (hpdev->desc.ser == new_desc->ser)) {
2631 hpdev->reported_missing = false;
2635 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2638 hpdev = new_pcichild_device(hbus, new_desc);
2640 dev_err(&hbus->hdev->device,
2641 "couldn't record a child device.\n");
2645 /* Move missing children to a list on the stack. */
2646 spin_lock_irqsave(&hbus->device_list_lock, flags);
2649 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2650 if (hpdev->reported_missing) {
2652 put_pcichild(hpdev);
2653 list_move_tail(&hpdev->list_entry, &removed);
2658 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2660 /* Delete everything that should no longer exist. */
2661 while (!list_empty(&removed)) {
2662 hpdev = list_first_entry(&removed, struct hv_pci_dev,
2664 list_del(&hpdev->list_entry);
2666 if (hpdev->pci_slot)
2667 pci_destroy_slot(hpdev->pci_slot);
2669 put_pcichild(hpdev);
2672 switch (hbus->state) {
2673 case hv_pcibus_installed:
2675 * Tell the core to rescan bus
2676 * because there may have been changes.
2678 pci_lock_rescan_remove();
2679 pci_scan_child_bus(hbus->bridge->bus);
2680 hv_pci_assign_numa_node(hbus);
2681 hv_pci_assign_slots(hbus);
2682 pci_unlock_rescan_remove();
2685 case hv_pcibus_init:
2686 case hv_pcibus_probed:
2687 survey_child_resources(hbus);
2694 mutex_unlock(&hbus->state_lock);
2700 * hv_pci_start_relations_work() - Queue work to start device discovery
2701 * @hbus: Root PCI bus, as understood by this driver
2702 * @dr: The list of children returned from host
2704 * Return: 0 on success, -errno on failure
2706 static int hv_pci_start_relations_work(struct hv_pcibus_device *hbus,
2707 struct hv_dr_state *dr)
2709 struct hv_dr_work *dr_wrk;
2710 unsigned long flags;
2713 if (hbus->state == hv_pcibus_removing) {
2714 dev_info(&hbus->hdev->device,
2715 "PCI VMBus BUS_RELATIONS: ignored\n");
2719 dr_wrk = kzalloc(sizeof(*dr_wrk), GFP_NOWAIT);
2723 INIT_WORK(&dr_wrk->wrk, pci_devices_present_work);
2726 spin_lock_irqsave(&hbus->device_list_lock, flags);
2728 * If pending_dr is true, we have already queued a work,
2729 * which will see the new dr. Otherwise, we need to
2732 pending_dr = !list_empty(&hbus->dr_list);
2733 list_add_tail(&dr->list_entry, &hbus->dr_list);
2734 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2739 queue_work(hbus->wq, &dr_wrk->wrk);
2745 * hv_pci_devices_present() - Handle list of new children
2746 * @hbus: Root PCI bus, as understood by this driver
2747 * @relations: Packet from host listing children
2749 * Process a new list of devices on the bus. The list of devices is
2750 * discovered by VSP and sent to us via VSP message PCI_BUS_RELATIONS,
2751 * whenever a new list of devices for this bus appears.
2753 static void hv_pci_devices_present(struct hv_pcibus_device *hbus,
2754 struct pci_bus_relations *relations)
2756 struct hv_dr_state *dr;
2759 dr = kzalloc(struct_size(dr, func, relations->device_count),
2764 dr->device_count = relations->device_count;
2765 for (i = 0; i < dr->device_count; i++) {
2766 dr->func[i].v_id = relations->func[i].v_id;
2767 dr->func[i].d_id = relations->func[i].d_id;
2768 dr->func[i].rev = relations->func[i].rev;
2769 dr->func[i].prog_intf = relations->func[i].prog_intf;
2770 dr->func[i].subclass = relations->func[i].subclass;
2771 dr->func[i].base_class = relations->func[i].base_class;
2772 dr->func[i].subsystem_id = relations->func[i].subsystem_id;
2773 dr->func[i].win_slot = relations->func[i].win_slot;
2774 dr->func[i].ser = relations->func[i].ser;
2777 if (hv_pci_start_relations_work(hbus, dr))
2782 * hv_pci_devices_present2() - Handle list of new children
2783 * @hbus: Root PCI bus, as understood by this driver
2784 * @relations: Packet from host listing children
2786 * This function is the v2 version of hv_pci_devices_present()
2788 static void hv_pci_devices_present2(struct hv_pcibus_device *hbus,
2789 struct pci_bus_relations2 *relations)
2791 struct hv_dr_state *dr;
2794 dr = kzalloc(struct_size(dr, func, relations->device_count),
2799 dr->device_count = relations->device_count;
2800 for (i = 0; i < dr->device_count; i++) {
2801 dr->func[i].v_id = relations->func[i].v_id;
2802 dr->func[i].d_id = relations->func[i].d_id;
2803 dr->func[i].rev = relations->func[i].rev;
2804 dr->func[i].prog_intf = relations->func[i].prog_intf;
2805 dr->func[i].subclass = relations->func[i].subclass;
2806 dr->func[i].base_class = relations->func[i].base_class;
2807 dr->func[i].subsystem_id = relations->func[i].subsystem_id;
2808 dr->func[i].win_slot = relations->func[i].win_slot;
2809 dr->func[i].ser = relations->func[i].ser;
2810 dr->func[i].flags = relations->func[i].flags;
2811 dr->func[i].virtual_numa_node =
2812 relations->func[i].virtual_numa_node;
2815 if (hv_pci_start_relations_work(hbus, dr))
2820 * hv_eject_device_work() - Asynchronously handles ejection
2821 * @work: Work struct embedded in internal device struct
2823 * This function handles ejecting a device. Windows will
2824 * attempt to gracefully eject a device, waiting 60 seconds to
2825 * hear back from the guest OS that this completed successfully.
2826 * If this timer expires, the device will be forcibly removed.
2828 static void hv_eject_device_work(struct work_struct *work)
2830 struct pci_eject_response *ejct_pkt;
2831 struct hv_pcibus_device *hbus;
2832 struct hv_pci_dev *hpdev;
2833 struct pci_dev *pdev;
2834 unsigned long flags;
2837 struct pci_packet pkt;
2838 u8 buffer[sizeof(struct pci_eject_response)];
2841 hpdev = container_of(work, struct hv_pci_dev, wrk);
2844 mutex_lock(&hbus->state_lock);
2847 * Ejection can come before or after the PCI bus has been set up, so
2848 * attempt to find it and tear down the bus state, if it exists. This
2849 * must be done without constructs like pci_domain_nr(hbus->bridge->bus)
2850 * because hbus->bridge->bus may not exist yet.
2852 wslot = wslot_to_devfn(hpdev->desc.win_slot.slot);
2853 pdev = pci_get_domain_bus_and_slot(hbus->bridge->domain_nr, 0, wslot);
2855 pci_lock_rescan_remove();
2856 pci_stop_and_remove_bus_device(pdev);
2858 pci_unlock_rescan_remove();
2861 spin_lock_irqsave(&hbus->device_list_lock, flags);
2862 list_del(&hpdev->list_entry);
2863 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2865 if (hpdev->pci_slot)
2866 pci_destroy_slot(hpdev->pci_slot);
2868 memset(&ctxt, 0, sizeof(ctxt));
2869 ejct_pkt = (struct pci_eject_response *)&ctxt.pkt.message;
2870 ejct_pkt->message_type.type = PCI_EJECTION_COMPLETE;
2871 ejct_pkt->wslot.slot = hpdev->desc.win_slot.slot;
2872 vmbus_sendpacket(hbus->hdev->channel, ejct_pkt,
2873 sizeof(*ejct_pkt), 0,
2874 VM_PKT_DATA_INBAND, 0);
2876 /* For the get_pcichild() in hv_pci_eject_device() */
2877 put_pcichild(hpdev);
2878 /* For the two refs got in new_pcichild_device() */
2879 put_pcichild(hpdev);
2880 put_pcichild(hpdev);
2881 /* hpdev has been freed. Do not use it any more. */
2883 mutex_unlock(&hbus->state_lock);
2887 * hv_pci_eject_device() - Handles device ejection
2888 * @hpdev: Internal device tracking struct
2890 * This function is invoked when an ejection packet arrives. It
2891 * just schedules work so that we don't re-enter the packet
2892 * delivery code handling the ejection.
2894 static void hv_pci_eject_device(struct hv_pci_dev *hpdev)
2896 struct hv_pcibus_device *hbus = hpdev->hbus;
2897 struct hv_device *hdev = hbus->hdev;
2899 if (hbus->state == hv_pcibus_removing) {
2900 dev_info(&hdev->device, "PCI VMBus EJECT: ignored\n");
2904 get_pcichild(hpdev);
2905 INIT_WORK(&hpdev->wrk, hv_eject_device_work);
2906 queue_work(hbus->wq, &hpdev->wrk);
2910 * hv_pci_onchannelcallback() - Handles incoming packets
2911 * @context: Internal bus tracking struct
2913 * This function is invoked whenever the host sends a packet to
2914 * this channel (which is private to this root PCI bus).
2916 static void hv_pci_onchannelcallback(void *context)
2918 const int packet_size = 0x100;
2920 struct hv_pcibus_device *hbus = context;
2921 struct vmbus_channel *chan = hbus->hdev->channel;
2923 u64 req_id, req_addr;
2924 struct vmpacket_descriptor *desc;
2925 unsigned char *buffer;
2926 int bufferlen = packet_size;
2927 struct pci_packet *comp_packet;
2928 struct pci_response *response;
2929 struct pci_incoming_message *new_message;
2930 struct pci_bus_relations *bus_rel;
2931 struct pci_bus_relations2 *bus_rel2;
2932 struct pci_dev_inval_block *inval;
2933 struct pci_dev_incoming *dev_message;
2934 struct hv_pci_dev *hpdev;
2935 unsigned long flags;
2937 buffer = kmalloc(bufferlen, GFP_ATOMIC);
2942 ret = vmbus_recvpacket_raw(chan, buffer, bufferlen,
2943 &bytes_recvd, &req_id);
2945 if (ret == -ENOBUFS) {
2947 /* Handle large packet */
2948 bufferlen = bytes_recvd;
2949 buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
2955 /* Zero length indicates there are no more packets. */
2956 if (ret || !bytes_recvd)
2960 * All incoming packets must be at least as large as a
2963 if (bytes_recvd <= sizeof(struct pci_response))
2965 desc = (struct vmpacket_descriptor *)buffer;
2967 switch (desc->type) {
2970 lock_requestor(chan, flags);
2971 req_addr = __vmbus_request_addr_match(chan, req_id,
2972 VMBUS_RQST_ADDR_ANY);
2973 if (req_addr == VMBUS_RQST_ERROR) {
2974 unlock_requestor(chan, flags);
2975 dev_err(&hbus->hdev->device,
2976 "Invalid transaction ID %llx\n",
2980 comp_packet = (struct pci_packet *)req_addr;
2981 response = (struct pci_response *)buffer;
2983 * Call ->completion_func() within the critical section to make
2984 * sure that the packet pointer is still valid during the call:
2985 * here 'valid' means that there's a task still waiting for the
2986 * completion, and that the packet data is still on the waiting
2987 * task's stack. Cf. hv_compose_msi_msg().
2989 comp_packet->completion_func(comp_packet->compl_ctxt,
2992 unlock_requestor(chan, flags);
2995 case VM_PKT_DATA_INBAND:
2997 new_message = (struct pci_incoming_message *)buffer;
2998 switch (new_message->message_type.type) {
2999 case PCI_BUS_RELATIONS:
3001 bus_rel = (struct pci_bus_relations *)buffer;
3002 if (bytes_recvd < sizeof(*bus_rel) ||
3004 struct_size(bus_rel, func,
3005 bus_rel->device_count)) {
3006 dev_err(&hbus->hdev->device,
3007 "bus relations too small\n");
3011 hv_pci_devices_present(hbus, bus_rel);
3014 case PCI_BUS_RELATIONS2:
3016 bus_rel2 = (struct pci_bus_relations2 *)buffer;
3017 if (bytes_recvd < sizeof(*bus_rel2) ||
3019 struct_size(bus_rel2, func,
3020 bus_rel2->device_count)) {
3021 dev_err(&hbus->hdev->device,
3022 "bus relations v2 too small\n");
3026 hv_pci_devices_present2(hbus, bus_rel2);
3031 dev_message = (struct pci_dev_incoming *)buffer;
3032 if (bytes_recvd < sizeof(*dev_message)) {
3033 dev_err(&hbus->hdev->device,
3034 "eject message too small\n");
3037 hpdev = get_pcichild_wslot(hbus,
3038 dev_message->wslot.slot);
3040 hv_pci_eject_device(hpdev);
3041 put_pcichild(hpdev);
3045 case PCI_INVALIDATE_BLOCK:
3047 inval = (struct pci_dev_inval_block *)buffer;
3048 if (bytes_recvd < sizeof(*inval)) {
3049 dev_err(&hbus->hdev->device,
3050 "invalidate message too small\n");
3053 hpdev = get_pcichild_wslot(hbus,
3056 if (hpdev->block_invalidate) {
3057 hpdev->block_invalidate(
3058 hpdev->invalidate_context,
3061 put_pcichild(hpdev);
3066 dev_warn(&hbus->hdev->device,
3067 "Unimplemented protocol message %x\n",
3068 new_message->message_type.type);
3074 dev_err(&hbus->hdev->device,
3075 "unhandled packet type %d, tid %llx len %d\n",
3076 desc->type, req_id, bytes_recvd);
3085 * hv_pci_protocol_negotiation() - Set up protocol
3086 * @hdev: VMBus's tracking struct for this root PCI bus.
3087 * @version: Array of supported channel protocol versions in
3088 * the order of probing - highest go first.
3089 * @num_version: Number of elements in the version array.
3091 * This driver is intended to support running on Windows 10
3092 * (server) and later versions. It will not run on earlier
3093 * versions, as they assume that many of the operations which
3094 * Linux needs accomplished with a spinlock held were done via
3095 * asynchronous messaging via VMBus. Windows 10 increases the
3096 * surface area of PCI emulation so that these actions can take
3097 * place by suspending a virtual processor for their duration.
3099 * This function negotiates the channel protocol version,
3100 * failing if the host doesn't support the necessary protocol
3103 static int hv_pci_protocol_negotiation(struct hv_device *hdev,
3104 enum pci_protocol_version_t version[],
3107 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3108 struct pci_version_request *version_req;
3109 struct hv_pci_compl comp_pkt;
3110 struct pci_packet *pkt;
3115 * Initiate the handshake with the host and negotiate
3116 * a version that the host can support. We start with the
3117 * highest version number and go down if the host cannot
3120 pkt = kzalloc(sizeof(*pkt) + sizeof(*version_req), GFP_KERNEL);
3124 init_completion(&comp_pkt.host_event);
3125 pkt->completion_func = hv_pci_generic_compl;
3126 pkt->compl_ctxt = &comp_pkt;
3127 version_req = (struct pci_version_request *)&pkt->message;
3128 version_req->message_type.type = PCI_QUERY_PROTOCOL_VERSION;
3130 for (i = 0; i < num_version; i++) {
3131 version_req->protocol_version = version[i];
3132 ret = vmbus_sendpacket(hdev->channel, version_req,
3133 sizeof(struct pci_version_request),
3134 (unsigned long)pkt, VM_PKT_DATA_INBAND,
3135 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3137 ret = wait_for_response(hdev, &comp_pkt.host_event);
3140 dev_err(&hdev->device,
3141 "PCI Pass-through VSP failed to request version: %d",
3146 if (comp_pkt.completion_status >= 0) {
3147 hbus->protocol_version = version[i];
3148 dev_info(&hdev->device,
3149 "PCI VMBus probing: Using version %#x\n",
3150 hbus->protocol_version);
3154 if (comp_pkt.completion_status != STATUS_REVISION_MISMATCH) {
3155 dev_err(&hdev->device,
3156 "PCI Pass-through VSP failed version request: %#x",
3157 comp_pkt.completion_status);
3162 reinit_completion(&comp_pkt.host_event);
3165 dev_err(&hdev->device,
3166 "PCI pass-through VSP failed to find supported version");
3175 * hv_pci_free_bridge_windows() - Release memory regions for the
3177 * @hbus: Root PCI bus, as understood by this driver
3179 static void hv_pci_free_bridge_windows(struct hv_pcibus_device *hbus)
3182 * Set the resources back to the way they looked when they
3183 * were allocated by setting IORESOURCE_BUSY again.
3186 if (hbus->low_mmio_space && hbus->low_mmio_res) {
3187 hbus->low_mmio_res->flags |= IORESOURCE_BUSY;
3188 vmbus_free_mmio(hbus->low_mmio_res->start,
3189 resource_size(hbus->low_mmio_res));
3192 if (hbus->high_mmio_space && hbus->high_mmio_res) {
3193 hbus->high_mmio_res->flags |= IORESOURCE_BUSY;
3194 vmbus_free_mmio(hbus->high_mmio_res->start,
3195 resource_size(hbus->high_mmio_res));
3200 * hv_pci_allocate_bridge_windows() - Allocate memory regions
3202 * @hbus: Root PCI bus, as understood by this driver
3204 * This function calls vmbus_allocate_mmio(), which is itself a
3205 * bit of a compromise. Ideally, we might change the pnp layer
3206 * in the kernel such that it comprehends either PCI devices
3207 * which are "grandchildren of ACPI," with some intermediate bus
3208 * node (in this case, VMBus) or change it such that it
3209 * understands VMBus. The pnp layer, however, has been declared
3210 * deprecated, and not subject to change.
3212 * The workaround, implemented here, is to ask VMBus to allocate
3213 * MMIO space for this bus. VMBus itself knows which ranges are
3214 * appropriate by looking at its own ACPI objects. Then, after
3215 * these ranges are claimed, they're modified to look like they
3216 * would have looked if the ACPI and pnp code had allocated
3217 * bridge windows. These descriptors have to exist in this form
3218 * in order to satisfy the code which will get invoked when the
3219 * endpoint PCI function driver calls request_mem_region() or
3220 * request_mem_region_exclusive().
3222 * Return: 0 on success, -errno on failure
3224 static int hv_pci_allocate_bridge_windows(struct hv_pcibus_device *hbus)
3226 resource_size_t align;
3229 if (hbus->low_mmio_space) {
3230 align = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
3231 ret = vmbus_allocate_mmio(&hbus->low_mmio_res, hbus->hdev, 0,
3232 (u64)(u32)0xffffffff,
3233 hbus->low_mmio_space,
3236 dev_err(&hbus->hdev->device,
3237 "Need %#llx of low MMIO space. Consider reconfiguring the VM.\n",
3238 hbus->low_mmio_space);
3242 /* Modify this resource to become a bridge window. */
3243 hbus->low_mmio_res->flags |= IORESOURCE_WINDOW;
3244 hbus->low_mmio_res->flags &= ~IORESOURCE_BUSY;
3245 pci_add_resource(&hbus->bridge->windows, hbus->low_mmio_res);
3248 if (hbus->high_mmio_space) {
3249 align = 1ULL << (63 - __builtin_clzll(hbus->high_mmio_space));
3250 ret = vmbus_allocate_mmio(&hbus->high_mmio_res, hbus->hdev,
3252 hbus->high_mmio_space, align,
3255 dev_err(&hbus->hdev->device,
3256 "Need %#llx of high MMIO space. Consider reconfiguring the VM.\n",
3257 hbus->high_mmio_space);
3258 goto release_low_mmio;
3261 /* Modify this resource to become a bridge window. */
3262 hbus->high_mmio_res->flags |= IORESOURCE_WINDOW;
3263 hbus->high_mmio_res->flags &= ~IORESOURCE_BUSY;
3264 pci_add_resource(&hbus->bridge->windows, hbus->high_mmio_res);
3270 if (hbus->low_mmio_res) {
3271 vmbus_free_mmio(hbus->low_mmio_res->start,
3272 resource_size(hbus->low_mmio_res));
3279 * hv_allocate_config_window() - Find MMIO space for PCI Config
3280 * @hbus: Root PCI bus, as understood by this driver
3282 * This function claims memory-mapped I/O space for accessing
3283 * configuration space for the functions on this bus.
3285 * Return: 0 on success, -errno on failure
3287 static int hv_allocate_config_window(struct hv_pcibus_device *hbus)
3292 * Set up a region of MMIO space to use for accessing configuration
3295 ret = vmbus_allocate_mmio(&hbus->mem_config, hbus->hdev, 0, -1,
3296 PCI_CONFIG_MMIO_LENGTH, 0x1000, false);
3301 * vmbus_allocate_mmio() gets used for allocating both device endpoint
3302 * resource claims (those which cannot be overlapped) and the ranges
3303 * which are valid for the children of this bus, which are intended
3304 * to be overlapped by those children. Set the flag on this claim
3305 * meaning that this region can't be overlapped.
3308 hbus->mem_config->flags |= IORESOURCE_BUSY;
3313 static void hv_free_config_window(struct hv_pcibus_device *hbus)
3315 vmbus_free_mmio(hbus->mem_config->start, PCI_CONFIG_MMIO_LENGTH);
3318 static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs);
3321 * hv_pci_enter_d0() - Bring the "bus" into the D0 power state
3322 * @hdev: VMBus's tracking struct for this root PCI bus
3324 * Return: 0 on success, -errno on failure
3326 static int hv_pci_enter_d0(struct hv_device *hdev)
3328 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3329 struct pci_bus_d0_entry *d0_entry;
3330 struct hv_pci_compl comp_pkt;
3331 struct pci_packet *pkt;
3337 * Tell the host that the bus is ready to use, and moved into the
3338 * powered-on state. This includes telling the host which region
3339 * of memory-mapped I/O space has been chosen for configuration space
3342 pkt = kzalloc(sizeof(*pkt) + sizeof(*d0_entry), GFP_KERNEL);
3346 init_completion(&comp_pkt.host_event);
3347 pkt->completion_func = hv_pci_generic_compl;
3348 pkt->compl_ctxt = &comp_pkt;
3349 d0_entry = (struct pci_bus_d0_entry *)&pkt->message;
3350 d0_entry->message_type.type = PCI_BUS_D0ENTRY;
3351 d0_entry->mmio_base = hbus->mem_config->start;
3353 ret = vmbus_sendpacket(hdev->channel, d0_entry, sizeof(*d0_entry),
3354 (unsigned long)pkt, VM_PKT_DATA_INBAND,
3355 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3357 ret = wait_for_response(hdev, &comp_pkt.host_event);
3363 * In certain case (Kdump) the pci device of interest was
3364 * not cleanly shut down and resource is still held on host
3365 * side, the host could return invalid device status.
3366 * We need to explicitly request host to release the resource
3367 * and try to enter D0 again.
3369 if (comp_pkt.completion_status < 0 && retry) {
3372 dev_err(&hdev->device, "Retrying D0 Entry\n");
3375 * Hv_pci_bus_exit() calls hv_send_resource_released()
3376 * to free up resources of its child devices.
3377 * In the kdump kernel we need to set the
3378 * wslot_res_allocated to 255 so it scans all child
3379 * devices to release resources allocated in the
3380 * normal kernel before panic happened.
3382 hbus->wslot_res_allocated = 255;
3384 ret = hv_pci_bus_exit(hdev, true);
3388 goto enter_d0_retry;
3390 dev_err(&hdev->device,
3391 "Retrying D0 failed with ret %d\n", ret);
3394 if (comp_pkt.completion_status < 0) {
3395 dev_err(&hdev->device,
3396 "PCI Pass-through VSP failed D0 Entry with status %x\n",
3397 comp_pkt.completion_status);
3410 * hv_pci_query_relations() - Ask host to send list of child
3412 * @hdev: VMBus's tracking struct for this root PCI bus
3414 * Return: 0 on success, -errno on failure
3416 static int hv_pci_query_relations(struct hv_device *hdev)
3418 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3419 struct pci_message message;
3420 struct completion comp;
3423 /* Ask the host to send along the list of child devices */
3424 init_completion(&comp);
3425 if (cmpxchg(&hbus->survey_event, NULL, &comp))
3428 memset(&message, 0, sizeof(message));
3429 message.type = PCI_QUERY_BUS_RELATIONS;
3431 ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
3432 0, VM_PKT_DATA_INBAND, 0);
3434 ret = wait_for_response(hdev, &comp);
3437 * In the case of fast device addition/removal, it's possible that
3438 * vmbus_sendpacket() or wait_for_response() returns -ENODEV but we
3439 * already got a PCI_BUS_RELATIONS* message from the host and the
3440 * channel callback already scheduled a work to hbus->wq, which can be
3441 * running pci_devices_present_work() -> survey_child_resources() ->
3442 * complete(&hbus->survey_event), even after hv_pci_query_relations()
3443 * exits and the stack variable 'comp' is no longer valid; as a result,
3444 * a hang or a page fault may happen when the complete() calls
3445 * raw_spin_lock_irqsave(). Flush hbus->wq before we exit from
3446 * hv_pci_query_relations() to avoid the issues. Note: if 'ret' is
3447 * -ENODEV, there can't be any more work item scheduled to hbus->wq
3448 * after the flush_workqueue(): see vmbus_onoffer_rescind() ->
3449 * vmbus_reset_channel_cb(), vmbus_rescind_cleanup() ->
3450 * channel->rescind = true.
3452 flush_workqueue(hbus->wq);
3458 * hv_send_resources_allocated() - Report local resource choices
3459 * @hdev: VMBus's tracking struct for this root PCI bus
3461 * The host OS is expecting to be sent a request as a message
3462 * which contains all the resources that the device will use.
3463 * The response contains those same resources, "translated"
3464 * which is to say, the values which should be used by the
3465 * hardware, when it delivers an interrupt. (MMIO resources are
3466 * used in local terms.) This is nice for Windows, and lines up
3467 * with the FDO/PDO split, which doesn't exist in Linux. Linux
3468 * is deeply expecting to scan an emulated PCI configuration
3469 * space. So this message is sent here only to drive the state
3470 * machine on the host forward.
3472 * Return: 0 on success, -errno on failure
3474 static int hv_send_resources_allocated(struct hv_device *hdev)
3476 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3477 struct pci_resources_assigned *res_assigned;
3478 struct pci_resources_assigned2 *res_assigned2;
3479 struct hv_pci_compl comp_pkt;
3480 struct hv_pci_dev *hpdev;
3481 struct pci_packet *pkt;
3486 size_res = (hbus->protocol_version < PCI_PROTOCOL_VERSION_1_2)
3487 ? sizeof(*res_assigned) : sizeof(*res_assigned2);
3489 pkt = kmalloc(sizeof(*pkt) + size_res, GFP_KERNEL);
3495 for (wslot = 0; wslot < 256; wslot++) {
3496 hpdev = get_pcichild_wslot(hbus, wslot);
3500 memset(pkt, 0, sizeof(*pkt) + size_res);
3501 init_completion(&comp_pkt.host_event);
3502 pkt->completion_func = hv_pci_generic_compl;
3503 pkt->compl_ctxt = &comp_pkt;
3505 if (hbus->protocol_version < PCI_PROTOCOL_VERSION_1_2) {
3507 (struct pci_resources_assigned *)&pkt->message;
3508 res_assigned->message_type.type =
3509 PCI_RESOURCES_ASSIGNED;
3510 res_assigned->wslot.slot = hpdev->desc.win_slot.slot;
3513 (struct pci_resources_assigned2 *)&pkt->message;
3514 res_assigned2->message_type.type =
3515 PCI_RESOURCES_ASSIGNED2;
3516 res_assigned2->wslot.slot = hpdev->desc.win_slot.slot;
3518 put_pcichild(hpdev);
3520 ret = vmbus_sendpacket(hdev->channel, &pkt->message,
3521 size_res, (unsigned long)pkt,
3523 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3525 ret = wait_for_response(hdev, &comp_pkt.host_event);
3529 if (comp_pkt.completion_status < 0) {
3531 dev_err(&hdev->device,
3532 "resource allocated returned 0x%x",
3533 comp_pkt.completion_status);
3537 hbus->wslot_res_allocated = wslot;
3545 * hv_send_resources_released() - Report local resources
3547 * @hdev: VMBus's tracking struct for this root PCI bus
3549 * Return: 0 on success, -errno on failure
3551 static int hv_send_resources_released(struct hv_device *hdev)
3553 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3554 struct pci_child_message pkt;
3555 struct hv_pci_dev *hpdev;
3559 for (wslot = hbus->wslot_res_allocated; wslot >= 0; wslot--) {
3560 hpdev = get_pcichild_wslot(hbus, wslot);
3564 memset(&pkt, 0, sizeof(pkt));
3565 pkt.message_type.type = PCI_RESOURCES_RELEASED;
3566 pkt.wslot.slot = hpdev->desc.win_slot.slot;
3568 put_pcichild(hpdev);
3570 ret = vmbus_sendpacket(hdev->channel, &pkt, sizeof(pkt), 0,
3571 VM_PKT_DATA_INBAND, 0);
3575 hbus->wslot_res_allocated = wslot - 1;
3578 hbus->wslot_res_allocated = -1;
3583 #define HVPCI_DOM_MAP_SIZE (64 * 1024)
3584 static DECLARE_BITMAP(hvpci_dom_map, HVPCI_DOM_MAP_SIZE);
3587 * PCI domain number 0 is used by emulated devices on Gen1 VMs, so define 0
3588 * as invalid for passthrough PCI devices of this driver.
3590 #define HVPCI_DOM_INVALID 0
3593 * hv_get_dom_num() - Get a valid PCI domain number
3594 * Check if the PCI domain number is in use, and return another number if
3597 * @dom: Requested domain number
3599 * return: domain number on success, HVPCI_DOM_INVALID on failure
3601 static u16 hv_get_dom_num(u16 dom)
3605 if (test_and_set_bit(dom, hvpci_dom_map) == 0)
3608 for_each_clear_bit(i, hvpci_dom_map, HVPCI_DOM_MAP_SIZE) {
3609 if (test_and_set_bit(i, hvpci_dom_map) == 0)
3613 return HVPCI_DOM_INVALID;
3617 * hv_put_dom_num() - Mark the PCI domain number as free
3618 * @dom: Domain number to be freed
3620 static void hv_put_dom_num(u16 dom)
3622 clear_bit(dom, hvpci_dom_map);
3626 * hv_pci_probe() - New VMBus channel probe, for a root PCI bus
3627 * @hdev: VMBus's tracking struct for this root PCI bus
3628 * @dev_id: Identifies the device itself
3630 * Return: 0 on success, -errno on failure
3632 static int hv_pci_probe(struct hv_device *hdev,
3633 const struct hv_vmbus_device_id *dev_id)
3635 struct pci_host_bridge *bridge;
3636 struct hv_pcibus_device *hbus;
3641 bridge = devm_pci_alloc_host_bridge(&hdev->device, 0);
3645 hbus = kzalloc(sizeof(*hbus), GFP_KERNEL);
3649 hbus->bridge = bridge;
3650 mutex_init(&hbus->state_lock);
3651 hbus->state = hv_pcibus_init;
3652 hbus->wslot_res_allocated = -1;
3655 * The PCI bus "domain" is what is called "segment" in ACPI and other
3656 * specs. Pull it from the instance ID, to get something usually
3657 * unique. In rare cases of collision, we will find out another number
3660 * Note that, since this code only runs in a Hyper-V VM, Hyper-V
3661 * together with this guest driver can guarantee that (1) The only
3662 * domain used by Gen1 VMs for something that looks like a physical
3663 * PCI bus (which is actually emulated by the hypervisor) is domain 0.
3664 * (2) There will be no overlap between domains (after fixing possible
3665 * collisions) in the same VM.
3667 dom_req = hdev->dev_instance.b[5] << 8 | hdev->dev_instance.b[4];
3668 dom = hv_get_dom_num(dom_req);
3670 if (dom == HVPCI_DOM_INVALID) {
3671 dev_err(&hdev->device,
3672 "Unable to use dom# 0x%x or other numbers", dom_req);
3678 dev_info(&hdev->device,
3679 "PCI dom# 0x%x has collision, using 0x%x",
3682 hbus->bridge->domain_nr = dom;
3684 hbus->sysdata.domain = dom;
3685 hbus->use_calls = !!(ms_hyperv.hints & HV_X64_USE_MMIO_HYPERCALLS);
3686 #elif defined(CONFIG_ARM64)
3688 * Set the PCI bus parent to be the corresponding VMbus
3689 * device. Then the VMbus device will be assigned as the
3690 * ACPI companion in pcibios_root_bridge_prepare() and
3691 * pci_dma_configure() will propagate device coherence
3692 * information to devices created on the bus.
3694 hbus->sysdata.parent = hdev->device.parent;
3695 hbus->use_calls = false;
3699 INIT_LIST_HEAD(&hbus->children);
3700 INIT_LIST_HEAD(&hbus->dr_list);
3701 spin_lock_init(&hbus->config_lock);
3702 spin_lock_init(&hbus->device_list_lock);
3703 hbus->wq = alloc_ordered_workqueue("hv_pci_%x", 0,
3704 hbus->bridge->domain_nr);
3710 hdev->channel->next_request_id_callback = vmbus_next_request_id;
3711 hdev->channel->request_addr_callback = vmbus_request_addr;
3712 hdev->channel->rqstor_size = HV_PCI_RQSTOR_SIZE;
3714 ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
3715 hv_pci_onchannelcallback, hbus);
3719 hv_set_drvdata(hdev, hbus);
3721 ret = hv_pci_protocol_negotiation(hdev, pci_protocol_versions,
3722 ARRAY_SIZE(pci_protocol_versions));
3726 ret = hv_allocate_config_window(hbus);
3730 hbus->cfg_addr = ioremap(hbus->mem_config->start,
3731 PCI_CONFIG_MMIO_LENGTH);
3732 if (!hbus->cfg_addr) {
3733 dev_err(&hdev->device,
3734 "Unable to map a virtual address for config space\n");
3739 name = kasprintf(GFP_KERNEL, "%pUL", &hdev->dev_instance);
3745 hbus->fwnode = irq_domain_alloc_named_fwnode(name);
3747 if (!hbus->fwnode) {
3752 ret = hv_pcie_init_irq_domain(hbus);
3756 ret = hv_pci_query_relations(hdev);
3758 goto free_irq_domain;
3760 mutex_lock(&hbus->state_lock);
3762 ret = hv_pci_enter_d0(hdev);
3764 goto release_state_lock;
3766 ret = hv_pci_allocate_bridge_windows(hbus);
3770 ret = hv_send_resources_allocated(hdev);
3774 prepopulate_bars(hbus);
3776 hbus->state = hv_pcibus_probed;
3778 ret = create_root_hv_pci_bus(hbus);
3782 mutex_unlock(&hbus->state_lock);
3786 hv_pci_free_bridge_windows(hbus);
3788 (void) hv_pci_bus_exit(hdev, true);
3790 mutex_unlock(&hbus->state_lock);
3792 irq_domain_remove(hbus->irq_domain);
3794 irq_domain_free_fwnode(hbus->fwnode);
3796 iounmap(hbus->cfg_addr);
3798 hv_free_config_window(hbus);
3800 vmbus_close(hdev->channel);
3802 destroy_workqueue(hbus->wq);
3804 hv_put_dom_num(hbus->bridge->domain_nr);
3810 static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs)
3812 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3813 struct vmbus_channel *chan = hdev->channel;
3815 struct pci_packet teardown_packet;
3816 u8 buffer[sizeof(struct pci_message)];
3818 struct hv_pci_compl comp_pkt;
3819 struct hv_pci_dev *hpdev, *tmp;
3820 unsigned long flags;
3825 * After the host sends the RESCIND_CHANNEL message, it doesn't
3826 * access the per-channel ringbuffer any longer.
3832 struct list_head removed;
3834 /* Move all present children to the list on stack */
3835 INIT_LIST_HEAD(&removed);
3836 spin_lock_irqsave(&hbus->device_list_lock, flags);
3837 list_for_each_entry_safe(hpdev, tmp, &hbus->children, list_entry)
3838 list_move_tail(&hpdev->list_entry, &removed);
3839 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
3841 /* Remove all children in the list */
3842 list_for_each_entry_safe(hpdev, tmp, &removed, list_entry) {
3843 list_del(&hpdev->list_entry);
3844 if (hpdev->pci_slot)
3845 pci_destroy_slot(hpdev->pci_slot);
3846 /* For the two refs got in new_pcichild_device() */
3847 put_pcichild(hpdev);
3848 put_pcichild(hpdev);
3852 ret = hv_send_resources_released(hdev);
3854 dev_err(&hdev->device,
3855 "Couldn't send resources released packet(s)\n");
3859 memset(&pkt.teardown_packet, 0, sizeof(pkt.teardown_packet));
3860 init_completion(&comp_pkt.host_event);
3861 pkt.teardown_packet.completion_func = hv_pci_generic_compl;
3862 pkt.teardown_packet.compl_ctxt = &comp_pkt;
3863 pkt.teardown_packet.message[0].type = PCI_BUS_D0EXIT;
3865 ret = vmbus_sendpacket_getid(chan, &pkt.teardown_packet.message,
3866 sizeof(struct pci_message),
3867 (unsigned long)&pkt.teardown_packet,
3868 &trans_id, VM_PKT_DATA_INBAND,
3869 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3873 if (wait_for_completion_timeout(&comp_pkt.host_event, 10 * HZ) == 0) {
3875 * The completion packet on the stack becomes invalid after
3876 * 'return'; remove the ID from the VMbus requestor if the
3877 * identifier is still mapped to/associated with the packet.
3879 * Cf. hv_pci_onchannelcallback().
3881 vmbus_request_addr_match(chan, trans_id,
3882 (unsigned long)&pkt.teardown_packet);
3890 * hv_pci_remove() - Remove routine for this VMBus channel
3891 * @hdev: VMBus's tracking struct for this root PCI bus
3893 static void hv_pci_remove(struct hv_device *hdev)
3895 struct hv_pcibus_device *hbus;
3897 hbus = hv_get_drvdata(hdev);
3898 if (hbus->state == hv_pcibus_installed) {
3899 tasklet_disable(&hdev->channel->callback_event);
3900 hbus->state = hv_pcibus_removing;
3901 tasklet_enable(&hdev->channel->callback_event);
3902 destroy_workqueue(hbus->wq);
3905 * At this point, no work is running or can be scheduled
3906 * on hbus-wq. We can't race with hv_pci_devices_present()
3907 * or hv_pci_eject_device(), it's safe to proceed.
3910 /* Remove the bus from PCI's point of view. */
3911 pci_lock_rescan_remove();
3912 pci_stop_root_bus(hbus->bridge->bus);
3913 hv_pci_remove_slots(hbus);
3914 pci_remove_root_bus(hbus->bridge->bus);
3915 pci_unlock_rescan_remove();
3918 hv_pci_bus_exit(hdev, false);
3920 vmbus_close(hdev->channel);
3922 iounmap(hbus->cfg_addr);
3923 hv_free_config_window(hbus);
3924 hv_pci_free_bridge_windows(hbus);
3925 irq_domain_remove(hbus->irq_domain);
3926 irq_domain_free_fwnode(hbus->fwnode);
3928 hv_put_dom_num(hbus->bridge->domain_nr);
3933 static int hv_pci_suspend(struct hv_device *hdev)
3935 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3936 enum hv_pcibus_state old_state;
3940 * hv_pci_suspend() must make sure there are no pending work items
3941 * before calling vmbus_close(), since it runs in a process context
3942 * as a callback in dpm_suspend(). When it starts to run, the channel
3943 * callback hv_pci_onchannelcallback(), which runs in a tasklet
3944 * context, can be still running concurrently and scheduling new work
3945 * items onto hbus->wq in hv_pci_devices_present() and
3946 * hv_pci_eject_device(), and the work item handlers can access the
3947 * vmbus channel, which can be being closed by hv_pci_suspend(), e.g.
3948 * the work item handler pci_devices_present_work() ->
3949 * new_pcichild_device() writes to the vmbus channel.
3951 * To eliminate the race, hv_pci_suspend() disables the channel
3952 * callback tasklet, sets hbus->state to hv_pcibus_removing, and
3953 * re-enables the tasklet. This way, when hv_pci_suspend() proceeds,
3954 * it knows that no new work item can be scheduled, and then it flushes
3955 * hbus->wq and safely closes the vmbus channel.
3957 tasklet_disable(&hdev->channel->callback_event);
3959 /* Change the hbus state to prevent new work items. */
3960 old_state = hbus->state;
3961 if (hbus->state == hv_pcibus_installed)
3962 hbus->state = hv_pcibus_removing;
3964 tasklet_enable(&hdev->channel->callback_event);
3966 if (old_state != hv_pcibus_installed)
3969 flush_workqueue(hbus->wq);
3971 ret = hv_pci_bus_exit(hdev, true);
3975 vmbus_close(hdev->channel);
3980 static int hv_pci_restore_msi_msg(struct pci_dev *pdev, void *arg)
3982 struct irq_data *irq_data;
3983 struct msi_desc *entry;
3986 if (!pdev->msi_enabled && !pdev->msix_enabled)
3989 msi_lock_descs(&pdev->dev);
3990 msi_for_each_desc(entry, &pdev->dev, MSI_DESC_ASSOCIATED) {
3991 irq_data = irq_get_irq_data(entry->irq);
3992 if (WARN_ON_ONCE(!irq_data)) {
3997 hv_compose_msi_msg(irq_data, &entry->msg);
3999 msi_unlock_descs(&pdev->dev);
4005 * Upon resume, pci_restore_msi_state() -> ... -> __pci_write_msi_msg()
4006 * directly writes the MSI/MSI-X registers via MMIO, but since Hyper-V
4007 * doesn't trap and emulate the MMIO accesses, here hv_compose_msi_msg()
4008 * must be used to ask Hyper-V to re-create the IOMMU Interrupt Remapping
4011 static void hv_pci_restore_msi_state(struct hv_pcibus_device *hbus)
4013 pci_walk_bus(hbus->bridge->bus, hv_pci_restore_msi_msg, NULL);
4016 static int hv_pci_resume(struct hv_device *hdev)
4018 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
4019 enum pci_protocol_version_t version[1];
4022 hbus->state = hv_pcibus_init;
4024 hdev->channel->next_request_id_callback = vmbus_next_request_id;
4025 hdev->channel->request_addr_callback = vmbus_request_addr;
4026 hdev->channel->rqstor_size = HV_PCI_RQSTOR_SIZE;
4028 ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
4029 hv_pci_onchannelcallback, hbus);
4033 /* Only use the version that was in use before hibernation. */
4034 version[0] = hbus->protocol_version;
4035 ret = hv_pci_protocol_negotiation(hdev, version, 1);
4039 ret = hv_pci_query_relations(hdev);
4043 mutex_lock(&hbus->state_lock);
4045 ret = hv_pci_enter_d0(hdev);
4047 goto release_state_lock;
4049 ret = hv_send_resources_allocated(hdev);
4051 goto release_state_lock;
4053 prepopulate_bars(hbus);
4055 hv_pci_restore_msi_state(hbus);
4057 hbus->state = hv_pcibus_installed;
4058 mutex_unlock(&hbus->state_lock);
4062 mutex_unlock(&hbus->state_lock);
4064 vmbus_close(hdev->channel);
4068 static const struct hv_vmbus_device_id hv_pci_id_table[] = {
4069 /* PCI Pass-through Class ID */
4070 /* 44C4F61D-4444-4400-9D52-802E27EDE19F */
4075 MODULE_DEVICE_TABLE(vmbus, hv_pci_id_table);
4077 static struct hv_driver hv_pci_drv = {
4079 .id_table = hv_pci_id_table,
4080 .probe = hv_pci_probe,
4081 .remove = hv_pci_remove,
4082 .suspend = hv_pci_suspend,
4083 .resume = hv_pci_resume,
4086 static void __exit exit_hv_pci_drv(void)
4088 vmbus_driver_unregister(&hv_pci_drv);
4090 hvpci_block_ops.read_block = NULL;
4091 hvpci_block_ops.write_block = NULL;
4092 hvpci_block_ops.reg_blk_invalidate = NULL;
4095 static int __init init_hv_pci_drv(void)
4099 if (!hv_is_hyperv_initialized())
4102 ret = hv_pci_irqchip_init();
4106 /* Set the invalid domain number's bit, so it will not be used */
4107 set_bit(HVPCI_DOM_INVALID, hvpci_dom_map);
4109 /* Initialize PCI block r/w interface */
4110 hvpci_block_ops.read_block = hv_read_config_block;
4111 hvpci_block_ops.write_block = hv_write_config_block;
4112 hvpci_block_ops.reg_blk_invalidate = hv_register_block_invalidate;
4114 return vmbus_driver_register(&hv_pci_drv);
4117 module_init(init_hv_pci_drv);
4118 module_exit(exit_hv_pci_drv);
4120 MODULE_DESCRIPTION("Hyper-V PCI");
4121 MODULE_LICENSE("GPL v2");