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/delay.h>
44 #include <linux/semaphore.h>
45 #include <linux/irqdomain.h>
46 #include <asm/irqdomain.h>
48 #include <linux/irq.h>
49 #include <linux/msi.h>
50 #include <linux/hyperv.h>
51 #include <linux/refcount.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 */
69 #define CPU_AFFINITY_ALL -1ULL
72 * Supported protocol versions in the order of probing - highest go
75 static enum pci_protocol_version_t pci_protocol_versions[] = {
76 PCI_PROTOCOL_VERSION_1_3,
77 PCI_PROTOCOL_VERSION_1_2,
78 PCI_PROTOCOL_VERSION_1_1,
81 #define PCI_CONFIG_MMIO_LENGTH 0x2000
82 #define CFG_PAGE_OFFSET 0x1000
83 #define CFG_PAGE_SIZE (PCI_CONFIG_MMIO_LENGTH - CFG_PAGE_OFFSET)
85 #define MAX_SUPPORTED_MSI_MESSAGES 0x400
87 #define STATUS_REVISION_MISMATCH 0xC0000059
89 /* space for 32bit serial number as string */
90 #define SLOT_NAME_SIZE 11
96 enum pci_message_type {
100 PCI_MESSAGE_BASE = 0x42490000,
101 PCI_BUS_RELATIONS = PCI_MESSAGE_BASE + 0,
102 PCI_QUERY_BUS_RELATIONS = PCI_MESSAGE_BASE + 1,
103 PCI_POWER_STATE_CHANGE = PCI_MESSAGE_BASE + 4,
104 PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5,
105 PCI_QUERY_RESOURCE_RESOURCES = PCI_MESSAGE_BASE + 6,
106 PCI_BUS_D0ENTRY = PCI_MESSAGE_BASE + 7,
107 PCI_BUS_D0EXIT = PCI_MESSAGE_BASE + 8,
108 PCI_READ_BLOCK = PCI_MESSAGE_BASE + 9,
109 PCI_WRITE_BLOCK = PCI_MESSAGE_BASE + 0xA,
110 PCI_EJECT = PCI_MESSAGE_BASE + 0xB,
111 PCI_QUERY_STOP = PCI_MESSAGE_BASE + 0xC,
112 PCI_REENABLE = PCI_MESSAGE_BASE + 0xD,
113 PCI_QUERY_STOP_FAILED = PCI_MESSAGE_BASE + 0xE,
114 PCI_EJECTION_COMPLETE = PCI_MESSAGE_BASE + 0xF,
115 PCI_RESOURCES_ASSIGNED = PCI_MESSAGE_BASE + 0x10,
116 PCI_RESOURCES_RELEASED = PCI_MESSAGE_BASE + 0x11,
117 PCI_INVALIDATE_BLOCK = PCI_MESSAGE_BASE + 0x12,
118 PCI_QUERY_PROTOCOL_VERSION = PCI_MESSAGE_BASE + 0x13,
119 PCI_CREATE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x14,
120 PCI_DELETE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x15,
121 PCI_RESOURCES_ASSIGNED2 = PCI_MESSAGE_BASE + 0x16,
122 PCI_CREATE_INTERRUPT_MESSAGE2 = PCI_MESSAGE_BASE + 0x17,
123 PCI_DELETE_INTERRUPT_MESSAGE2 = PCI_MESSAGE_BASE + 0x18, /* unused */
124 PCI_BUS_RELATIONS2 = PCI_MESSAGE_BASE + 0x19,
129 * Structures defining the virtual PCI Express protocol.
141 * Function numbers are 8-bits wide on Express, as interpreted through ARI,
142 * which is all this driver does. This representation is the one used in
143 * Windows, which is what is expected when sending this back and forth with
144 * the Hyper-V parent partition.
146 union win_slot_encoding {
156 * Pretty much as defined in the PCI Specifications.
158 struct pci_function_description {
159 u16 v_id; /* vendor ID */
160 u16 d_id; /* device ID */
166 union win_slot_encoding win_slot;
167 u32 ser; /* serial number */
170 enum pci_device_description_flags {
171 HV_PCI_DEVICE_FLAG_NONE = 0x0,
172 HV_PCI_DEVICE_FLAG_NUMA_AFFINITY = 0x1,
175 struct pci_function_description2 {
176 u16 v_id; /* vendor ID */
177 u16 d_id; /* device ID */
183 union win_slot_encoding win_slot;
184 u32 ser; /* serial number */
186 u16 virtual_numa_node;
193 * @delivery_mode: As defined in Intel's Programmer's
194 * Reference Manual, Volume 3, Chapter 8.
195 * @vector_count: Number of contiguous entries in the
196 * Interrupt Descriptor Table that are
197 * occupied by this Message-Signaled
198 * Interrupt. For "MSI", as first defined
199 * in PCI 2.2, this can be between 1 and
200 * 32. For "MSI-X," as first defined in PCI
201 * 3.0, this must be 1, as each MSI-X table
202 * entry would have its own descriptor.
203 * @reserved: Empty space
204 * @cpu_mask: All the target virtual processors.
215 * struct hv_msi_desc2 - 1.2 version of hv_msi_desc
217 * @delivery_mode: As defined in Intel's Programmer's
218 * Reference Manual, Volume 3, Chapter 8.
219 * @vector_count: Number of contiguous entries in the
220 * Interrupt Descriptor Table that are
221 * occupied by this Message-Signaled
222 * Interrupt. For "MSI", as first defined
223 * in PCI 2.2, this can be between 1 and
224 * 32. For "MSI-X," as first defined in PCI
225 * 3.0, this must be 1, as each MSI-X table
226 * entry would have its own descriptor.
227 * @processor_count: number of bits enabled in array.
228 * @processor_array: All the target virtual processors.
230 struct hv_msi_desc2 {
235 u16 processor_array[32];
239 * struct tran_int_desc
240 * @reserved: unused, padding
241 * @vector_count: same as in hv_msi_desc
242 * @data: This is the "data payload" value that is
243 * written by the device when it generates
244 * a message-signaled interrupt, either MSI
246 * @address: This is the address to which the data
247 * payload is written on interrupt
250 struct tran_int_desc {
258 * A generic message format for virtual PCI.
259 * Specific message formats are defined later in the file.
266 struct pci_child_message {
267 struct pci_message message_type;
268 union win_slot_encoding wslot;
271 struct pci_incoming_message {
272 struct vmpacket_descriptor hdr;
273 struct pci_message message_type;
276 struct pci_response {
277 struct vmpacket_descriptor hdr;
278 s32 status; /* negative values are failures */
282 void (*completion_func)(void *context, struct pci_response *resp,
283 int resp_packet_size);
286 struct pci_message message[];
290 * Specific message types supporting the PCI protocol.
294 * Version negotiation message. Sent from the guest to the host.
295 * The guest is free to try different versions until the host
296 * accepts the version.
298 * pci_version: The protocol version requested.
299 * is_last_attempt: If TRUE, this is the last version guest will request.
300 * reservedz: Reserved field, set to zero.
303 struct pci_version_request {
304 struct pci_message message_type;
305 u32 protocol_version;
309 * Bus D0 Entry. This is sent from the guest to the host when the virtual
310 * bus (PCI Express port) is ready for action.
313 struct pci_bus_d0_entry {
314 struct pci_message message_type;
319 struct pci_bus_relations {
320 struct pci_incoming_message incoming;
322 struct pci_function_description func[];
325 struct pci_bus_relations2 {
326 struct pci_incoming_message incoming;
328 struct pci_function_description2 func[];
331 struct pci_q_res_req_response {
332 struct vmpacket_descriptor hdr;
333 s32 status; /* negative values are failures */
334 u32 probed_bar[PCI_STD_NUM_BARS];
337 struct pci_set_power {
338 struct pci_message message_type;
339 union win_slot_encoding wslot;
340 u32 power_state; /* In Windows terms */
344 struct pci_set_power_response {
345 struct vmpacket_descriptor hdr;
346 s32 status; /* negative values are failures */
347 union win_slot_encoding wslot;
348 u32 resultant_state; /* In Windows terms */
352 struct pci_resources_assigned {
353 struct pci_message message_type;
354 union win_slot_encoding wslot;
355 u8 memory_range[0x14][6]; /* not used here */
360 struct pci_resources_assigned2 {
361 struct pci_message message_type;
362 union win_slot_encoding wslot;
363 u8 memory_range[0x14][6]; /* not used here */
364 u32 msi_descriptor_count;
368 struct pci_create_interrupt {
369 struct pci_message message_type;
370 union win_slot_encoding wslot;
371 struct hv_msi_desc int_desc;
374 struct pci_create_int_response {
375 struct pci_response response;
377 struct tran_int_desc int_desc;
380 struct pci_create_interrupt2 {
381 struct pci_message message_type;
382 union win_slot_encoding wslot;
383 struct hv_msi_desc2 int_desc;
386 struct pci_delete_interrupt {
387 struct pci_message message_type;
388 union win_slot_encoding wslot;
389 struct tran_int_desc int_desc;
393 * Note: the VM must pass a valid block id, wslot and bytes_requested.
395 struct pci_read_block {
396 struct pci_message message_type;
398 union win_slot_encoding wslot;
402 struct pci_read_block_response {
403 struct vmpacket_descriptor hdr;
405 u8 bytes[HV_CONFIG_BLOCK_SIZE_MAX];
409 * Note: the VM must pass a valid block id, wslot and byte_count.
411 struct pci_write_block {
412 struct pci_message message_type;
414 union win_slot_encoding wslot;
416 u8 bytes[HV_CONFIG_BLOCK_SIZE_MAX];
419 struct pci_dev_inval_block {
420 struct pci_incoming_message incoming;
421 union win_slot_encoding wslot;
425 struct pci_dev_incoming {
426 struct pci_incoming_message incoming;
427 union win_slot_encoding wslot;
430 struct pci_eject_response {
431 struct pci_message message_type;
432 union win_slot_encoding wslot;
436 static int pci_ring_size = (4 * PAGE_SIZE);
439 * Driver specific state.
442 enum hv_pcibus_state {
450 struct hv_pcibus_device {
451 struct pci_sysdata sysdata;
452 /* Protocol version negotiated with the host */
453 enum pci_protocol_version_t protocol_version;
454 enum hv_pcibus_state state;
455 struct hv_device *hdev;
456 resource_size_t low_mmio_space;
457 resource_size_t high_mmio_space;
458 struct resource *mem_config;
459 struct resource *low_mmio_res;
460 struct resource *high_mmio_res;
461 struct completion *survey_event;
462 struct pci_bus *pci_bus;
463 spinlock_t config_lock; /* Avoid two threads writing index page */
464 spinlock_t device_list_lock; /* Protect lists below */
465 void __iomem *cfg_addr;
467 struct list_head resources_for_children;
469 struct list_head children;
470 struct list_head dr_list;
472 struct msi_domain_info msi_info;
473 struct irq_domain *irq_domain;
475 spinlock_t retarget_msi_interrupt_lock;
477 struct workqueue_struct *wq;
479 /* Highest slot of child device with resources allocated */
480 int wslot_res_allocated;
482 /* hypercall arg, must not cross page boundary */
483 struct hv_retarget_device_interrupt retarget_msi_interrupt_params;
486 * Don't put anything here: retarget_msi_interrupt_params must be last
491 * Tracks "Device Relations" messages from the host, which must be both
492 * processed in order and deferred so that they don't run in the context
493 * of the incoming packet callback.
496 struct work_struct wrk;
497 struct hv_pcibus_device *bus;
500 struct hv_pcidev_description {
501 u16 v_id; /* vendor ID */
502 u16 d_id; /* device ID */
508 union win_slot_encoding win_slot;
509 u32 ser; /* serial number */
511 u16 virtual_numa_node;
515 struct list_head list_entry;
517 struct hv_pcidev_description func[];
520 enum hv_pcichild_state {
521 hv_pcichild_init = 0,
522 hv_pcichild_requirements,
523 hv_pcichild_resourced,
524 hv_pcichild_ejecting,
529 /* List protected by pci_rescan_remove_lock */
530 struct list_head list_entry;
532 enum hv_pcichild_state state;
533 struct pci_slot *pci_slot;
534 struct hv_pcidev_description desc;
535 bool reported_missing;
536 struct hv_pcibus_device *hbus;
537 struct work_struct wrk;
539 void (*block_invalidate)(void *context, u64 block_mask);
540 void *invalidate_context;
543 * What would be observed if one wrote 0xFFFFFFFF to a BAR and then
544 * read it back, for each of the BAR offsets within config space.
546 u32 probed_bar[PCI_STD_NUM_BARS];
549 struct hv_pci_compl {
550 struct completion host_event;
551 s32 completion_status;
554 static void hv_pci_onchannelcallback(void *context);
557 * hv_pci_generic_compl() - Invoked for a completion packet
558 * @context: Set up by the sender of the packet.
559 * @resp: The response packet
560 * @resp_packet_size: Size in bytes of the packet
562 * This function is used to trigger an event and report status
563 * for any message for which the completion packet contains a
564 * status and nothing else.
566 static void hv_pci_generic_compl(void *context, struct pci_response *resp,
567 int resp_packet_size)
569 struct hv_pci_compl *comp_pkt = context;
571 if (resp_packet_size >= offsetofend(struct pci_response, status))
572 comp_pkt->completion_status = resp->status;
574 comp_pkt->completion_status = -1;
576 complete(&comp_pkt->host_event);
579 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
582 static void get_pcichild(struct hv_pci_dev *hpdev)
584 refcount_inc(&hpdev->refs);
587 static void put_pcichild(struct hv_pci_dev *hpdev)
589 if (refcount_dec_and_test(&hpdev->refs))
594 * There is no good way to get notified from vmbus_onoffer_rescind(),
595 * so let's use polling here, since this is not a hot path.
597 static int wait_for_response(struct hv_device *hdev,
598 struct completion *comp)
601 if (hdev->channel->rescind) {
602 dev_warn_once(&hdev->device, "The device is gone.\n");
606 if (wait_for_completion_timeout(comp, HZ / 10))
614 * devfn_to_wslot() - Convert from Linux PCI slot to Windows
615 * @devfn: The Linux representation of PCI slot
617 * Windows uses a slightly different representation of PCI slot.
619 * Return: The Windows representation
621 static u32 devfn_to_wslot(int devfn)
623 union win_slot_encoding wslot;
626 wslot.bits.dev = PCI_SLOT(devfn);
627 wslot.bits.func = PCI_FUNC(devfn);
633 * wslot_to_devfn() - Convert from Windows PCI slot to Linux
634 * @wslot: The Windows representation of PCI slot
636 * Windows uses a slightly different representation of PCI slot.
638 * Return: The Linux representation
640 static int wslot_to_devfn(u32 wslot)
642 union win_slot_encoding slot_no;
644 slot_no.slot = wslot;
645 return PCI_DEVFN(slot_no.bits.dev, slot_no.bits.func);
649 * PCI Configuration Space for these root PCI buses is implemented as a pair
650 * of pages in memory-mapped I/O space. Writing to the first page chooses
651 * the PCI function being written or read. Once the first page has been
652 * written to, the following page maps in the entire configuration space of
657 * _hv_pcifront_read_config() - Internal PCI config read
658 * @hpdev: The PCI driver's representation of the device
659 * @where: Offset within config space
660 * @size: Size of the transfer
661 * @val: Pointer to the buffer receiving the data
663 static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where,
667 void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
670 * If the attempt is to read the IDs or the ROM BAR, simulate that.
672 if (where + size <= PCI_COMMAND) {
673 memcpy(val, ((u8 *)&hpdev->desc.v_id) + where, size);
674 } else if (where >= PCI_CLASS_REVISION && where + size <=
675 PCI_CACHE_LINE_SIZE) {
676 memcpy(val, ((u8 *)&hpdev->desc.rev) + where -
677 PCI_CLASS_REVISION, size);
678 } else if (where >= PCI_SUBSYSTEM_VENDOR_ID && where + size <=
680 memcpy(val, (u8 *)&hpdev->desc.subsystem_id + where -
681 PCI_SUBSYSTEM_VENDOR_ID, size);
682 } else if (where >= PCI_ROM_ADDRESS && where + size <=
683 PCI_CAPABILITY_LIST) {
684 /* ROM BARs are unimplemented */
686 } else if (where >= PCI_INTERRUPT_LINE && where + size <=
689 * Interrupt Line and Interrupt PIN are hard-wired to zero
690 * because this front-end only supports message-signaled
694 } else if (where + size <= CFG_PAGE_SIZE) {
695 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
696 /* Choose the function to be read. (See comment above) */
697 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
698 /* Make sure the function was chosen before we start reading. */
700 /* Read from that function's config space. */
713 * Make sure the read was done before we release the spinlock
714 * allowing consecutive reads/writes.
717 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
719 dev_err(&hpdev->hbus->hdev->device,
720 "Attempt to read beyond a function's config space.\n");
724 static u16 hv_pcifront_get_vendor_id(struct hv_pci_dev *hpdev)
728 void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET +
731 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
733 /* Choose the function to be read. (See comment above) */
734 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
735 /* Make sure the function was chosen before we start reading. */
737 /* Read from that function's config space. */
740 * mb() is not required here, because the spin_unlock_irqrestore()
744 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
750 * _hv_pcifront_write_config() - Internal PCI config write
751 * @hpdev: The PCI driver's representation of the device
752 * @where: Offset within config space
753 * @size: Size of the transfer
754 * @val: The data being transferred
756 static void _hv_pcifront_write_config(struct hv_pci_dev *hpdev, int where,
760 void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
762 if (where >= PCI_SUBSYSTEM_VENDOR_ID &&
763 where + size <= PCI_CAPABILITY_LIST) {
764 /* SSIDs and ROM BARs are read-only */
765 } else if (where >= PCI_COMMAND && where + size <= CFG_PAGE_SIZE) {
766 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
767 /* Choose the function to be written. (See comment above) */
768 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
769 /* Make sure the function was chosen before we start writing. */
771 /* Write to that function's config space. */
784 * Make sure the write was done before we release the spinlock
785 * allowing consecutive reads/writes.
788 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
790 dev_err(&hpdev->hbus->hdev->device,
791 "Attempt to write beyond a function's config space.\n");
796 * hv_pcifront_read_config() - Read configuration space
797 * @bus: PCI Bus structure
798 * @devfn: Device/function
799 * @where: Offset from base
800 * @size: Byte/word/dword
801 * @val: Value to be read
803 * Return: PCIBIOS_SUCCESSFUL on success
804 * PCIBIOS_DEVICE_NOT_FOUND on failure
806 static int hv_pcifront_read_config(struct pci_bus *bus, unsigned int devfn,
807 int where, int size, u32 *val)
809 struct hv_pcibus_device *hbus =
810 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
811 struct hv_pci_dev *hpdev;
813 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
815 return PCIBIOS_DEVICE_NOT_FOUND;
817 _hv_pcifront_read_config(hpdev, where, size, val);
820 return PCIBIOS_SUCCESSFUL;
824 * hv_pcifront_write_config() - Write configuration space
825 * @bus: PCI Bus structure
826 * @devfn: Device/function
827 * @where: Offset from base
828 * @size: Byte/word/dword
829 * @val: Value to be written to device
831 * Return: PCIBIOS_SUCCESSFUL on success
832 * PCIBIOS_DEVICE_NOT_FOUND on failure
834 static int hv_pcifront_write_config(struct pci_bus *bus, unsigned int devfn,
835 int where, int size, u32 val)
837 struct hv_pcibus_device *hbus =
838 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
839 struct hv_pci_dev *hpdev;
841 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
843 return PCIBIOS_DEVICE_NOT_FOUND;
845 _hv_pcifront_write_config(hpdev, where, size, val);
848 return PCIBIOS_SUCCESSFUL;
851 /* PCIe operations */
852 static struct pci_ops hv_pcifront_ops = {
853 .read = hv_pcifront_read_config,
854 .write = hv_pcifront_write_config,
858 * Paravirtual backchannel
860 * Hyper-V SR-IOV provides a backchannel mechanism in software for
861 * communication between a VF driver and a PF driver. These
862 * "configuration blocks" are similar in concept to PCI configuration space,
863 * but instead of doing reads and writes in 32-bit chunks through a very slow
864 * path, packets of up to 128 bytes can be sent or received asynchronously.
866 * Nearly every SR-IOV device contains just such a communications channel in
867 * hardware, so using this one in software is usually optional. Using the
868 * software channel, however, allows driver implementers to leverage software
869 * tools that fuzz the communications channel looking for vulnerabilities.
871 * The usage model for these packets puts the responsibility for reading or
872 * writing on the VF driver. The VF driver sends a read or a write packet,
873 * indicating which "block" is being referred to by number.
875 * If the PF driver wishes to initiate communication, it can "invalidate" one or
876 * more of the first 64 blocks. This invalidation is delivered via a callback
877 * supplied by the VF driver by this driver.
879 * No protocol is implied, except that supplied by the PF and VF drivers.
882 struct hv_read_config_compl {
883 struct hv_pci_compl comp_pkt;
886 unsigned int bytes_returned;
890 * hv_pci_read_config_compl() - Invoked when a response packet
891 * for a read config block operation arrives.
892 * @context: Identifies the read config operation
893 * @resp: The response packet itself
894 * @resp_packet_size: Size in bytes of the response packet
896 static void hv_pci_read_config_compl(void *context, struct pci_response *resp,
897 int resp_packet_size)
899 struct hv_read_config_compl *comp = context;
900 struct pci_read_block_response *read_resp =
901 (struct pci_read_block_response *)resp;
902 unsigned int data_len, hdr_len;
904 hdr_len = offsetof(struct pci_read_block_response, bytes);
905 if (resp_packet_size < hdr_len) {
906 comp->comp_pkt.completion_status = -1;
910 data_len = resp_packet_size - hdr_len;
911 if (data_len > 0 && read_resp->status == 0) {
912 comp->bytes_returned = min(comp->len, data_len);
913 memcpy(comp->buf, read_resp->bytes, comp->bytes_returned);
915 comp->bytes_returned = 0;
918 comp->comp_pkt.completion_status = read_resp->status;
920 complete(&comp->comp_pkt.host_event);
924 * hv_read_config_block() - Sends a read config block request to
925 * the back-end driver running in the Hyper-V parent partition.
926 * @pdev: The PCI driver's representation for this device.
927 * @buf: Buffer into which the config block will be copied.
928 * @len: Size in bytes of buf.
929 * @block_id: Identifies the config block which has been requested.
930 * @bytes_returned: Size which came back from the back-end driver.
932 * Return: 0 on success, -errno on failure
934 static int hv_read_config_block(struct pci_dev *pdev, void *buf,
935 unsigned int len, unsigned int block_id,
936 unsigned int *bytes_returned)
938 struct hv_pcibus_device *hbus =
939 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
942 struct pci_packet pkt;
943 char buf[sizeof(struct pci_read_block)];
945 struct hv_read_config_compl comp_pkt;
946 struct pci_read_block *read_blk;
949 if (len == 0 || len > HV_CONFIG_BLOCK_SIZE_MAX)
952 init_completion(&comp_pkt.comp_pkt.host_event);
956 memset(&pkt, 0, sizeof(pkt));
957 pkt.pkt.completion_func = hv_pci_read_config_compl;
958 pkt.pkt.compl_ctxt = &comp_pkt;
959 read_blk = (struct pci_read_block *)&pkt.pkt.message;
960 read_blk->message_type.type = PCI_READ_BLOCK;
961 read_blk->wslot.slot = devfn_to_wslot(pdev->devfn);
962 read_blk->block_id = block_id;
963 read_blk->bytes_requested = len;
965 ret = vmbus_sendpacket(hbus->hdev->channel, read_blk,
966 sizeof(*read_blk), (unsigned long)&pkt.pkt,
968 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
972 ret = wait_for_response(hbus->hdev, &comp_pkt.comp_pkt.host_event);
976 if (comp_pkt.comp_pkt.completion_status != 0 ||
977 comp_pkt.bytes_returned == 0) {
978 dev_err(&hbus->hdev->device,
979 "Read Config Block failed: 0x%x, bytes_returned=%d\n",
980 comp_pkt.comp_pkt.completion_status,
981 comp_pkt.bytes_returned);
985 *bytes_returned = comp_pkt.bytes_returned;
990 * hv_pci_write_config_compl() - Invoked when a response packet for a write
991 * config block operation arrives.
992 * @context: Identifies the write config operation
993 * @resp: The response packet itself
994 * @resp_packet_size: Size in bytes of the response packet
996 static void hv_pci_write_config_compl(void *context, struct pci_response *resp,
997 int resp_packet_size)
999 struct hv_pci_compl *comp_pkt = context;
1001 comp_pkt->completion_status = resp->status;
1002 complete(&comp_pkt->host_event);
1006 * hv_write_config_block() - Sends a write config block request to the
1007 * back-end driver running in the Hyper-V parent partition.
1008 * @pdev: The PCI driver's representation for this device.
1009 * @buf: Buffer from which the config block will be copied.
1010 * @len: Size in bytes of buf.
1011 * @block_id: Identifies the config block which is being written.
1013 * Return: 0 on success, -errno on failure
1015 static int hv_write_config_block(struct pci_dev *pdev, void *buf,
1016 unsigned int len, unsigned int block_id)
1018 struct hv_pcibus_device *hbus =
1019 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1022 struct pci_packet pkt;
1023 char buf[sizeof(struct pci_write_block)];
1026 struct hv_pci_compl comp_pkt;
1027 struct pci_write_block *write_blk;
1031 if (len == 0 || len > HV_CONFIG_BLOCK_SIZE_MAX)
1034 init_completion(&comp_pkt.host_event);
1036 memset(&pkt, 0, sizeof(pkt));
1037 pkt.pkt.completion_func = hv_pci_write_config_compl;
1038 pkt.pkt.compl_ctxt = &comp_pkt;
1039 write_blk = (struct pci_write_block *)&pkt.pkt.message;
1040 write_blk->message_type.type = PCI_WRITE_BLOCK;
1041 write_blk->wslot.slot = devfn_to_wslot(pdev->devfn);
1042 write_blk->block_id = block_id;
1043 write_blk->byte_count = len;
1044 memcpy(write_blk->bytes, buf, len);
1045 pkt_size = offsetof(struct pci_write_block, bytes) + len;
1047 * This quirk is required on some hosts shipped around 2018, because
1048 * these hosts don't check the pkt_size correctly (new hosts have been
1049 * fixed since early 2019). The quirk is also safe on very old hosts
1050 * and new hosts, because, on them, what really matters is the length
1051 * specified in write_blk->byte_count.
1053 pkt_size += sizeof(pkt.reserved);
1055 ret = vmbus_sendpacket(hbus->hdev->channel, write_blk, pkt_size,
1056 (unsigned long)&pkt.pkt, VM_PKT_DATA_INBAND,
1057 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1061 ret = wait_for_response(hbus->hdev, &comp_pkt.host_event);
1065 if (comp_pkt.completion_status != 0) {
1066 dev_err(&hbus->hdev->device,
1067 "Write Config Block failed: 0x%x\n",
1068 comp_pkt.completion_status);
1076 * hv_register_block_invalidate() - Invoked when a config block invalidation
1077 * arrives from the back-end driver.
1078 * @pdev: The PCI driver's representation for this device.
1079 * @context: Identifies the device.
1080 * @block_invalidate: Identifies all of the blocks being invalidated.
1082 * Return: 0 on success, -errno on failure
1084 static int hv_register_block_invalidate(struct pci_dev *pdev, void *context,
1085 void (*block_invalidate)(void *context,
1088 struct hv_pcibus_device *hbus =
1089 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1091 struct hv_pci_dev *hpdev;
1093 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1097 hpdev->block_invalidate = block_invalidate;
1098 hpdev->invalidate_context = context;
1100 put_pcichild(hpdev);
1105 /* Interrupt management hooks */
1106 static void hv_int_desc_free(struct hv_pci_dev *hpdev,
1107 struct tran_int_desc *int_desc)
1109 struct pci_delete_interrupt *int_pkt;
1111 struct pci_packet pkt;
1112 u8 buffer[sizeof(struct pci_delete_interrupt)];
1115 memset(&ctxt, 0, sizeof(ctxt));
1116 int_pkt = (struct pci_delete_interrupt *)&ctxt.pkt.message;
1117 int_pkt->message_type.type =
1118 PCI_DELETE_INTERRUPT_MESSAGE;
1119 int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
1120 int_pkt->int_desc = *int_desc;
1121 vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt, sizeof(*int_pkt),
1122 (unsigned long)&ctxt.pkt, VM_PKT_DATA_INBAND, 0);
1127 * hv_msi_free() - Free the MSI.
1128 * @domain: The interrupt domain pointer
1129 * @info: Extra MSI-related context
1130 * @irq: Identifies the IRQ.
1132 * The Hyper-V parent partition and hypervisor are tracking the
1133 * messages that are in use, keeping the interrupt redirection
1134 * table up to date. This callback sends a message that frees
1135 * the IRT entry and related tracking nonsense.
1137 static void hv_msi_free(struct irq_domain *domain, struct msi_domain_info *info,
1140 struct hv_pcibus_device *hbus;
1141 struct hv_pci_dev *hpdev;
1142 struct pci_dev *pdev;
1143 struct tran_int_desc *int_desc;
1144 struct irq_data *irq_data = irq_domain_get_irq_data(domain, irq);
1145 struct msi_desc *msi = irq_data_get_msi_desc(irq_data);
1147 pdev = msi_desc_to_pci_dev(msi);
1149 int_desc = irq_data_get_irq_chip_data(irq_data);
1153 irq_data->chip_data = NULL;
1154 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1160 hv_int_desc_free(hpdev, int_desc);
1161 put_pcichild(hpdev);
1164 static int hv_set_affinity(struct irq_data *data, const struct cpumask *dest,
1167 struct irq_data *parent = data->parent_data;
1169 return parent->chip->irq_set_affinity(parent, dest, force);
1172 static void hv_irq_mask(struct irq_data *data)
1174 pci_msi_mask_irq(data);
1178 * hv_irq_unmask() - "Unmask" the IRQ by setting its current
1180 * @data: Describes the IRQ
1182 * Build new a destination for the MSI and make a hypercall to
1183 * update the Interrupt Redirection Table. "Device Logical ID"
1184 * is built out of this PCI bus's instance GUID and the function
1185 * number of the device.
1187 static void hv_irq_unmask(struct irq_data *data)
1189 struct msi_desc *msi_desc = irq_data_get_msi_desc(data);
1190 struct irq_cfg *cfg = irqd_cfg(data);
1191 struct hv_retarget_device_interrupt *params;
1192 struct hv_pcibus_device *hbus;
1193 struct cpumask *dest;
1195 struct pci_bus *pbus;
1196 struct pci_dev *pdev;
1197 unsigned long flags;
1202 dest = irq_data_get_effective_affinity_mask(data);
1203 pdev = msi_desc_to_pci_dev(msi_desc);
1205 hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
1207 spin_lock_irqsave(&hbus->retarget_msi_interrupt_lock, flags);
1209 params = &hbus->retarget_msi_interrupt_params;
1210 memset(params, 0, sizeof(*params));
1211 params->partition_id = HV_PARTITION_ID_SELF;
1212 params->int_entry.source = HV_INTERRUPT_SOURCE_MSI;
1213 hv_set_msi_entry_from_desc(¶ms->int_entry.msi_entry, msi_desc);
1214 params->device_id = (hbus->hdev->dev_instance.b[5] << 24) |
1215 (hbus->hdev->dev_instance.b[4] << 16) |
1216 (hbus->hdev->dev_instance.b[7] << 8) |
1217 (hbus->hdev->dev_instance.b[6] & 0xf8) |
1218 PCI_FUNC(pdev->devfn);
1219 params->int_target.vector = cfg->vector;
1222 * Honoring apic->delivery_mode set to APIC_DELIVERY_MODE_FIXED by
1223 * setting the HV_DEVICE_INTERRUPT_TARGET_MULTICAST flag results in a
1224 * spurious interrupt storm. Not doing so does not seem to have a
1225 * negative effect (yet?).
1228 if (hbus->protocol_version >= PCI_PROTOCOL_VERSION_1_2) {
1230 * PCI_PROTOCOL_VERSION_1_2 supports the VP_SET version of the
1231 * HVCALL_RETARGET_INTERRUPT hypercall, which also coincides
1232 * with >64 VP support.
1233 * ms_hyperv.hints & HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED
1234 * is not sufficient for this hypercall.
1236 params->int_target.flags |=
1237 HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET;
1239 if (!alloc_cpumask_var(&tmp, GFP_ATOMIC)) {
1244 cpumask_and(tmp, dest, cpu_online_mask);
1245 nr_bank = cpumask_to_vpset(¶ms->int_target.vp_set, tmp);
1246 free_cpumask_var(tmp);
1254 * var-sized hypercall, var-size starts after vp_mask (thus
1255 * vp_set.format does not count, but vp_set.valid_bank_mask
1258 var_size = 1 + nr_bank;
1260 for_each_cpu_and(cpu, dest, cpu_online_mask) {
1261 params->int_target.vp_mask |=
1262 (1ULL << hv_cpu_number_to_vp_number(cpu));
1266 res = hv_do_hypercall(HVCALL_RETARGET_INTERRUPT | (var_size << 17),
1270 spin_unlock_irqrestore(&hbus->retarget_msi_interrupt_lock, flags);
1273 * During hibernation, when a CPU is offlined, the kernel tries
1274 * to move the interrupt to the remaining CPUs that haven't
1275 * been offlined yet. In this case, the below hv_do_hypercall()
1276 * always fails since the vmbus channel has been closed:
1277 * refer to cpu_disable_common() -> fixup_irqs() ->
1278 * irq_migrate_all_off_this_cpu() -> migrate_one_irq().
1280 * Suppress the error message for hibernation because the failure
1281 * during hibernation does not matter (at this time all the devices
1282 * have been frozen). Note: the correct affinity info is still updated
1283 * into the irqdata data structure in migrate_one_irq() ->
1284 * irq_do_set_affinity() -> hv_set_affinity(), so later when the VM
1285 * resumes, hv_pci_restore_msi_state() is able to correctly restore
1286 * the interrupt with the correct affinity.
1288 if (!hv_result_success(res) && hbus->state != hv_pcibus_removing)
1289 dev_err(&hbus->hdev->device,
1290 "%s() failed: %#llx", __func__, res);
1292 pci_msi_unmask_irq(data);
1295 struct compose_comp_ctxt {
1296 struct hv_pci_compl comp_pkt;
1297 struct tran_int_desc int_desc;
1300 static void hv_pci_compose_compl(void *context, struct pci_response *resp,
1301 int resp_packet_size)
1303 struct compose_comp_ctxt *comp_pkt = context;
1304 struct pci_create_int_response *int_resp =
1305 (struct pci_create_int_response *)resp;
1307 comp_pkt->comp_pkt.completion_status = resp->status;
1308 comp_pkt->int_desc = int_resp->int_desc;
1309 complete(&comp_pkt->comp_pkt.host_event);
1312 static u32 hv_compose_msi_req_v1(
1313 struct pci_create_interrupt *int_pkt, struct cpumask *affinity,
1314 u32 slot, u8 vector)
1316 int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE;
1317 int_pkt->wslot.slot = slot;
1318 int_pkt->int_desc.vector = vector;
1319 int_pkt->int_desc.vector_count = 1;
1320 int_pkt->int_desc.delivery_mode = APIC_DELIVERY_MODE_FIXED;
1323 * Create MSI w/ dummy vCPU set, overwritten by subsequent retarget in
1326 int_pkt->int_desc.cpu_mask = CPU_AFFINITY_ALL;
1328 return sizeof(*int_pkt);
1331 static u32 hv_compose_msi_req_v2(
1332 struct pci_create_interrupt2 *int_pkt, struct cpumask *affinity,
1333 u32 slot, u8 vector)
1337 int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE2;
1338 int_pkt->wslot.slot = slot;
1339 int_pkt->int_desc.vector = vector;
1340 int_pkt->int_desc.vector_count = 1;
1341 int_pkt->int_desc.delivery_mode = APIC_DELIVERY_MODE_FIXED;
1344 * Create MSI w/ dummy vCPU set targeting just one vCPU, overwritten
1345 * by subsequent retarget in hv_irq_unmask().
1347 cpu = cpumask_first_and(affinity, cpu_online_mask);
1348 int_pkt->int_desc.processor_array[0] =
1349 hv_cpu_number_to_vp_number(cpu);
1350 int_pkt->int_desc.processor_count = 1;
1352 return sizeof(*int_pkt);
1356 * hv_compose_msi_msg() - Supplies a valid MSI address/data
1357 * @data: Everything about this MSI
1358 * @msg: Buffer that is filled in by this function
1360 * This function unpacks the IRQ looking for target CPU set, IDT
1361 * vector and mode and sends a message to the parent partition
1362 * asking for a mapping for that tuple in this partition. The
1363 * response supplies a data value and address to which that data
1364 * should be written to trigger that interrupt.
1366 static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
1368 struct irq_cfg *cfg = irqd_cfg(data);
1369 struct hv_pcibus_device *hbus;
1370 struct vmbus_channel *channel;
1371 struct hv_pci_dev *hpdev;
1372 struct pci_bus *pbus;
1373 struct pci_dev *pdev;
1374 struct cpumask *dest;
1375 struct compose_comp_ctxt comp;
1376 struct tran_int_desc *int_desc;
1378 struct pci_packet pci_pkt;
1380 struct pci_create_interrupt v1;
1381 struct pci_create_interrupt2 v2;
1388 pdev = msi_desc_to_pci_dev(irq_data_get_msi_desc(data));
1389 dest = irq_data_get_effective_affinity_mask(data);
1391 hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
1392 channel = hbus->hdev->channel;
1393 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1395 goto return_null_message;
1397 /* Free any previous message that might have already been composed. */
1398 if (data->chip_data) {
1399 int_desc = data->chip_data;
1400 data->chip_data = NULL;
1401 hv_int_desc_free(hpdev, int_desc);
1404 int_desc = kzalloc(sizeof(*int_desc), GFP_ATOMIC);
1406 goto drop_reference;
1408 memset(&ctxt, 0, sizeof(ctxt));
1409 init_completion(&comp.comp_pkt.host_event);
1410 ctxt.pci_pkt.completion_func = hv_pci_compose_compl;
1411 ctxt.pci_pkt.compl_ctxt = ∁
1413 switch (hbus->protocol_version) {
1414 case PCI_PROTOCOL_VERSION_1_1:
1415 size = hv_compose_msi_req_v1(&ctxt.int_pkts.v1,
1417 hpdev->desc.win_slot.slot,
1421 case PCI_PROTOCOL_VERSION_1_2:
1422 case PCI_PROTOCOL_VERSION_1_3:
1423 size = hv_compose_msi_req_v2(&ctxt.int_pkts.v2,
1425 hpdev->desc.win_slot.slot,
1430 /* As we only negotiate protocol versions known to this driver,
1431 * this path should never hit. However, this is it not a hot
1432 * path so we print a message to aid future updates.
1434 dev_err(&hbus->hdev->device,
1435 "Unexpected vPCI protocol, update driver.");
1439 ret = vmbus_sendpacket(hpdev->hbus->hdev->channel, &ctxt.int_pkts,
1440 size, (unsigned long)&ctxt.pci_pkt,
1442 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1444 dev_err(&hbus->hdev->device,
1445 "Sending request for interrupt failed: 0x%x",
1446 comp.comp_pkt.completion_status);
1451 * Prevents hv_pci_onchannelcallback() from running concurrently
1454 tasklet_disable_in_atomic(&channel->callback_event);
1457 * Since this function is called with IRQ locks held, can't
1458 * do normal wait for completion; instead poll.
1460 while (!try_wait_for_completion(&comp.comp_pkt.host_event)) {
1461 unsigned long flags;
1463 /* 0xFFFF means an invalid PCI VENDOR ID. */
1464 if (hv_pcifront_get_vendor_id(hpdev) == 0xFFFF) {
1465 dev_err_once(&hbus->hdev->device,
1466 "the device has gone\n");
1467 goto enable_tasklet;
1471 * Make sure that the ring buffer data structure doesn't get
1472 * freed while we dereference the ring buffer pointer. Test
1473 * for the channel's onchannel_callback being NULL within a
1474 * sched_lock critical section. See also the inline comments
1475 * in vmbus_reset_channel_cb().
1477 spin_lock_irqsave(&channel->sched_lock, flags);
1478 if (unlikely(channel->onchannel_callback == NULL)) {
1479 spin_unlock_irqrestore(&channel->sched_lock, flags);
1480 goto enable_tasklet;
1482 hv_pci_onchannelcallback(hbus);
1483 spin_unlock_irqrestore(&channel->sched_lock, flags);
1485 if (hpdev->state == hv_pcichild_ejecting) {
1486 dev_err_once(&hbus->hdev->device,
1487 "the device is being ejected\n");
1488 goto enable_tasklet;
1494 tasklet_enable(&channel->callback_event);
1496 if (comp.comp_pkt.completion_status < 0) {
1497 dev_err(&hbus->hdev->device,
1498 "Request for interrupt failed: 0x%x",
1499 comp.comp_pkt.completion_status);
1504 * Record the assignment so that this can be unwound later. Using
1505 * irq_set_chip_data() here would be appropriate, but the lock it takes
1508 *int_desc = comp.int_desc;
1509 data->chip_data = int_desc;
1511 /* Pass up the result. */
1512 msg->address_hi = comp.int_desc.address >> 32;
1513 msg->address_lo = comp.int_desc.address & 0xffffffff;
1514 msg->data = comp.int_desc.data;
1516 put_pcichild(hpdev);
1520 tasklet_enable(&channel->callback_event);
1524 put_pcichild(hpdev);
1525 return_null_message:
1526 msg->address_hi = 0;
1527 msg->address_lo = 0;
1531 /* HW Interrupt Chip Descriptor */
1532 static struct irq_chip hv_msi_irq_chip = {
1533 .name = "Hyper-V PCIe MSI",
1534 .irq_compose_msi_msg = hv_compose_msi_msg,
1535 .irq_set_affinity = hv_set_affinity,
1536 .irq_ack = irq_chip_ack_parent,
1537 .irq_mask = hv_irq_mask,
1538 .irq_unmask = hv_irq_unmask,
1541 static struct msi_domain_ops hv_msi_ops = {
1542 .msi_prepare = pci_msi_prepare,
1543 .msi_free = hv_msi_free,
1547 * hv_pcie_init_irq_domain() - Initialize IRQ domain
1548 * @hbus: The root PCI bus
1550 * This function creates an IRQ domain which will be used for
1551 * interrupts from devices that have been passed through. These
1552 * devices only support MSI and MSI-X, not line-based interrupts
1553 * or simulations of line-based interrupts through PCIe's
1554 * fabric-layer messages. Because interrupts are remapped, we
1555 * can support multi-message MSI here.
1557 * Return: '0' on success and error value on failure
1559 static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus)
1561 hbus->msi_info.chip = &hv_msi_irq_chip;
1562 hbus->msi_info.ops = &hv_msi_ops;
1563 hbus->msi_info.flags = (MSI_FLAG_USE_DEF_DOM_OPS |
1564 MSI_FLAG_USE_DEF_CHIP_OPS | MSI_FLAG_MULTI_PCI_MSI |
1566 hbus->msi_info.handler = handle_edge_irq;
1567 hbus->msi_info.handler_name = "edge";
1568 hbus->msi_info.data = hbus;
1569 hbus->irq_domain = pci_msi_create_irq_domain(hbus->sysdata.fwnode,
1572 if (!hbus->irq_domain) {
1573 dev_err(&hbus->hdev->device,
1574 "Failed to build an MSI IRQ domain\n");
1582 * get_bar_size() - Get the address space consumed by a BAR
1583 * @bar_val: Value that a BAR returned after -1 was written
1586 * This function returns the size of the BAR, rounded up to 1
1587 * page. It has to be rounded up because the hypervisor's page
1588 * table entry that maps the BAR into the VM can't specify an
1589 * offset within a page. The invariant is that the hypervisor
1590 * must place any BARs of smaller than page length at the
1591 * beginning of a page.
1593 * Return: Size in bytes of the consumed MMIO space.
1595 static u64 get_bar_size(u64 bar_val)
1597 return round_up((1 + ~(bar_val & PCI_BASE_ADDRESS_MEM_MASK)),
1602 * survey_child_resources() - Total all MMIO requirements
1603 * @hbus: Root PCI bus, as understood by this driver
1605 static void survey_child_resources(struct hv_pcibus_device *hbus)
1607 struct hv_pci_dev *hpdev;
1608 resource_size_t bar_size = 0;
1609 unsigned long flags;
1610 struct completion *event;
1614 /* If nobody is waiting on the answer, don't compute it. */
1615 event = xchg(&hbus->survey_event, NULL);
1619 /* If the answer has already been computed, go with it. */
1620 if (hbus->low_mmio_space || hbus->high_mmio_space) {
1625 spin_lock_irqsave(&hbus->device_list_lock, flags);
1628 * Due to an interesting quirk of the PCI spec, all memory regions
1629 * for a child device are a power of 2 in size and aligned in memory,
1630 * so it's sufficient to just add them up without tracking alignment.
1632 list_for_each_entry(hpdev, &hbus->children, list_entry) {
1633 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
1634 if (hpdev->probed_bar[i] & PCI_BASE_ADDRESS_SPACE_IO)
1635 dev_err(&hbus->hdev->device,
1636 "There's an I/O BAR in this list!\n");
1638 if (hpdev->probed_bar[i] != 0) {
1640 * A probed BAR has all the upper bits set that
1644 bar_val = hpdev->probed_bar[i];
1645 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1647 ((u64)hpdev->probed_bar[++i] << 32);
1649 bar_val |= 0xffffffff00000000ULL;
1651 bar_size = get_bar_size(bar_val);
1653 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1654 hbus->high_mmio_space += bar_size;
1656 hbus->low_mmio_space += bar_size;
1661 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1666 * prepopulate_bars() - Fill in BARs with defaults
1667 * @hbus: Root PCI bus, as understood by this driver
1669 * The core PCI driver code seems much, much happier if the BARs
1670 * for a device have values upon first scan. So fill them in.
1671 * The algorithm below works down from large sizes to small,
1672 * attempting to pack the assignments optimally. The assumption,
1673 * enforced in other parts of the code, is that the beginning of
1674 * the memory-mapped I/O space will be aligned on the largest
1677 static void prepopulate_bars(struct hv_pcibus_device *hbus)
1679 resource_size_t high_size = 0;
1680 resource_size_t low_size = 0;
1681 resource_size_t high_base = 0;
1682 resource_size_t low_base = 0;
1683 resource_size_t bar_size;
1684 struct hv_pci_dev *hpdev;
1685 unsigned long flags;
1691 if (hbus->low_mmio_space) {
1692 low_size = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
1693 low_base = hbus->low_mmio_res->start;
1696 if (hbus->high_mmio_space) {
1698 (63 - __builtin_clzll(hbus->high_mmio_space));
1699 high_base = hbus->high_mmio_res->start;
1702 spin_lock_irqsave(&hbus->device_list_lock, flags);
1705 * Clear the memory enable bit, in case it's already set. This occurs
1706 * in the suspend path of hibernation, where the device is suspended,
1707 * resumed and suspended again: see hibernation_snapshot() and
1708 * hibernation_platform_enter().
1710 * If the memory enable bit is already set, Hyper-V silently ignores
1711 * the below BAR updates, and the related PCI device driver can not
1712 * work, because reading from the device register(s) always returns
1715 list_for_each_entry(hpdev, &hbus->children, list_entry) {
1716 _hv_pcifront_read_config(hpdev, PCI_COMMAND, 2, &command);
1717 command &= ~PCI_COMMAND_MEMORY;
1718 _hv_pcifront_write_config(hpdev, PCI_COMMAND, 2, command);
1721 /* Pick addresses for the BARs. */
1723 list_for_each_entry(hpdev, &hbus->children, list_entry) {
1724 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
1725 bar_val = hpdev->probed_bar[i];
1728 high = bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64;
1731 ((u64)hpdev->probed_bar[i + 1]
1734 bar_val |= 0xffffffffULL << 32;
1736 bar_size = get_bar_size(bar_val);
1738 if (high_size != bar_size) {
1742 _hv_pcifront_write_config(hpdev,
1743 PCI_BASE_ADDRESS_0 + (4 * i),
1745 (u32)(high_base & 0xffffff00));
1747 _hv_pcifront_write_config(hpdev,
1748 PCI_BASE_ADDRESS_0 + (4 * i),
1749 4, (u32)(high_base >> 32));
1750 high_base += bar_size;
1752 if (low_size != bar_size)
1754 _hv_pcifront_write_config(hpdev,
1755 PCI_BASE_ADDRESS_0 + (4 * i),
1757 (u32)(low_base & 0xffffff00));
1758 low_base += bar_size;
1761 if (high_size <= 1 && low_size <= 1) {
1762 /* Set the memory enable bit. */
1763 _hv_pcifront_read_config(hpdev, PCI_COMMAND, 2,
1765 command |= PCI_COMMAND_MEMORY;
1766 _hv_pcifront_write_config(hpdev, PCI_COMMAND, 2,
1774 } while (high_size || low_size);
1776 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1780 * Assign entries in sysfs pci slot directory.
1782 * Note that this function does not need to lock the children list
1783 * because it is called from pci_devices_present_work which
1784 * is serialized with hv_eject_device_work because they are on the
1785 * same ordered workqueue. Therefore hbus->children list will not change
1786 * even when pci_create_slot sleeps.
1788 static void hv_pci_assign_slots(struct hv_pcibus_device *hbus)
1790 struct hv_pci_dev *hpdev;
1791 char name[SLOT_NAME_SIZE];
1794 list_for_each_entry(hpdev, &hbus->children, list_entry) {
1795 if (hpdev->pci_slot)
1798 slot_nr = PCI_SLOT(wslot_to_devfn(hpdev->desc.win_slot.slot));
1799 snprintf(name, SLOT_NAME_SIZE, "%u", hpdev->desc.ser);
1800 hpdev->pci_slot = pci_create_slot(hbus->pci_bus, slot_nr,
1802 if (IS_ERR(hpdev->pci_slot)) {
1803 pr_warn("pci_create slot %s failed\n", name);
1804 hpdev->pci_slot = NULL;
1810 * Remove entries in sysfs pci slot directory.
1812 static void hv_pci_remove_slots(struct hv_pcibus_device *hbus)
1814 struct hv_pci_dev *hpdev;
1816 list_for_each_entry(hpdev, &hbus->children, list_entry) {
1817 if (!hpdev->pci_slot)
1819 pci_destroy_slot(hpdev->pci_slot);
1820 hpdev->pci_slot = NULL;
1825 * Set NUMA node for the devices on the bus
1827 static void hv_pci_assign_numa_node(struct hv_pcibus_device *hbus)
1829 struct pci_dev *dev;
1830 struct pci_bus *bus = hbus->pci_bus;
1831 struct hv_pci_dev *hv_dev;
1833 list_for_each_entry(dev, &bus->devices, bus_list) {
1834 hv_dev = get_pcichild_wslot(hbus, devfn_to_wslot(dev->devfn));
1838 if (hv_dev->desc.flags & HV_PCI_DEVICE_FLAG_NUMA_AFFINITY)
1839 set_dev_node(&dev->dev, hv_dev->desc.virtual_numa_node);
1841 put_pcichild(hv_dev);
1846 * create_root_hv_pci_bus() - Expose a new root PCI bus
1847 * @hbus: Root PCI bus, as understood by this driver
1849 * Return: 0 on success, -errno on failure
1851 static int create_root_hv_pci_bus(struct hv_pcibus_device *hbus)
1853 /* Register the device */
1854 hbus->pci_bus = pci_create_root_bus(&hbus->hdev->device,
1855 0, /* bus number is always zero */
1858 &hbus->resources_for_children);
1862 pci_lock_rescan_remove();
1863 pci_scan_child_bus(hbus->pci_bus);
1864 hv_pci_assign_numa_node(hbus);
1865 pci_bus_assign_resources(hbus->pci_bus);
1866 hv_pci_assign_slots(hbus);
1867 pci_bus_add_devices(hbus->pci_bus);
1868 pci_unlock_rescan_remove();
1869 hbus->state = hv_pcibus_installed;
1873 struct q_res_req_compl {
1874 struct completion host_event;
1875 struct hv_pci_dev *hpdev;
1879 * q_resource_requirements() - Query Resource Requirements
1880 * @context: The completion context.
1881 * @resp: The response that came from the host.
1882 * @resp_packet_size: The size in bytes of resp.
1884 * This function is invoked on completion of a Query Resource
1885 * Requirements packet.
1887 static void q_resource_requirements(void *context, struct pci_response *resp,
1888 int resp_packet_size)
1890 struct q_res_req_compl *completion = context;
1891 struct pci_q_res_req_response *q_res_req =
1892 (struct pci_q_res_req_response *)resp;
1895 if (resp->status < 0) {
1896 dev_err(&completion->hpdev->hbus->hdev->device,
1897 "query resource requirements failed: %x\n",
1900 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
1901 completion->hpdev->probed_bar[i] =
1902 q_res_req->probed_bar[i];
1906 complete(&completion->host_event);
1910 * new_pcichild_device() - Create a new child device
1911 * @hbus: The internal struct tracking this root PCI bus.
1912 * @desc: The information supplied so far from the host
1915 * This function creates the tracking structure for a new child
1916 * device and kicks off the process of figuring out what it is.
1918 * Return: Pointer to the new tracking struct
1920 static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
1921 struct hv_pcidev_description *desc)
1923 struct hv_pci_dev *hpdev;
1924 struct pci_child_message *res_req;
1925 struct q_res_req_compl comp_pkt;
1927 struct pci_packet init_packet;
1928 u8 buffer[sizeof(struct pci_child_message)];
1930 unsigned long flags;
1933 hpdev = kzalloc(sizeof(*hpdev), GFP_KERNEL);
1939 memset(&pkt, 0, sizeof(pkt));
1940 init_completion(&comp_pkt.host_event);
1941 comp_pkt.hpdev = hpdev;
1942 pkt.init_packet.compl_ctxt = &comp_pkt;
1943 pkt.init_packet.completion_func = q_resource_requirements;
1944 res_req = (struct pci_child_message *)&pkt.init_packet.message;
1945 res_req->message_type.type = PCI_QUERY_RESOURCE_REQUIREMENTS;
1946 res_req->wslot.slot = desc->win_slot.slot;
1948 ret = vmbus_sendpacket(hbus->hdev->channel, res_req,
1949 sizeof(struct pci_child_message),
1950 (unsigned long)&pkt.init_packet,
1952 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1956 if (wait_for_response(hbus->hdev, &comp_pkt.host_event))
1959 hpdev->desc = *desc;
1960 refcount_set(&hpdev->refs, 1);
1961 get_pcichild(hpdev);
1962 spin_lock_irqsave(&hbus->device_list_lock, flags);
1964 list_add_tail(&hpdev->list_entry, &hbus->children);
1965 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1974 * get_pcichild_wslot() - Find device from slot
1975 * @hbus: Root PCI bus, as understood by this driver
1976 * @wslot: Location on the bus
1978 * This function looks up a PCI device and returns the internal
1979 * representation of it. It acquires a reference on it, so that
1980 * the device won't be deleted while somebody is using it. The
1981 * caller is responsible for calling put_pcichild() to release
1984 * Return: Internal representation of a PCI device
1986 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
1989 unsigned long flags;
1990 struct hv_pci_dev *iter, *hpdev = NULL;
1992 spin_lock_irqsave(&hbus->device_list_lock, flags);
1993 list_for_each_entry(iter, &hbus->children, list_entry) {
1994 if (iter->desc.win_slot.slot == wslot) {
1996 get_pcichild(hpdev);
2000 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2006 * pci_devices_present_work() - Handle new list of child devices
2007 * @work: Work struct embedded in struct hv_dr_work
2009 * "Bus Relations" is the Windows term for "children of this
2010 * bus." The terminology is preserved here for people trying to
2011 * debug the interaction between Hyper-V and Linux. This
2012 * function is called when the parent partition reports a list
2013 * of functions that should be observed under this PCI Express
2016 * This function updates the list, and must tolerate being
2017 * called multiple times with the same information. The typical
2018 * number of child devices is one, with very atypical cases
2019 * involving three or four, so the algorithms used here can be
2020 * simple and inefficient.
2022 * It must also treat the omission of a previously observed device as
2023 * notification that the device no longer exists.
2025 * Note that this function is serialized with hv_eject_device_work(),
2026 * because both are pushed to the ordered workqueue hbus->wq.
2028 static void pci_devices_present_work(struct work_struct *work)
2032 struct hv_pcidev_description *new_desc;
2033 struct hv_pci_dev *hpdev;
2034 struct hv_pcibus_device *hbus;
2035 struct list_head removed;
2036 struct hv_dr_work *dr_wrk;
2037 struct hv_dr_state *dr = NULL;
2038 unsigned long flags;
2040 dr_wrk = container_of(work, struct hv_dr_work, wrk);
2044 INIT_LIST_HEAD(&removed);
2046 /* Pull this off the queue and process it if it was the last one. */
2047 spin_lock_irqsave(&hbus->device_list_lock, flags);
2048 while (!list_empty(&hbus->dr_list)) {
2049 dr = list_first_entry(&hbus->dr_list, struct hv_dr_state,
2051 list_del(&dr->list_entry);
2053 /* Throw this away if the list still has stuff in it. */
2054 if (!list_empty(&hbus->dr_list)) {
2059 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2064 /* First, mark all existing children as reported missing. */
2065 spin_lock_irqsave(&hbus->device_list_lock, flags);
2066 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2067 hpdev->reported_missing = true;
2069 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2071 /* Next, add back any reported devices. */
2072 for (child_no = 0; child_no < dr->device_count; child_no++) {
2074 new_desc = &dr->func[child_no];
2076 spin_lock_irqsave(&hbus->device_list_lock, flags);
2077 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2078 if ((hpdev->desc.win_slot.slot == new_desc->win_slot.slot) &&
2079 (hpdev->desc.v_id == new_desc->v_id) &&
2080 (hpdev->desc.d_id == new_desc->d_id) &&
2081 (hpdev->desc.ser == new_desc->ser)) {
2082 hpdev->reported_missing = false;
2086 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2089 hpdev = new_pcichild_device(hbus, new_desc);
2091 dev_err(&hbus->hdev->device,
2092 "couldn't record a child device.\n");
2096 /* Move missing children to a list on the stack. */
2097 spin_lock_irqsave(&hbus->device_list_lock, flags);
2100 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2101 if (hpdev->reported_missing) {
2103 put_pcichild(hpdev);
2104 list_move_tail(&hpdev->list_entry, &removed);
2109 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2111 /* Delete everything that should no longer exist. */
2112 while (!list_empty(&removed)) {
2113 hpdev = list_first_entry(&removed, struct hv_pci_dev,
2115 list_del(&hpdev->list_entry);
2117 if (hpdev->pci_slot)
2118 pci_destroy_slot(hpdev->pci_slot);
2120 put_pcichild(hpdev);
2123 switch (hbus->state) {
2124 case hv_pcibus_installed:
2126 * Tell the core to rescan bus
2127 * because there may have been changes.
2129 pci_lock_rescan_remove();
2130 pci_scan_child_bus(hbus->pci_bus);
2131 hv_pci_assign_numa_node(hbus);
2132 hv_pci_assign_slots(hbus);
2133 pci_unlock_rescan_remove();
2136 case hv_pcibus_init:
2137 case hv_pcibus_probed:
2138 survey_child_resources(hbus);
2149 * hv_pci_start_relations_work() - Queue work to start device discovery
2150 * @hbus: Root PCI bus, as understood by this driver
2151 * @dr: The list of children returned from host
2153 * Return: 0 on success, -errno on failure
2155 static int hv_pci_start_relations_work(struct hv_pcibus_device *hbus,
2156 struct hv_dr_state *dr)
2158 struct hv_dr_work *dr_wrk;
2159 unsigned long flags;
2162 if (hbus->state == hv_pcibus_removing) {
2163 dev_info(&hbus->hdev->device,
2164 "PCI VMBus BUS_RELATIONS: ignored\n");
2168 dr_wrk = kzalloc(sizeof(*dr_wrk), GFP_NOWAIT);
2172 INIT_WORK(&dr_wrk->wrk, pci_devices_present_work);
2175 spin_lock_irqsave(&hbus->device_list_lock, flags);
2177 * If pending_dr is true, we have already queued a work,
2178 * which will see the new dr. Otherwise, we need to
2181 pending_dr = !list_empty(&hbus->dr_list);
2182 list_add_tail(&dr->list_entry, &hbus->dr_list);
2183 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2188 queue_work(hbus->wq, &dr_wrk->wrk);
2194 * hv_pci_devices_present() - Handle list of new children
2195 * @hbus: Root PCI bus, as understood by this driver
2196 * @relations: Packet from host listing children
2198 * Process a new list of devices on the bus. The list of devices is
2199 * discovered by VSP and sent to us via VSP message PCI_BUS_RELATIONS,
2200 * whenever a new list of devices for this bus appears.
2202 static void hv_pci_devices_present(struct hv_pcibus_device *hbus,
2203 struct pci_bus_relations *relations)
2205 struct hv_dr_state *dr;
2208 dr = kzalloc(struct_size(dr, func, relations->device_count),
2213 dr->device_count = relations->device_count;
2214 for (i = 0; i < dr->device_count; i++) {
2215 dr->func[i].v_id = relations->func[i].v_id;
2216 dr->func[i].d_id = relations->func[i].d_id;
2217 dr->func[i].rev = relations->func[i].rev;
2218 dr->func[i].prog_intf = relations->func[i].prog_intf;
2219 dr->func[i].subclass = relations->func[i].subclass;
2220 dr->func[i].base_class = relations->func[i].base_class;
2221 dr->func[i].subsystem_id = relations->func[i].subsystem_id;
2222 dr->func[i].win_slot = relations->func[i].win_slot;
2223 dr->func[i].ser = relations->func[i].ser;
2226 if (hv_pci_start_relations_work(hbus, dr))
2231 * hv_pci_devices_present2() - Handle list of new children
2232 * @hbus: Root PCI bus, as understood by this driver
2233 * @relations: Packet from host listing children
2235 * This function is the v2 version of hv_pci_devices_present()
2237 static void hv_pci_devices_present2(struct hv_pcibus_device *hbus,
2238 struct pci_bus_relations2 *relations)
2240 struct hv_dr_state *dr;
2243 dr = kzalloc(struct_size(dr, func, relations->device_count),
2248 dr->device_count = relations->device_count;
2249 for (i = 0; i < dr->device_count; i++) {
2250 dr->func[i].v_id = relations->func[i].v_id;
2251 dr->func[i].d_id = relations->func[i].d_id;
2252 dr->func[i].rev = relations->func[i].rev;
2253 dr->func[i].prog_intf = relations->func[i].prog_intf;
2254 dr->func[i].subclass = relations->func[i].subclass;
2255 dr->func[i].base_class = relations->func[i].base_class;
2256 dr->func[i].subsystem_id = relations->func[i].subsystem_id;
2257 dr->func[i].win_slot = relations->func[i].win_slot;
2258 dr->func[i].ser = relations->func[i].ser;
2259 dr->func[i].flags = relations->func[i].flags;
2260 dr->func[i].virtual_numa_node =
2261 relations->func[i].virtual_numa_node;
2264 if (hv_pci_start_relations_work(hbus, dr))
2269 * hv_eject_device_work() - Asynchronously handles ejection
2270 * @work: Work struct embedded in internal device struct
2272 * This function handles ejecting a device. Windows will
2273 * attempt to gracefully eject a device, waiting 60 seconds to
2274 * hear back from the guest OS that this completed successfully.
2275 * If this timer expires, the device will be forcibly removed.
2277 static void hv_eject_device_work(struct work_struct *work)
2279 struct pci_eject_response *ejct_pkt;
2280 struct hv_pcibus_device *hbus;
2281 struct hv_pci_dev *hpdev;
2282 struct pci_dev *pdev;
2283 unsigned long flags;
2286 struct pci_packet pkt;
2287 u8 buffer[sizeof(struct pci_eject_response)];
2290 hpdev = container_of(work, struct hv_pci_dev, wrk);
2293 WARN_ON(hpdev->state != hv_pcichild_ejecting);
2296 * Ejection can come before or after the PCI bus has been set up, so
2297 * attempt to find it and tear down the bus state, if it exists. This
2298 * must be done without constructs like pci_domain_nr(hbus->pci_bus)
2299 * because hbus->pci_bus may not exist yet.
2301 wslot = wslot_to_devfn(hpdev->desc.win_slot.slot);
2302 pdev = pci_get_domain_bus_and_slot(hbus->sysdata.domain, 0, wslot);
2304 pci_lock_rescan_remove();
2305 pci_stop_and_remove_bus_device(pdev);
2307 pci_unlock_rescan_remove();
2310 spin_lock_irqsave(&hbus->device_list_lock, flags);
2311 list_del(&hpdev->list_entry);
2312 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2314 if (hpdev->pci_slot)
2315 pci_destroy_slot(hpdev->pci_slot);
2317 memset(&ctxt, 0, sizeof(ctxt));
2318 ejct_pkt = (struct pci_eject_response *)&ctxt.pkt.message;
2319 ejct_pkt->message_type.type = PCI_EJECTION_COMPLETE;
2320 ejct_pkt->wslot.slot = hpdev->desc.win_slot.slot;
2321 vmbus_sendpacket(hbus->hdev->channel, ejct_pkt,
2322 sizeof(*ejct_pkt), (unsigned long)&ctxt.pkt,
2323 VM_PKT_DATA_INBAND, 0);
2325 /* For the get_pcichild() in hv_pci_eject_device() */
2326 put_pcichild(hpdev);
2327 /* For the two refs got in new_pcichild_device() */
2328 put_pcichild(hpdev);
2329 put_pcichild(hpdev);
2330 /* hpdev has been freed. Do not use it any more. */
2334 * hv_pci_eject_device() - Handles device ejection
2335 * @hpdev: Internal device tracking struct
2337 * This function is invoked when an ejection packet arrives. It
2338 * just schedules work so that we don't re-enter the packet
2339 * delivery code handling the ejection.
2341 static void hv_pci_eject_device(struct hv_pci_dev *hpdev)
2343 struct hv_pcibus_device *hbus = hpdev->hbus;
2344 struct hv_device *hdev = hbus->hdev;
2346 if (hbus->state == hv_pcibus_removing) {
2347 dev_info(&hdev->device, "PCI VMBus EJECT: ignored\n");
2351 hpdev->state = hv_pcichild_ejecting;
2352 get_pcichild(hpdev);
2353 INIT_WORK(&hpdev->wrk, hv_eject_device_work);
2354 queue_work(hbus->wq, &hpdev->wrk);
2358 * hv_pci_onchannelcallback() - Handles incoming packets
2359 * @context: Internal bus tracking struct
2361 * This function is invoked whenever the host sends a packet to
2362 * this channel (which is private to this root PCI bus).
2364 static void hv_pci_onchannelcallback(void *context)
2366 const int packet_size = 0x100;
2368 struct hv_pcibus_device *hbus = context;
2371 struct vmpacket_descriptor *desc;
2372 unsigned char *buffer;
2373 int bufferlen = packet_size;
2374 struct pci_packet *comp_packet;
2375 struct pci_response *response;
2376 struct pci_incoming_message *new_message;
2377 struct pci_bus_relations *bus_rel;
2378 struct pci_bus_relations2 *bus_rel2;
2379 struct pci_dev_inval_block *inval;
2380 struct pci_dev_incoming *dev_message;
2381 struct hv_pci_dev *hpdev;
2383 buffer = kmalloc(bufferlen, GFP_ATOMIC);
2388 ret = vmbus_recvpacket_raw(hbus->hdev->channel, buffer,
2389 bufferlen, &bytes_recvd, &req_id);
2391 if (ret == -ENOBUFS) {
2393 /* Handle large packet */
2394 bufferlen = bytes_recvd;
2395 buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
2401 /* Zero length indicates there are no more packets. */
2402 if (ret || !bytes_recvd)
2406 * All incoming packets must be at least as large as a
2409 if (bytes_recvd <= sizeof(struct pci_response))
2411 desc = (struct vmpacket_descriptor *)buffer;
2413 switch (desc->type) {
2417 * The host is trusted, and thus it's safe to interpret
2418 * this transaction ID as a pointer.
2420 comp_packet = (struct pci_packet *)req_id;
2421 response = (struct pci_response *)buffer;
2422 comp_packet->completion_func(comp_packet->compl_ctxt,
2427 case VM_PKT_DATA_INBAND:
2429 new_message = (struct pci_incoming_message *)buffer;
2430 switch (new_message->message_type.type) {
2431 case PCI_BUS_RELATIONS:
2433 bus_rel = (struct pci_bus_relations *)buffer;
2435 struct_size(bus_rel, func,
2436 bus_rel->device_count)) {
2437 dev_err(&hbus->hdev->device,
2438 "bus relations too small\n");
2442 hv_pci_devices_present(hbus, bus_rel);
2445 case PCI_BUS_RELATIONS2:
2447 bus_rel2 = (struct pci_bus_relations2 *)buffer;
2449 struct_size(bus_rel2, func,
2450 bus_rel2->device_count)) {
2451 dev_err(&hbus->hdev->device,
2452 "bus relations v2 too small\n");
2456 hv_pci_devices_present2(hbus, bus_rel2);
2461 dev_message = (struct pci_dev_incoming *)buffer;
2462 hpdev = get_pcichild_wslot(hbus,
2463 dev_message->wslot.slot);
2465 hv_pci_eject_device(hpdev);
2466 put_pcichild(hpdev);
2470 case PCI_INVALIDATE_BLOCK:
2472 inval = (struct pci_dev_inval_block *)buffer;
2473 hpdev = get_pcichild_wslot(hbus,
2476 if (hpdev->block_invalidate) {
2477 hpdev->block_invalidate(
2478 hpdev->invalidate_context,
2481 put_pcichild(hpdev);
2486 dev_warn(&hbus->hdev->device,
2487 "Unimplemented protocol message %x\n",
2488 new_message->message_type.type);
2494 dev_err(&hbus->hdev->device,
2495 "unhandled packet type %d, tid %llx len %d\n",
2496 desc->type, req_id, bytes_recvd);
2505 * hv_pci_protocol_negotiation() - Set up protocol
2506 * @hdev: VMBus's tracking struct for this root PCI bus.
2507 * @version: Array of supported channel protocol versions in
2508 * the order of probing - highest go first.
2509 * @num_version: Number of elements in the version array.
2511 * This driver is intended to support running on Windows 10
2512 * (server) and later versions. It will not run on earlier
2513 * versions, as they assume that many of the operations which
2514 * Linux needs accomplished with a spinlock held were done via
2515 * asynchronous messaging via VMBus. Windows 10 increases the
2516 * surface area of PCI emulation so that these actions can take
2517 * place by suspending a virtual processor for their duration.
2519 * This function negotiates the channel protocol version,
2520 * failing if the host doesn't support the necessary protocol
2523 static int hv_pci_protocol_negotiation(struct hv_device *hdev,
2524 enum pci_protocol_version_t version[],
2527 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2528 struct pci_version_request *version_req;
2529 struct hv_pci_compl comp_pkt;
2530 struct pci_packet *pkt;
2535 * Initiate the handshake with the host and negotiate
2536 * a version that the host can support. We start with the
2537 * highest version number and go down if the host cannot
2540 pkt = kzalloc(sizeof(*pkt) + sizeof(*version_req), GFP_KERNEL);
2544 init_completion(&comp_pkt.host_event);
2545 pkt->completion_func = hv_pci_generic_compl;
2546 pkt->compl_ctxt = &comp_pkt;
2547 version_req = (struct pci_version_request *)&pkt->message;
2548 version_req->message_type.type = PCI_QUERY_PROTOCOL_VERSION;
2550 for (i = 0; i < num_version; i++) {
2551 version_req->protocol_version = version[i];
2552 ret = vmbus_sendpacket(hdev->channel, version_req,
2553 sizeof(struct pci_version_request),
2554 (unsigned long)pkt, VM_PKT_DATA_INBAND,
2555 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2557 ret = wait_for_response(hdev, &comp_pkt.host_event);
2560 dev_err(&hdev->device,
2561 "PCI Pass-through VSP failed to request version: %d",
2566 if (comp_pkt.completion_status >= 0) {
2567 hbus->protocol_version = version[i];
2568 dev_info(&hdev->device,
2569 "PCI VMBus probing: Using version %#x\n",
2570 hbus->protocol_version);
2574 if (comp_pkt.completion_status != STATUS_REVISION_MISMATCH) {
2575 dev_err(&hdev->device,
2576 "PCI Pass-through VSP failed version request: %#x",
2577 comp_pkt.completion_status);
2582 reinit_completion(&comp_pkt.host_event);
2585 dev_err(&hdev->device,
2586 "PCI pass-through VSP failed to find supported version");
2595 * hv_pci_free_bridge_windows() - Release memory regions for the
2597 * @hbus: Root PCI bus, as understood by this driver
2599 static void hv_pci_free_bridge_windows(struct hv_pcibus_device *hbus)
2602 * Set the resources back to the way they looked when they
2603 * were allocated by setting IORESOURCE_BUSY again.
2606 if (hbus->low_mmio_space && hbus->low_mmio_res) {
2607 hbus->low_mmio_res->flags |= IORESOURCE_BUSY;
2608 vmbus_free_mmio(hbus->low_mmio_res->start,
2609 resource_size(hbus->low_mmio_res));
2612 if (hbus->high_mmio_space && hbus->high_mmio_res) {
2613 hbus->high_mmio_res->flags |= IORESOURCE_BUSY;
2614 vmbus_free_mmio(hbus->high_mmio_res->start,
2615 resource_size(hbus->high_mmio_res));
2620 * hv_pci_allocate_bridge_windows() - Allocate memory regions
2622 * @hbus: Root PCI bus, as understood by this driver
2624 * This function calls vmbus_allocate_mmio(), which is itself a
2625 * bit of a compromise. Ideally, we might change the pnp layer
2626 * in the kernel such that it comprehends either PCI devices
2627 * which are "grandchildren of ACPI," with some intermediate bus
2628 * node (in this case, VMBus) or change it such that it
2629 * understands VMBus. The pnp layer, however, has been declared
2630 * deprecated, and not subject to change.
2632 * The workaround, implemented here, is to ask VMBus to allocate
2633 * MMIO space for this bus. VMBus itself knows which ranges are
2634 * appropriate by looking at its own ACPI objects. Then, after
2635 * these ranges are claimed, they're modified to look like they
2636 * would have looked if the ACPI and pnp code had allocated
2637 * bridge windows. These descriptors have to exist in this form
2638 * in order to satisfy the code which will get invoked when the
2639 * endpoint PCI function driver calls request_mem_region() or
2640 * request_mem_region_exclusive().
2642 * Return: 0 on success, -errno on failure
2644 static int hv_pci_allocate_bridge_windows(struct hv_pcibus_device *hbus)
2646 resource_size_t align;
2649 if (hbus->low_mmio_space) {
2650 align = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
2651 ret = vmbus_allocate_mmio(&hbus->low_mmio_res, hbus->hdev, 0,
2652 (u64)(u32)0xffffffff,
2653 hbus->low_mmio_space,
2656 dev_err(&hbus->hdev->device,
2657 "Need %#llx of low MMIO space. Consider reconfiguring the VM.\n",
2658 hbus->low_mmio_space);
2662 /* Modify this resource to become a bridge window. */
2663 hbus->low_mmio_res->flags |= IORESOURCE_WINDOW;
2664 hbus->low_mmio_res->flags &= ~IORESOURCE_BUSY;
2665 pci_add_resource(&hbus->resources_for_children,
2666 hbus->low_mmio_res);
2669 if (hbus->high_mmio_space) {
2670 align = 1ULL << (63 - __builtin_clzll(hbus->high_mmio_space));
2671 ret = vmbus_allocate_mmio(&hbus->high_mmio_res, hbus->hdev,
2673 hbus->high_mmio_space, align,
2676 dev_err(&hbus->hdev->device,
2677 "Need %#llx of high MMIO space. Consider reconfiguring the VM.\n",
2678 hbus->high_mmio_space);
2679 goto release_low_mmio;
2682 /* Modify this resource to become a bridge window. */
2683 hbus->high_mmio_res->flags |= IORESOURCE_WINDOW;
2684 hbus->high_mmio_res->flags &= ~IORESOURCE_BUSY;
2685 pci_add_resource(&hbus->resources_for_children,
2686 hbus->high_mmio_res);
2692 if (hbus->low_mmio_res) {
2693 vmbus_free_mmio(hbus->low_mmio_res->start,
2694 resource_size(hbus->low_mmio_res));
2701 * hv_allocate_config_window() - Find MMIO space for PCI Config
2702 * @hbus: Root PCI bus, as understood by this driver
2704 * This function claims memory-mapped I/O space for accessing
2705 * configuration space for the functions on this bus.
2707 * Return: 0 on success, -errno on failure
2709 static int hv_allocate_config_window(struct hv_pcibus_device *hbus)
2714 * Set up a region of MMIO space to use for accessing configuration
2717 ret = vmbus_allocate_mmio(&hbus->mem_config, hbus->hdev, 0, -1,
2718 PCI_CONFIG_MMIO_LENGTH, 0x1000, false);
2723 * vmbus_allocate_mmio() gets used for allocating both device endpoint
2724 * resource claims (those which cannot be overlapped) and the ranges
2725 * which are valid for the children of this bus, which are intended
2726 * to be overlapped by those children. Set the flag on this claim
2727 * meaning that this region can't be overlapped.
2730 hbus->mem_config->flags |= IORESOURCE_BUSY;
2735 static void hv_free_config_window(struct hv_pcibus_device *hbus)
2737 vmbus_free_mmio(hbus->mem_config->start, PCI_CONFIG_MMIO_LENGTH);
2740 static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs);
2743 * hv_pci_enter_d0() - Bring the "bus" into the D0 power state
2744 * @hdev: VMBus's tracking struct for this root PCI bus
2746 * Return: 0 on success, -errno on failure
2748 static int hv_pci_enter_d0(struct hv_device *hdev)
2750 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2751 struct pci_bus_d0_entry *d0_entry;
2752 struct hv_pci_compl comp_pkt;
2753 struct pci_packet *pkt;
2757 * Tell the host that the bus is ready to use, and moved into the
2758 * powered-on state. This includes telling the host which region
2759 * of memory-mapped I/O space has been chosen for configuration space
2762 pkt = kzalloc(sizeof(*pkt) + sizeof(*d0_entry), GFP_KERNEL);
2766 init_completion(&comp_pkt.host_event);
2767 pkt->completion_func = hv_pci_generic_compl;
2768 pkt->compl_ctxt = &comp_pkt;
2769 d0_entry = (struct pci_bus_d0_entry *)&pkt->message;
2770 d0_entry->message_type.type = PCI_BUS_D0ENTRY;
2771 d0_entry->mmio_base = hbus->mem_config->start;
2773 ret = vmbus_sendpacket(hdev->channel, d0_entry, sizeof(*d0_entry),
2774 (unsigned long)pkt, VM_PKT_DATA_INBAND,
2775 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2777 ret = wait_for_response(hdev, &comp_pkt.host_event);
2782 if (comp_pkt.completion_status < 0) {
2783 dev_err(&hdev->device,
2784 "PCI Pass-through VSP failed D0 Entry with status %x\n",
2785 comp_pkt.completion_status);
2798 * hv_pci_query_relations() - Ask host to send list of child
2800 * @hdev: VMBus's tracking struct for this root PCI bus
2802 * Return: 0 on success, -errno on failure
2804 static int hv_pci_query_relations(struct hv_device *hdev)
2806 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2807 struct pci_message message;
2808 struct completion comp;
2811 /* Ask the host to send along the list of child devices */
2812 init_completion(&comp);
2813 if (cmpxchg(&hbus->survey_event, NULL, &comp))
2816 memset(&message, 0, sizeof(message));
2817 message.type = PCI_QUERY_BUS_RELATIONS;
2819 ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
2820 0, VM_PKT_DATA_INBAND, 0);
2822 ret = wait_for_response(hdev, &comp);
2828 * hv_send_resources_allocated() - Report local resource choices
2829 * @hdev: VMBus's tracking struct for this root PCI bus
2831 * The host OS is expecting to be sent a request as a message
2832 * which contains all the resources that the device will use.
2833 * The response contains those same resources, "translated"
2834 * which is to say, the values which should be used by the
2835 * hardware, when it delivers an interrupt. (MMIO resources are
2836 * used in local terms.) This is nice for Windows, and lines up
2837 * with the FDO/PDO split, which doesn't exist in Linux. Linux
2838 * is deeply expecting to scan an emulated PCI configuration
2839 * space. So this message is sent here only to drive the state
2840 * machine on the host forward.
2842 * Return: 0 on success, -errno on failure
2844 static int hv_send_resources_allocated(struct hv_device *hdev)
2846 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2847 struct pci_resources_assigned *res_assigned;
2848 struct pci_resources_assigned2 *res_assigned2;
2849 struct hv_pci_compl comp_pkt;
2850 struct hv_pci_dev *hpdev;
2851 struct pci_packet *pkt;
2856 size_res = (hbus->protocol_version < PCI_PROTOCOL_VERSION_1_2)
2857 ? sizeof(*res_assigned) : sizeof(*res_assigned2);
2859 pkt = kmalloc(sizeof(*pkt) + size_res, GFP_KERNEL);
2865 for (wslot = 0; wslot < 256; wslot++) {
2866 hpdev = get_pcichild_wslot(hbus, wslot);
2870 memset(pkt, 0, sizeof(*pkt) + size_res);
2871 init_completion(&comp_pkt.host_event);
2872 pkt->completion_func = hv_pci_generic_compl;
2873 pkt->compl_ctxt = &comp_pkt;
2875 if (hbus->protocol_version < PCI_PROTOCOL_VERSION_1_2) {
2877 (struct pci_resources_assigned *)&pkt->message;
2878 res_assigned->message_type.type =
2879 PCI_RESOURCES_ASSIGNED;
2880 res_assigned->wslot.slot = hpdev->desc.win_slot.slot;
2883 (struct pci_resources_assigned2 *)&pkt->message;
2884 res_assigned2->message_type.type =
2885 PCI_RESOURCES_ASSIGNED2;
2886 res_assigned2->wslot.slot = hpdev->desc.win_slot.slot;
2888 put_pcichild(hpdev);
2890 ret = vmbus_sendpacket(hdev->channel, &pkt->message,
2891 size_res, (unsigned long)pkt,
2893 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2895 ret = wait_for_response(hdev, &comp_pkt.host_event);
2899 if (comp_pkt.completion_status < 0) {
2901 dev_err(&hdev->device,
2902 "resource allocated returned 0x%x",
2903 comp_pkt.completion_status);
2907 hbus->wslot_res_allocated = wslot;
2915 * hv_send_resources_released() - Report local resources
2917 * @hdev: VMBus's tracking struct for this root PCI bus
2919 * Return: 0 on success, -errno on failure
2921 static int hv_send_resources_released(struct hv_device *hdev)
2923 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2924 struct pci_child_message pkt;
2925 struct hv_pci_dev *hpdev;
2929 for (wslot = hbus->wslot_res_allocated; wslot >= 0; wslot--) {
2930 hpdev = get_pcichild_wslot(hbus, wslot);
2934 memset(&pkt, 0, sizeof(pkt));
2935 pkt.message_type.type = PCI_RESOURCES_RELEASED;
2936 pkt.wslot.slot = hpdev->desc.win_slot.slot;
2938 put_pcichild(hpdev);
2940 ret = vmbus_sendpacket(hdev->channel, &pkt, sizeof(pkt), 0,
2941 VM_PKT_DATA_INBAND, 0);
2945 hbus->wslot_res_allocated = wslot - 1;
2948 hbus->wslot_res_allocated = -1;
2953 #define HVPCI_DOM_MAP_SIZE (64 * 1024)
2954 static DECLARE_BITMAP(hvpci_dom_map, HVPCI_DOM_MAP_SIZE);
2957 * PCI domain number 0 is used by emulated devices on Gen1 VMs, so define 0
2958 * as invalid for passthrough PCI devices of this driver.
2960 #define HVPCI_DOM_INVALID 0
2963 * hv_get_dom_num() - Get a valid PCI domain number
2964 * Check if the PCI domain number is in use, and return another number if
2967 * @dom: Requested domain number
2969 * return: domain number on success, HVPCI_DOM_INVALID on failure
2971 static u16 hv_get_dom_num(u16 dom)
2975 if (test_and_set_bit(dom, hvpci_dom_map) == 0)
2978 for_each_clear_bit(i, hvpci_dom_map, HVPCI_DOM_MAP_SIZE) {
2979 if (test_and_set_bit(i, hvpci_dom_map) == 0)
2983 return HVPCI_DOM_INVALID;
2987 * hv_put_dom_num() - Mark the PCI domain number as free
2988 * @dom: Domain number to be freed
2990 static void hv_put_dom_num(u16 dom)
2992 clear_bit(dom, hvpci_dom_map);
2996 * hv_pci_probe() - New VMBus channel probe, for a root PCI bus
2997 * @hdev: VMBus's tracking struct for this root PCI bus
2998 * @dev_id: Identifies the device itself
3000 * Return: 0 on success, -errno on failure
3002 static int hv_pci_probe(struct hv_device *hdev,
3003 const struct hv_vmbus_device_id *dev_id)
3005 struct hv_pcibus_device *hbus;
3008 bool enter_d0_retry = true;
3012 * hv_pcibus_device contains the hypercall arguments for retargeting in
3013 * hv_irq_unmask(). Those must not cross a page boundary.
3015 BUILD_BUG_ON(sizeof(*hbus) > HV_HYP_PAGE_SIZE);
3018 * With the recent 59bb47985c1d ("mm, sl[aou]b: guarantee natural
3019 * alignment for kmalloc(power-of-two)"), kzalloc() is able to allocate
3020 * a 4KB buffer that is guaranteed to be 4KB-aligned. Here the size and
3021 * alignment of hbus is important because hbus's field
3022 * retarget_msi_interrupt_params must not cross a 4KB page boundary.
3024 * Here we prefer kzalloc to get_zeroed_page(), because a buffer
3025 * allocated by the latter is not tracked and scanned by kmemleak, and
3026 * hence kmemleak reports the pointer contained in the hbus buffer
3027 * (i.e. the hpdev struct, which is created in new_pcichild_device() and
3028 * is tracked by hbus->children) as memory leak (false positive).
3030 * If the kernel doesn't have 59bb47985c1d, get_zeroed_page() *must* be
3031 * used to allocate the hbus buffer and we can avoid the kmemleak false
3032 * positive by using kmemleak_alloc() and kmemleak_free() to ask
3033 * kmemleak to track and scan the hbus buffer.
3035 hbus = kzalloc(HV_HYP_PAGE_SIZE, GFP_KERNEL);
3038 hbus->state = hv_pcibus_init;
3039 hbus->wslot_res_allocated = -1;
3042 * The PCI bus "domain" is what is called "segment" in ACPI and other
3043 * specs. Pull it from the instance ID, to get something usually
3044 * unique. In rare cases of collision, we will find out another number
3047 * Note that, since this code only runs in a Hyper-V VM, Hyper-V
3048 * together with this guest driver can guarantee that (1) The only
3049 * domain used by Gen1 VMs for something that looks like a physical
3050 * PCI bus (which is actually emulated by the hypervisor) is domain 0.
3051 * (2) There will be no overlap between domains (after fixing possible
3052 * collisions) in the same VM.
3054 dom_req = hdev->dev_instance.b[5] << 8 | hdev->dev_instance.b[4];
3055 dom = hv_get_dom_num(dom_req);
3057 if (dom == HVPCI_DOM_INVALID) {
3058 dev_err(&hdev->device,
3059 "Unable to use dom# 0x%hx or other numbers", dom_req);
3065 dev_info(&hdev->device,
3066 "PCI dom# 0x%hx has collision, using 0x%hx",
3069 hbus->sysdata.domain = dom;
3072 INIT_LIST_HEAD(&hbus->children);
3073 INIT_LIST_HEAD(&hbus->dr_list);
3074 INIT_LIST_HEAD(&hbus->resources_for_children);
3075 spin_lock_init(&hbus->config_lock);
3076 spin_lock_init(&hbus->device_list_lock);
3077 spin_lock_init(&hbus->retarget_msi_interrupt_lock);
3078 hbus->wq = alloc_ordered_workqueue("hv_pci_%x", 0,
3079 hbus->sysdata.domain);
3085 ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
3086 hv_pci_onchannelcallback, hbus);
3090 hv_set_drvdata(hdev, hbus);
3092 ret = hv_pci_protocol_negotiation(hdev, pci_protocol_versions,
3093 ARRAY_SIZE(pci_protocol_versions));
3097 ret = hv_allocate_config_window(hbus);
3101 hbus->cfg_addr = ioremap(hbus->mem_config->start,
3102 PCI_CONFIG_MMIO_LENGTH);
3103 if (!hbus->cfg_addr) {
3104 dev_err(&hdev->device,
3105 "Unable to map a virtual address for config space\n");
3110 name = kasprintf(GFP_KERNEL, "%pUL", &hdev->dev_instance);
3116 hbus->sysdata.fwnode = irq_domain_alloc_named_fwnode(name);
3118 if (!hbus->sysdata.fwnode) {
3123 ret = hv_pcie_init_irq_domain(hbus);
3128 ret = hv_pci_query_relations(hdev);
3130 goto free_irq_domain;
3132 ret = hv_pci_enter_d0(hdev);
3134 * In certain case (Kdump) the pci device of interest was
3135 * not cleanly shut down and resource is still held on host
3136 * side, the host could return invalid device status.
3137 * We need to explicitly request host to release the resource
3138 * and try to enter D0 again.
3139 * Since the hv_pci_bus_exit() call releases structures
3140 * of all its child devices, we need to start the retry from
3141 * hv_pci_query_relations() call, requesting host to send
3142 * the synchronous child device relations message before this
3143 * information is needed in hv_send_resources_allocated()
3146 if (ret == -EPROTO && enter_d0_retry) {
3147 enter_d0_retry = false;
3149 dev_err(&hdev->device, "Retrying D0 Entry\n");
3152 * Hv_pci_bus_exit() calls hv_send_resources_released()
3153 * to free up resources of its child devices.
3154 * In the kdump kernel we need to set the
3155 * wslot_res_allocated to 255 so it scans all child
3156 * devices to release resources allocated in the
3157 * normal kernel before panic happened.
3159 hbus->wslot_res_allocated = 255;
3160 ret = hv_pci_bus_exit(hdev, true);
3165 dev_err(&hdev->device,
3166 "Retrying D0 failed with ret %d\n", ret);
3169 goto free_irq_domain;
3171 ret = hv_pci_allocate_bridge_windows(hbus);
3175 ret = hv_send_resources_allocated(hdev);
3179 prepopulate_bars(hbus);
3181 hbus->state = hv_pcibus_probed;
3183 ret = create_root_hv_pci_bus(hbus);
3190 hv_pci_free_bridge_windows(hbus);
3192 (void) hv_pci_bus_exit(hdev, true);
3194 irq_domain_remove(hbus->irq_domain);
3196 irq_domain_free_fwnode(hbus->sysdata.fwnode);
3198 iounmap(hbus->cfg_addr);
3200 hv_free_config_window(hbus);
3202 vmbus_close(hdev->channel);
3204 destroy_workqueue(hbus->wq);
3206 hv_put_dom_num(hbus->sysdata.domain);
3212 static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs)
3214 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3216 struct pci_packet teardown_packet;
3217 u8 buffer[sizeof(struct pci_message)];
3219 struct hv_pci_compl comp_pkt;
3220 struct hv_pci_dev *hpdev, *tmp;
3221 unsigned long flags;
3225 * After the host sends the RESCIND_CHANNEL message, it doesn't
3226 * access the per-channel ringbuffer any longer.
3228 if (hdev->channel->rescind)
3232 /* Delete any children which might still exist. */
3233 spin_lock_irqsave(&hbus->device_list_lock, flags);
3234 list_for_each_entry_safe(hpdev, tmp, &hbus->children, list_entry) {
3235 list_del(&hpdev->list_entry);
3236 if (hpdev->pci_slot)
3237 pci_destroy_slot(hpdev->pci_slot);
3238 /* For the two refs got in new_pcichild_device() */
3239 put_pcichild(hpdev);
3240 put_pcichild(hpdev);
3242 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
3245 ret = hv_send_resources_released(hdev);
3247 dev_err(&hdev->device,
3248 "Couldn't send resources released packet(s)\n");
3252 memset(&pkt.teardown_packet, 0, sizeof(pkt.teardown_packet));
3253 init_completion(&comp_pkt.host_event);
3254 pkt.teardown_packet.completion_func = hv_pci_generic_compl;
3255 pkt.teardown_packet.compl_ctxt = &comp_pkt;
3256 pkt.teardown_packet.message[0].type = PCI_BUS_D0EXIT;
3258 ret = vmbus_sendpacket(hdev->channel, &pkt.teardown_packet.message,
3259 sizeof(struct pci_message),
3260 (unsigned long)&pkt.teardown_packet,
3262 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3266 if (wait_for_completion_timeout(&comp_pkt.host_event, 10 * HZ) == 0)
3273 * hv_pci_remove() - Remove routine for this VMBus channel
3274 * @hdev: VMBus's tracking struct for this root PCI bus
3276 * Return: 0 on success, -errno on failure
3278 static int hv_pci_remove(struct hv_device *hdev)
3280 struct hv_pcibus_device *hbus;
3283 hbus = hv_get_drvdata(hdev);
3284 if (hbus->state == hv_pcibus_installed) {
3285 tasklet_disable(&hdev->channel->callback_event);
3286 hbus->state = hv_pcibus_removing;
3287 tasklet_enable(&hdev->channel->callback_event);
3288 destroy_workqueue(hbus->wq);
3291 * At this point, no work is running or can be scheduled
3292 * on hbus-wq. We can't race with hv_pci_devices_present()
3293 * or hv_pci_eject_device(), it's safe to proceed.
3296 /* Remove the bus from PCI's point of view. */
3297 pci_lock_rescan_remove();
3298 pci_stop_root_bus(hbus->pci_bus);
3299 hv_pci_remove_slots(hbus);
3300 pci_remove_root_bus(hbus->pci_bus);
3301 pci_unlock_rescan_remove();
3304 ret = hv_pci_bus_exit(hdev, false);
3306 vmbus_close(hdev->channel);
3308 iounmap(hbus->cfg_addr);
3309 hv_free_config_window(hbus);
3310 pci_free_resource_list(&hbus->resources_for_children);
3311 hv_pci_free_bridge_windows(hbus);
3312 irq_domain_remove(hbus->irq_domain);
3313 irq_domain_free_fwnode(hbus->sysdata.fwnode);
3315 hv_put_dom_num(hbus->sysdata.domain);
3321 static int hv_pci_suspend(struct hv_device *hdev)
3323 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3324 enum hv_pcibus_state old_state;
3328 * hv_pci_suspend() must make sure there are no pending work items
3329 * before calling vmbus_close(), since it runs in a process context
3330 * as a callback in dpm_suspend(). When it starts to run, the channel
3331 * callback hv_pci_onchannelcallback(), which runs in a tasklet
3332 * context, can be still running concurrently and scheduling new work
3333 * items onto hbus->wq in hv_pci_devices_present() and
3334 * hv_pci_eject_device(), and the work item handlers can access the
3335 * vmbus channel, which can be being closed by hv_pci_suspend(), e.g.
3336 * the work item handler pci_devices_present_work() ->
3337 * new_pcichild_device() writes to the vmbus channel.
3339 * To eliminate the race, hv_pci_suspend() disables the channel
3340 * callback tasklet, sets hbus->state to hv_pcibus_removing, and
3341 * re-enables the tasklet. This way, when hv_pci_suspend() proceeds,
3342 * it knows that no new work item can be scheduled, and then it flushes
3343 * hbus->wq and safely closes the vmbus channel.
3345 tasklet_disable(&hdev->channel->callback_event);
3347 /* Change the hbus state to prevent new work items. */
3348 old_state = hbus->state;
3349 if (hbus->state == hv_pcibus_installed)
3350 hbus->state = hv_pcibus_removing;
3352 tasklet_enable(&hdev->channel->callback_event);
3354 if (old_state != hv_pcibus_installed)
3357 flush_workqueue(hbus->wq);
3359 ret = hv_pci_bus_exit(hdev, true);
3363 vmbus_close(hdev->channel);
3368 static int hv_pci_restore_msi_msg(struct pci_dev *pdev, void *arg)
3370 struct msi_desc *entry;
3371 struct irq_data *irq_data;
3373 for_each_pci_msi_entry(entry, pdev) {
3374 irq_data = irq_get_irq_data(entry->irq);
3375 if (WARN_ON_ONCE(!irq_data))
3378 hv_compose_msi_msg(irq_data, &entry->msg);
3385 * Upon resume, pci_restore_msi_state() -> ... -> __pci_write_msi_msg()
3386 * directly writes the MSI/MSI-X registers via MMIO, but since Hyper-V
3387 * doesn't trap and emulate the MMIO accesses, here hv_compose_msi_msg()
3388 * must be used to ask Hyper-V to re-create the IOMMU Interrupt Remapping
3391 static void hv_pci_restore_msi_state(struct hv_pcibus_device *hbus)
3393 pci_walk_bus(hbus->pci_bus, hv_pci_restore_msi_msg, NULL);
3396 static int hv_pci_resume(struct hv_device *hdev)
3398 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3399 enum pci_protocol_version_t version[1];
3402 hbus->state = hv_pcibus_init;
3404 ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
3405 hv_pci_onchannelcallback, hbus);
3409 /* Only use the version that was in use before hibernation. */
3410 version[0] = hbus->protocol_version;
3411 ret = hv_pci_protocol_negotiation(hdev, version, 1);
3415 ret = hv_pci_query_relations(hdev);
3419 ret = hv_pci_enter_d0(hdev);
3423 ret = hv_send_resources_allocated(hdev);
3427 prepopulate_bars(hbus);
3429 hv_pci_restore_msi_state(hbus);
3431 hbus->state = hv_pcibus_installed;
3434 vmbus_close(hdev->channel);
3438 static const struct hv_vmbus_device_id hv_pci_id_table[] = {
3439 /* PCI Pass-through Class ID */
3440 /* 44C4F61D-4444-4400-9D52-802E27EDE19F */
3445 MODULE_DEVICE_TABLE(vmbus, hv_pci_id_table);
3447 static struct hv_driver hv_pci_drv = {
3449 .id_table = hv_pci_id_table,
3450 .probe = hv_pci_probe,
3451 .remove = hv_pci_remove,
3452 .suspend = hv_pci_suspend,
3453 .resume = hv_pci_resume,
3456 static void __exit exit_hv_pci_drv(void)
3458 vmbus_driver_unregister(&hv_pci_drv);
3460 hvpci_block_ops.read_block = NULL;
3461 hvpci_block_ops.write_block = NULL;
3462 hvpci_block_ops.reg_blk_invalidate = NULL;
3465 static int __init init_hv_pci_drv(void)
3467 if (!hv_is_hyperv_initialized())
3470 /* Set the invalid domain number's bit, so it will not be used */
3471 set_bit(HVPCI_DOM_INVALID, hvpci_dom_map);
3473 /* Initialize PCI block r/w interface */
3474 hvpci_block_ops.read_block = hv_read_config_block;
3475 hvpci_block_ops.write_block = hv_write_config_block;
3476 hvpci_block_ops.reg_blk_invalidate = hv_register_block_invalidate;
3478 return vmbus_driver_register(&hv_pci_drv);
3481 module_init(init_hv_pci_drv);
3482 module_exit(exit_hv_pci_drv);
3484 MODULE_DESCRIPTION("Hyper-V PCI");
3485 MODULE_LICENSE("GPL v2");