2 * Copyright (c) Microsoft Corporation.
5 * Jake Oshins <jakeo@microsoft.com>
7 * This driver acts as a paravirtual front-end for PCI Express root buses.
8 * When a PCI Express function (either an entire device or an SR-IOV
9 * Virtual Function) is being passed through to the VM, this driver exposes
10 * a new bus to the guest VM. This is modeled as a root PCI bus because
11 * no bridges are being exposed to the VM. In fact, with a "Generation 2"
12 * VM within Hyper-V, there may seem to be no PCI bus at all in the VM
13 * until a device as been exposed using this driver.
15 * Each root PCI bus has its own PCI domain, which is called "Segment" in
16 * the PCI Firmware Specifications. Thus while each device passed through
17 * to the VM using this front-end will appear at "device 0", the domain will
18 * be unique. Typically, each bus will have one PCI function on it, though
19 * this driver does support more than one.
21 * In order to map the interrupts from the device through to the guest VM,
22 * this driver also implements an IRQ Domain, which handles interrupts (either
23 * MSI or MSI-X) associated with the functions on the bus. As interrupts are
24 * set up, torn down, or reaffined, this driver communicates with the
25 * underlying hypervisor to adjust the mappings in the I/O MMU so that each
26 * interrupt will be delivered to the correct virtual processor at the right
27 * vector. This driver does not support level-triggered (line-based)
28 * interrupts, and will report that the Interrupt Line register in the
29 * function's configuration space is zero.
31 * The rest of this driver mostly maps PCI concepts onto underlying Hyper-V
32 * facilities. For instance, the configuration space of a function exposed
33 * by Hyper-V is mapped into a single page of memory space, and the
34 * read and write handlers for config space must be aware of this mechanism.
35 * Similarly, device setup and teardown involves messages sent to and from
36 * the PCI back-end driver in Hyper-V.
38 * This program is free software; you can redistribute it and/or modify it
39 * under the terms of the GNU General Public License version 2 as published
40 * by the Free Software Foundation.
42 * This program is distributed in the hope that it will be useful, but
43 * WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
45 * NON INFRINGEMENT. See the GNU General Public License for more
50 #include <linux/kernel.h>
51 #include <linux/module.h>
52 #include <linux/pci.h>
53 #include <linux/semaphore.h>
54 #include <linux/irqdomain.h>
55 #include <linux/irq.h>
57 #include <asm/irqdomain.h>
59 #include <linux/msi.h>
60 #include <linux/hyperv.h>
61 #include <asm/mshyperv.h>
64 * Protocol versions. The low word is the minor version, the high word the
68 #define PCI_MAKE_VERSION(major, minor) ((u32)(((major) << 16) | (major)))
69 #define PCI_MAJOR_VERSION(version) ((u32)(version) >> 16)
70 #define PCI_MINOR_VERSION(version) ((u32)(version) & 0xff)
73 PCI_PROTOCOL_VERSION_1_1 = PCI_MAKE_VERSION(1, 1),
74 PCI_PROTOCOL_VERSION_CURRENT = PCI_PROTOCOL_VERSION_1_1
77 #define CPU_AFFINITY_ALL -1ULL
78 #define PCI_CONFIG_MMIO_LENGTH 0x2000
79 #define CFG_PAGE_OFFSET 0x1000
80 #define CFG_PAGE_SIZE (PCI_CONFIG_MMIO_LENGTH - CFG_PAGE_OFFSET)
82 #define MAX_SUPPORTED_MSI_MESSAGES 0x400
88 enum pci_message_type {
92 PCI_MESSAGE_BASE = 0x42490000,
93 PCI_BUS_RELATIONS = PCI_MESSAGE_BASE + 0,
94 PCI_QUERY_BUS_RELATIONS = PCI_MESSAGE_BASE + 1,
95 PCI_POWER_STATE_CHANGE = PCI_MESSAGE_BASE + 4,
96 PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5,
97 PCI_QUERY_RESOURCE_RESOURCES = PCI_MESSAGE_BASE + 6,
98 PCI_BUS_D0ENTRY = PCI_MESSAGE_BASE + 7,
99 PCI_BUS_D0EXIT = PCI_MESSAGE_BASE + 8,
100 PCI_READ_BLOCK = PCI_MESSAGE_BASE + 9,
101 PCI_WRITE_BLOCK = PCI_MESSAGE_BASE + 0xA,
102 PCI_EJECT = PCI_MESSAGE_BASE + 0xB,
103 PCI_QUERY_STOP = PCI_MESSAGE_BASE + 0xC,
104 PCI_REENABLE = PCI_MESSAGE_BASE + 0xD,
105 PCI_QUERY_STOP_FAILED = PCI_MESSAGE_BASE + 0xE,
106 PCI_EJECTION_COMPLETE = PCI_MESSAGE_BASE + 0xF,
107 PCI_RESOURCES_ASSIGNED = PCI_MESSAGE_BASE + 0x10,
108 PCI_RESOURCES_RELEASED = PCI_MESSAGE_BASE + 0x11,
109 PCI_INVALIDATE_BLOCK = PCI_MESSAGE_BASE + 0x12,
110 PCI_QUERY_PROTOCOL_VERSION = PCI_MESSAGE_BASE + 0x13,
111 PCI_CREATE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x14,
112 PCI_DELETE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x15,
117 * Structures defining the virtual PCI Express protocol.
129 * Function numbers are 8-bits wide on Express, as interpreted through ARI,
130 * which is all this driver does. This representation is the one used in
131 * Windows, which is what is expected when sending this back and forth with
132 * the Hyper-V parent partition.
134 union win_slot_encoding {
144 * Pretty much as defined in the PCI Specifications.
146 struct pci_function_description {
147 u16 v_id; /* vendor ID */
148 u16 d_id; /* device ID */
154 union win_slot_encoding win_slot;
155 u32 ser; /* serial number */
161 * @delivery_mode: As defined in Intel's Programmer's
162 * Reference Manual, Volume 3, Chapter 8.
163 * @vector_count: Number of contiguous entries in the
164 * Interrupt Descriptor Table that are
165 * occupied by this Message-Signaled
166 * Interrupt. For "MSI", as first defined
167 * in PCI 2.2, this can be between 1 and
168 * 32. For "MSI-X," as first defined in PCI
169 * 3.0, this must be 1, as each MSI-X table
170 * entry would have its own descriptor.
171 * @reserved: Empty space
172 * @cpu_mask: All the target virtual processors.
183 * struct tran_int_desc
184 * @reserved: unused, padding
185 * @vector_count: same as in hv_msi_desc
186 * @data: This is the "data payload" value that is
187 * written by the device when it generates
188 * a message-signaled interrupt, either MSI
190 * @address: This is the address to which the data
191 * payload is written on interrupt
194 struct tran_int_desc {
202 * A generic message format for virtual PCI.
203 * Specific message formats are defined later in the file.
210 struct pci_child_message {
211 struct pci_message message_type;
212 union win_slot_encoding wslot;
215 struct pci_incoming_message {
216 struct vmpacket_descriptor hdr;
217 struct pci_message message_type;
220 struct pci_response {
221 struct vmpacket_descriptor hdr;
222 s32 status; /* negative values are failures */
226 void (*completion_func)(void *context, struct pci_response *resp,
227 int resp_packet_size);
230 struct pci_message message[0];
234 * Specific message types supporting the PCI protocol.
238 * Version negotiation message. Sent from the guest to the host.
239 * The guest is free to try different versions until the host
240 * accepts the version.
242 * pci_version: The protocol version requested.
243 * is_last_attempt: If TRUE, this is the last version guest will request.
244 * reservedz: Reserved field, set to zero.
247 struct pci_version_request {
248 struct pci_message message_type;
249 enum pci_message_type protocol_version;
253 * Bus D0 Entry. This is sent from the guest to the host when the virtual
254 * bus (PCI Express port) is ready for action.
257 struct pci_bus_d0_entry {
258 struct pci_message message_type;
263 struct pci_bus_relations {
264 struct pci_incoming_message incoming;
266 struct pci_function_description func[0];
269 struct pci_q_res_req_response {
270 struct vmpacket_descriptor hdr;
271 s32 status; /* negative values are failures */
275 struct pci_set_power {
276 struct pci_message message_type;
277 union win_slot_encoding wslot;
278 u32 power_state; /* In Windows terms */
282 struct pci_set_power_response {
283 struct vmpacket_descriptor hdr;
284 s32 status; /* negative values are failures */
285 union win_slot_encoding wslot;
286 u32 resultant_state; /* In Windows terms */
290 struct pci_resources_assigned {
291 struct pci_message message_type;
292 union win_slot_encoding wslot;
293 u8 memory_range[0x14][6]; /* not used here */
298 struct pci_create_interrupt {
299 struct pci_message message_type;
300 union win_slot_encoding wslot;
301 struct hv_msi_desc int_desc;
304 struct pci_create_int_response {
305 struct pci_response response;
307 struct tran_int_desc int_desc;
310 struct pci_delete_interrupt {
311 struct pci_message message_type;
312 union win_slot_encoding wslot;
313 struct tran_int_desc int_desc;
316 struct pci_dev_incoming {
317 struct pci_incoming_message incoming;
318 union win_slot_encoding wslot;
321 struct pci_eject_response {
322 struct pci_message message_type;
323 union win_slot_encoding wslot;
327 static int pci_ring_size = (4 * PAGE_SIZE);
330 * Definitions or interrupt steering hypercall.
332 #define HV_PARTITION_ID_SELF ((u64)-1)
333 #define HVCALL_RETARGET_INTERRUPT 0x7e
335 struct retarget_msi_interrupt {
336 u64 partition_id; /* use "self" */
338 u32 source; /* 1 for MSI(-X) */
349 * Driver specific state.
352 enum hv_pcibus_state {
360 struct hv_pcibus_device {
361 struct pci_sysdata sysdata;
362 enum hv_pcibus_state state;
363 atomic_t remove_lock;
364 struct hv_device *hdev;
365 resource_size_t low_mmio_space;
366 resource_size_t high_mmio_space;
367 struct resource *mem_config;
368 struct resource *low_mmio_res;
369 struct resource *high_mmio_res;
370 struct completion *survey_event;
371 struct completion remove_event;
372 struct pci_bus *pci_bus;
373 spinlock_t config_lock; /* Avoid two threads writing index page */
374 spinlock_t device_list_lock; /* Protect lists below */
375 void __iomem *cfg_addr;
377 struct semaphore enum_sem;
378 struct list_head resources_for_children;
380 struct list_head children;
381 struct list_head dr_list;
383 struct msi_domain_info msi_info;
384 struct msi_controller msi_chip;
385 struct irq_domain *irq_domain;
389 * Tracks "Device Relations" messages from the host, which must be both
390 * processed in order and deferred so that they don't run in the context
391 * of the incoming packet callback.
394 struct work_struct wrk;
395 struct hv_pcibus_device *bus;
399 struct list_head list_entry;
401 struct pci_function_description func[0];
404 enum hv_pcichild_state {
405 hv_pcichild_init = 0,
406 hv_pcichild_requirements,
407 hv_pcichild_resourced,
408 hv_pcichild_ejecting,
412 enum hv_pcidev_ref_reason {
413 hv_pcidev_ref_invalid = 0,
414 hv_pcidev_ref_initial,
415 hv_pcidev_ref_by_slot,
416 hv_pcidev_ref_packet,
418 hv_pcidev_ref_childlist,
424 /* List protected by pci_rescan_remove_lock */
425 struct list_head list_entry;
427 enum hv_pcichild_state state;
428 struct pci_function_description desc;
429 bool reported_missing;
430 struct hv_pcibus_device *hbus;
431 struct work_struct wrk;
434 * What would be observed if one wrote 0xFFFFFFFF to a BAR and then
435 * read it back, for each of the BAR offsets within config space.
440 struct hv_pci_compl {
441 struct completion host_event;
442 s32 completion_status;
446 * hv_pci_generic_compl() - Invoked for a completion packet
447 * @context: Set up by the sender of the packet.
448 * @resp: The response packet
449 * @resp_packet_size: Size in bytes of the packet
451 * This function is used to trigger an event and report status
452 * for any message for which the completion packet contains a
453 * status and nothing else.
455 static void hv_pci_generic_compl(void *context, struct pci_response *resp,
456 int resp_packet_size)
458 struct hv_pci_compl *comp_pkt = context;
460 if (resp_packet_size >= offsetofend(struct pci_response, status))
461 comp_pkt->completion_status = resp->status;
463 comp_pkt->completion_status = -1;
465 complete(&comp_pkt->host_event);
468 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
470 static void get_pcichild(struct hv_pci_dev *hv_pcidev,
471 enum hv_pcidev_ref_reason reason);
472 static void put_pcichild(struct hv_pci_dev *hv_pcidev,
473 enum hv_pcidev_ref_reason reason);
475 static void get_hvpcibus(struct hv_pcibus_device *hv_pcibus);
476 static void put_hvpcibus(struct hv_pcibus_device *hv_pcibus);
479 * devfn_to_wslot() - Convert from Linux PCI slot to Windows
480 * @devfn: The Linux representation of PCI slot
482 * Windows uses a slightly different representation of PCI slot.
484 * Return: The Windows representation
486 static u32 devfn_to_wslot(int devfn)
488 union win_slot_encoding wslot;
491 wslot.bits.dev = PCI_SLOT(devfn);
492 wslot.bits.func = PCI_FUNC(devfn);
498 * wslot_to_devfn() - Convert from Windows PCI slot to Linux
499 * @wslot: The Windows representation of PCI slot
501 * Windows uses a slightly different representation of PCI slot.
503 * Return: The Linux representation
505 static int wslot_to_devfn(u32 wslot)
507 union win_slot_encoding slot_no;
509 slot_no.slot = wslot;
510 return PCI_DEVFN(slot_no.bits.dev, slot_no.bits.func);
514 * PCI Configuration Space for these root PCI buses is implemented as a pair
515 * of pages in memory-mapped I/O space. Writing to the first page chooses
516 * the PCI function being written or read. Once the first page has been
517 * written to, the following page maps in the entire configuration space of
522 * _hv_pcifront_read_config() - Internal PCI config read
523 * @hpdev: The PCI driver's representation of the device
524 * @where: Offset within config space
525 * @size: Size of the transfer
526 * @val: Pointer to the buffer receiving the data
528 static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where,
532 void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
535 * If the attempt is to read the IDs or the ROM BAR, simulate that.
537 if (where + size <= PCI_COMMAND) {
538 memcpy(val, ((u8 *)&hpdev->desc.v_id) + where, size);
539 } else if (where >= PCI_CLASS_REVISION && where + size <=
540 PCI_CACHE_LINE_SIZE) {
541 memcpy(val, ((u8 *)&hpdev->desc.rev) + where -
542 PCI_CLASS_REVISION, size);
543 } else if (where >= PCI_SUBSYSTEM_VENDOR_ID && where + size <=
545 memcpy(val, (u8 *)&hpdev->desc.subsystem_id + where -
546 PCI_SUBSYSTEM_VENDOR_ID, size);
547 } else if (where >= PCI_ROM_ADDRESS && where + size <=
548 PCI_CAPABILITY_LIST) {
549 /* ROM BARs are unimplemented */
551 } else if (where >= PCI_INTERRUPT_LINE && where + size <=
554 * Interrupt Line and Interrupt PIN are hard-wired to zero
555 * because this front-end only supports message-signaled
559 } else if (where + size <= CFG_PAGE_SIZE) {
560 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
561 /* Choose the function to be read. (See comment above) */
562 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
563 /* Make sure the function was chosen before we start reading. */
565 /* Read from that function's config space. */
578 * Make sure the write was done before we release the spinlock
579 * allowing consecutive reads/writes.
582 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
584 dev_err(&hpdev->hbus->hdev->device,
585 "Attempt to read beyond a function's config space.\n");
590 * _hv_pcifront_write_config() - Internal PCI config write
591 * @hpdev: The PCI driver's representation of the device
592 * @where: Offset within config space
593 * @size: Size of the transfer
594 * @val: The data being transferred
596 static void _hv_pcifront_write_config(struct hv_pci_dev *hpdev, int where,
600 void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
602 if (where >= PCI_SUBSYSTEM_VENDOR_ID &&
603 where + size <= PCI_CAPABILITY_LIST) {
604 /* SSIDs and ROM BARs are read-only */
605 } else if (where >= PCI_COMMAND && where + size <= CFG_PAGE_SIZE) {
606 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
607 /* Choose the function to be written. (See comment above) */
608 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
609 /* Make sure the function was chosen before we start writing. */
611 /* Write to that function's config space. */
624 * Make sure the write was done before we release the spinlock
625 * allowing consecutive reads/writes.
628 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
630 dev_err(&hpdev->hbus->hdev->device,
631 "Attempt to write beyond a function's config space.\n");
636 * hv_pcifront_read_config() - Read configuration space
637 * @bus: PCI Bus structure
638 * @devfn: Device/function
639 * @where: Offset from base
640 * @size: Byte/word/dword
641 * @val: Value to be read
643 * Return: PCIBIOS_SUCCESSFUL on success
644 * PCIBIOS_DEVICE_NOT_FOUND on failure
646 static int hv_pcifront_read_config(struct pci_bus *bus, unsigned int devfn,
647 int where, int size, u32 *val)
649 struct hv_pcibus_device *hbus =
650 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
651 struct hv_pci_dev *hpdev;
653 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
655 return PCIBIOS_DEVICE_NOT_FOUND;
657 _hv_pcifront_read_config(hpdev, where, size, val);
659 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
660 return PCIBIOS_SUCCESSFUL;
664 * hv_pcifront_write_config() - Write configuration space
665 * @bus: PCI Bus structure
666 * @devfn: Device/function
667 * @where: Offset from base
668 * @size: Byte/word/dword
669 * @val: Value to be written to device
671 * Return: PCIBIOS_SUCCESSFUL on success
672 * PCIBIOS_DEVICE_NOT_FOUND on failure
674 static int hv_pcifront_write_config(struct pci_bus *bus, unsigned int devfn,
675 int where, int size, u32 val)
677 struct hv_pcibus_device *hbus =
678 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
679 struct hv_pci_dev *hpdev;
681 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
683 return PCIBIOS_DEVICE_NOT_FOUND;
685 _hv_pcifront_write_config(hpdev, where, size, val);
687 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
688 return PCIBIOS_SUCCESSFUL;
691 /* PCIe operations */
692 static struct pci_ops hv_pcifront_ops = {
693 .read = hv_pcifront_read_config,
694 .write = hv_pcifront_write_config,
697 /* Interrupt management hooks */
698 static void hv_int_desc_free(struct hv_pci_dev *hpdev,
699 struct tran_int_desc *int_desc)
701 struct pci_delete_interrupt *int_pkt;
703 struct pci_packet pkt;
704 u8 buffer[sizeof(struct pci_delete_interrupt)];
707 memset(&ctxt, 0, sizeof(ctxt));
708 int_pkt = (struct pci_delete_interrupt *)&ctxt.pkt.message;
709 int_pkt->message_type.type =
710 PCI_DELETE_INTERRUPT_MESSAGE;
711 int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
712 int_pkt->int_desc = *int_desc;
713 vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt, sizeof(*int_pkt),
714 (unsigned long)&ctxt.pkt, VM_PKT_DATA_INBAND, 0);
719 * hv_msi_free() - Free the MSI.
720 * @domain: The interrupt domain pointer
721 * @info: Extra MSI-related context
722 * @irq: Identifies the IRQ.
724 * The Hyper-V parent partition and hypervisor are tracking the
725 * messages that are in use, keeping the interrupt redirection
726 * table up to date. This callback sends a message that frees
727 * the IRT entry and related tracking nonsense.
729 static void hv_msi_free(struct irq_domain *domain, struct msi_domain_info *info,
732 struct hv_pcibus_device *hbus;
733 struct hv_pci_dev *hpdev;
734 struct pci_dev *pdev;
735 struct tran_int_desc *int_desc;
736 struct irq_data *irq_data = irq_domain_get_irq_data(domain, irq);
737 struct msi_desc *msi = irq_data_get_msi_desc(irq_data);
739 pdev = msi_desc_to_pci_dev(msi);
741 int_desc = irq_data_get_irq_chip_data(irq_data);
745 irq_data->chip_data = NULL;
746 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
752 hv_int_desc_free(hpdev, int_desc);
753 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
756 static int hv_set_affinity(struct irq_data *data, const struct cpumask *dest,
759 struct irq_data *parent = data->parent_data;
761 return parent->chip->irq_set_affinity(parent, dest, force);
764 void hv_irq_mask(struct irq_data *data)
766 pci_msi_mask_irq(data);
770 * hv_irq_unmask() - "Unmask" the IRQ by setting its current
772 * @data: Describes the IRQ
774 * Build new a destination for the MSI and make a hypercall to
775 * update the Interrupt Redirection Table. "Device Logical ID"
776 * is built out of this PCI bus's instance GUID and the function
777 * number of the device.
779 void hv_irq_unmask(struct irq_data *data)
781 struct msi_desc *msi_desc = irq_data_get_msi_desc(data);
782 struct irq_cfg *cfg = irqd_cfg(data);
783 struct retarget_msi_interrupt params;
784 struct hv_pcibus_device *hbus;
785 struct cpumask *dest;
786 struct pci_bus *pbus;
787 struct pci_dev *pdev;
790 dest = irq_data_get_affinity_mask(data);
791 pdev = msi_desc_to_pci_dev(msi_desc);
793 hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
795 memset(¶ms, 0, sizeof(params));
796 params.partition_id = HV_PARTITION_ID_SELF;
797 params.source = 1; /* MSI(-X) */
798 params.address = msi_desc->msg.address_lo;
799 params.data = msi_desc->msg.data;
800 params.device_id = (hbus->hdev->dev_instance.b[5] << 24) |
801 (hbus->hdev->dev_instance.b[4] << 16) |
802 (hbus->hdev->dev_instance.b[7] << 8) |
803 (hbus->hdev->dev_instance.b[6] & 0xf8) |
804 PCI_FUNC(pdev->devfn);
805 params.vector = cfg->vector;
807 for_each_cpu_and(cpu, dest, cpu_online_mask)
808 params.vp_mask |= (1ULL << vmbus_cpu_number_to_vp_number(cpu));
810 hv_do_hypercall(HVCALL_RETARGET_INTERRUPT, ¶ms, NULL);
812 pci_msi_unmask_irq(data);
815 struct compose_comp_ctxt {
816 struct hv_pci_compl comp_pkt;
817 struct tran_int_desc int_desc;
820 static void hv_pci_compose_compl(void *context, struct pci_response *resp,
821 int resp_packet_size)
823 struct compose_comp_ctxt *comp_pkt = context;
824 struct pci_create_int_response *int_resp =
825 (struct pci_create_int_response *)resp;
827 comp_pkt->comp_pkt.completion_status = resp->status;
828 comp_pkt->int_desc = int_resp->int_desc;
829 complete(&comp_pkt->comp_pkt.host_event);
833 * hv_compose_msi_msg() - Supplies a valid MSI address/data
834 * @data: Everything about this MSI
835 * @msg: Buffer that is filled in by this function
837 * This function unpacks the IRQ looking for target CPU set, IDT
838 * vector and mode and sends a message to the parent partition
839 * asking for a mapping for that tuple in this partition. The
840 * response supplies a data value and address to which that data
841 * should be written to trigger that interrupt.
843 static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
845 struct irq_cfg *cfg = irqd_cfg(data);
846 struct hv_pcibus_device *hbus;
847 struct hv_pci_dev *hpdev;
848 struct pci_bus *pbus;
849 struct pci_dev *pdev;
850 struct pci_create_interrupt *int_pkt;
851 struct compose_comp_ctxt comp;
852 struct tran_int_desc *int_desc;
853 struct cpumask *affinity;
855 struct pci_packet pkt;
856 u8 buffer[sizeof(struct pci_create_interrupt)];
861 pdev = msi_desc_to_pci_dev(irq_data_get_msi_desc(data));
863 hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
864 hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
866 goto return_null_message;
868 /* Free any previous message that might have already been composed. */
869 if (data->chip_data) {
870 int_desc = data->chip_data;
871 data->chip_data = NULL;
872 hv_int_desc_free(hpdev, int_desc);
875 int_desc = kzalloc(sizeof(*int_desc), GFP_ATOMIC);
879 memset(&ctxt, 0, sizeof(ctxt));
880 init_completion(&comp.comp_pkt.host_event);
881 ctxt.pkt.completion_func = hv_pci_compose_compl;
882 ctxt.pkt.compl_ctxt = ∁
883 int_pkt = (struct pci_create_interrupt *)&ctxt.pkt.message;
884 int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE;
885 int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
886 int_pkt->int_desc.vector = cfg->vector;
887 int_pkt->int_desc.vector_count = 1;
888 int_pkt->int_desc.delivery_mode =
889 (apic->irq_delivery_mode == dest_LowestPrio) ? 1 : 0;
892 * This bit doesn't have to work on machines with more than 64
893 * processors because Hyper-V only supports 64 in a guest.
895 affinity = irq_data_get_affinity_mask(data);
896 if (cpumask_weight(affinity) >= 32) {
897 int_pkt->int_desc.cpu_mask = CPU_AFFINITY_ALL;
899 for_each_cpu_and(cpu, affinity, cpu_online_mask) {
900 int_pkt->int_desc.cpu_mask |=
901 (1ULL << vmbus_cpu_number_to_vp_number(cpu));
905 ret = vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt,
906 sizeof(*int_pkt), (unsigned long)&ctxt.pkt,
908 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
912 wait_for_completion(&comp.comp_pkt.host_event);
914 if (comp.comp_pkt.completion_status < 0) {
915 dev_err(&hbus->hdev->device,
916 "Request for interrupt failed: 0x%x",
917 comp.comp_pkt.completion_status);
922 * Record the assignment so that this can be unwound later. Using
923 * irq_set_chip_data() here would be appropriate, but the lock it takes
926 *int_desc = comp.int_desc;
927 data->chip_data = int_desc;
929 /* Pass up the result. */
930 msg->address_hi = comp.int_desc.address >> 32;
931 msg->address_lo = comp.int_desc.address & 0xffffffff;
932 msg->data = comp.int_desc.data;
934 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
940 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
947 /* HW Interrupt Chip Descriptor */
948 static struct irq_chip hv_msi_irq_chip = {
949 .name = "Hyper-V PCIe MSI",
950 .irq_compose_msi_msg = hv_compose_msi_msg,
951 .irq_set_affinity = hv_set_affinity,
952 .irq_ack = irq_chip_ack_parent,
953 .irq_mask = hv_irq_mask,
954 .irq_unmask = hv_irq_unmask,
957 static irq_hw_number_t hv_msi_domain_ops_get_hwirq(struct msi_domain_info *info,
958 msi_alloc_info_t *arg)
960 return arg->msi_hwirq;
963 static struct msi_domain_ops hv_msi_ops = {
964 .get_hwirq = hv_msi_domain_ops_get_hwirq,
965 .msi_prepare = pci_msi_prepare,
966 .set_desc = pci_msi_set_desc,
967 .msi_free = hv_msi_free,
971 * hv_pcie_init_irq_domain() - Initialize IRQ domain
972 * @hbus: The root PCI bus
974 * This function creates an IRQ domain which will be used for
975 * interrupts from devices that have been passed through. These
976 * devices only support MSI and MSI-X, not line-based interrupts
977 * or simulations of line-based interrupts through PCIe's
978 * fabric-layer messages. Because interrupts are remapped, we
979 * can support multi-message MSI here.
981 * Return: '0' on success and error value on failure
983 static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus)
985 hbus->msi_info.chip = &hv_msi_irq_chip;
986 hbus->msi_info.ops = &hv_msi_ops;
987 hbus->msi_info.flags = (MSI_FLAG_USE_DEF_DOM_OPS |
988 MSI_FLAG_USE_DEF_CHIP_OPS | MSI_FLAG_MULTI_PCI_MSI |
990 hbus->msi_info.handler = handle_edge_irq;
991 hbus->msi_info.handler_name = "edge";
992 hbus->msi_info.data = hbus;
993 hbus->irq_domain = pci_msi_create_irq_domain(hbus->sysdata.fwnode,
996 if (!hbus->irq_domain) {
997 dev_err(&hbus->hdev->device,
998 "Failed to build an MSI IRQ domain\n");
1006 * get_bar_size() - Get the address space consumed by a BAR
1007 * @bar_val: Value that a BAR returned after -1 was written
1010 * This function returns the size of the BAR, rounded up to 1
1011 * page. It has to be rounded up because the hypervisor's page
1012 * table entry that maps the BAR into the VM can't specify an
1013 * offset within a page. The invariant is that the hypervisor
1014 * must place any BARs of smaller than page length at the
1015 * beginning of a page.
1017 * Return: Size in bytes of the consumed MMIO space.
1019 static u64 get_bar_size(u64 bar_val)
1021 return round_up((1 + ~(bar_val & PCI_BASE_ADDRESS_MEM_MASK)),
1026 * survey_child_resources() - Total all MMIO requirements
1027 * @hbus: Root PCI bus, as understood by this driver
1029 static void survey_child_resources(struct hv_pcibus_device *hbus)
1031 struct list_head *iter;
1032 struct hv_pci_dev *hpdev;
1033 resource_size_t bar_size = 0;
1034 unsigned long flags;
1035 struct completion *event;
1039 /* If nobody is waiting on the answer, don't compute it. */
1040 event = xchg(&hbus->survey_event, NULL);
1044 /* If the answer has already been computed, go with it. */
1045 if (hbus->low_mmio_space || hbus->high_mmio_space) {
1050 spin_lock_irqsave(&hbus->device_list_lock, flags);
1053 * Due to an interesting quirk of the PCI spec, all memory regions
1054 * for a child device are a power of 2 in size and aligned in memory,
1055 * so it's sufficient to just add them up without tracking alignment.
1057 list_for_each(iter, &hbus->children) {
1058 hpdev = container_of(iter, struct hv_pci_dev, list_entry);
1059 for (i = 0; i < 6; i++) {
1060 if (hpdev->probed_bar[i] & PCI_BASE_ADDRESS_SPACE_IO)
1061 dev_err(&hbus->hdev->device,
1062 "There's an I/O BAR in this list!\n");
1064 if (hpdev->probed_bar[i] != 0) {
1066 * A probed BAR has all the upper bits set that
1070 bar_val = hpdev->probed_bar[i];
1071 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1073 ((u64)hpdev->probed_bar[++i] << 32);
1075 bar_val |= 0xffffffff00000000ULL;
1077 bar_size = get_bar_size(bar_val);
1079 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1080 hbus->high_mmio_space += bar_size;
1082 hbus->low_mmio_space += bar_size;
1087 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1092 * prepopulate_bars() - Fill in BARs with defaults
1093 * @hbus: Root PCI bus, as understood by this driver
1095 * The core PCI driver code seems much, much happier if the BARs
1096 * for a device have values upon first scan. So fill them in.
1097 * The algorithm below works down from large sizes to small,
1098 * attempting to pack the assignments optimally. The assumption,
1099 * enforced in other parts of the code, is that the beginning of
1100 * the memory-mapped I/O space will be aligned on the largest
1103 static void prepopulate_bars(struct hv_pcibus_device *hbus)
1105 resource_size_t high_size = 0;
1106 resource_size_t low_size = 0;
1107 resource_size_t high_base = 0;
1108 resource_size_t low_base = 0;
1109 resource_size_t bar_size;
1110 struct hv_pci_dev *hpdev;
1111 struct list_head *iter;
1112 unsigned long flags;
1118 if (hbus->low_mmio_space) {
1119 low_size = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
1120 low_base = hbus->low_mmio_res->start;
1123 if (hbus->high_mmio_space) {
1125 (63 - __builtin_clzll(hbus->high_mmio_space));
1126 high_base = hbus->high_mmio_res->start;
1129 spin_lock_irqsave(&hbus->device_list_lock, flags);
1131 /* Pick addresses for the BARs. */
1133 list_for_each(iter, &hbus->children) {
1134 hpdev = container_of(iter, struct hv_pci_dev,
1136 for (i = 0; i < 6; i++) {
1137 bar_val = hpdev->probed_bar[i];
1140 high = bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64;
1143 ((u64)hpdev->probed_bar[i + 1]
1146 bar_val |= 0xffffffffULL << 32;
1148 bar_size = get_bar_size(bar_val);
1150 if (high_size != bar_size) {
1154 _hv_pcifront_write_config(hpdev,
1155 PCI_BASE_ADDRESS_0 + (4 * i),
1157 (u32)(high_base & 0xffffff00));
1159 _hv_pcifront_write_config(hpdev,
1160 PCI_BASE_ADDRESS_0 + (4 * i),
1161 4, (u32)(high_base >> 32));
1162 high_base += bar_size;
1164 if (low_size != bar_size)
1166 _hv_pcifront_write_config(hpdev,
1167 PCI_BASE_ADDRESS_0 + (4 * i),
1169 (u32)(low_base & 0xffffff00));
1170 low_base += bar_size;
1173 if (high_size <= 1 && low_size <= 1) {
1174 /* Set the memory enable bit. */
1175 _hv_pcifront_read_config(hpdev, PCI_COMMAND, 2,
1177 command |= PCI_COMMAND_MEMORY;
1178 _hv_pcifront_write_config(hpdev, PCI_COMMAND, 2,
1186 } while (high_size || low_size);
1188 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1192 * create_root_hv_pci_bus() - Expose a new root PCI bus
1193 * @hbus: Root PCI bus, as understood by this driver
1195 * Return: 0 on success, -errno on failure
1197 static int create_root_hv_pci_bus(struct hv_pcibus_device *hbus)
1199 /* Register the device */
1200 hbus->pci_bus = pci_create_root_bus(&hbus->hdev->device,
1201 0, /* bus number is always zero */
1204 &hbus->resources_for_children);
1208 hbus->pci_bus->msi = &hbus->msi_chip;
1209 hbus->pci_bus->msi->dev = &hbus->hdev->device;
1211 pci_lock_rescan_remove();
1212 pci_scan_child_bus(hbus->pci_bus);
1213 pci_bus_assign_resources(hbus->pci_bus);
1214 pci_bus_add_devices(hbus->pci_bus);
1215 pci_unlock_rescan_remove();
1216 hbus->state = hv_pcibus_installed;
1220 struct q_res_req_compl {
1221 struct completion host_event;
1222 struct hv_pci_dev *hpdev;
1226 * q_resource_requirements() - Query Resource Requirements
1227 * @context: The completion context.
1228 * @resp: The response that came from the host.
1229 * @resp_packet_size: The size in bytes of resp.
1231 * This function is invoked on completion of a Query Resource
1232 * Requirements packet.
1234 static void q_resource_requirements(void *context, struct pci_response *resp,
1235 int resp_packet_size)
1237 struct q_res_req_compl *completion = context;
1238 struct pci_q_res_req_response *q_res_req =
1239 (struct pci_q_res_req_response *)resp;
1242 if (resp->status < 0) {
1243 dev_err(&completion->hpdev->hbus->hdev->device,
1244 "query resource requirements failed: %x\n",
1247 for (i = 0; i < 6; i++) {
1248 completion->hpdev->probed_bar[i] =
1249 q_res_req->probed_bar[i];
1253 complete(&completion->host_event);
1256 static void get_pcichild(struct hv_pci_dev *hpdev,
1257 enum hv_pcidev_ref_reason reason)
1259 atomic_inc(&hpdev->refs);
1262 static void put_pcichild(struct hv_pci_dev *hpdev,
1263 enum hv_pcidev_ref_reason reason)
1265 if (atomic_dec_and_test(&hpdev->refs))
1270 * new_pcichild_device() - Create a new child device
1271 * @hbus: The internal struct tracking this root PCI bus.
1272 * @desc: The information supplied so far from the host
1275 * This function creates the tracking structure for a new child
1276 * device and kicks off the process of figuring out what it is.
1278 * Return: Pointer to the new tracking struct
1280 static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
1281 struct pci_function_description *desc)
1283 struct hv_pci_dev *hpdev;
1284 struct pci_child_message *res_req;
1285 struct q_res_req_compl comp_pkt;
1287 struct pci_packet init_packet;
1290 unsigned long flags;
1293 hpdev = kzalloc(sizeof(*hpdev), GFP_ATOMIC);
1299 memset(&pkt, 0, sizeof(pkt));
1300 init_completion(&comp_pkt.host_event);
1301 comp_pkt.hpdev = hpdev;
1302 pkt.init_packet.compl_ctxt = &comp_pkt;
1303 pkt.init_packet.completion_func = q_resource_requirements;
1304 res_req = (struct pci_child_message *)&pkt.init_packet.message;
1305 res_req->message_type.type = PCI_QUERY_RESOURCE_REQUIREMENTS;
1306 res_req->wslot.slot = desc->win_slot.slot;
1308 ret = vmbus_sendpacket(hbus->hdev->channel, res_req,
1309 sizeof(struct pci_child_message),
1310 (unsigned long)&pkt.init_packet,
1312 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1316 wait_for_completion(&comp_pkt.host_event);
1318 hpdev->desc = *desc;
1319 get_pcichild(hpdev, hv_pcidev_ref_initial);
1320 get_pcichild(hpdev, hv_pcidev_ref_childlist);
1321 spin_lock_irqsave(&hbus->device_list_lock, flags);
1322 list_add_tail(&hpdev->list_entry, &hbus->children);
1323 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1332 * get_pcichild_wslot() - Find device from slot
1333 * @hbus: Root PCI bus, as understood by this driver
1334 * @wslot: Location on the bus
1336 * This function looks up a PCI device and returns the internal
1337 * representation of it. It acquires a reference on it, so that
1338 * the device won't be deleted while somebody is using it. The
1339 * caller is responsible for calling put_pcichild() to release
1342 * Return: Internal representation of a PCI device
1344 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
1347 unsigned long flags;
1348 struct hv_pci_dev *iter, *hpdev = NULL;
1350 spin_lock_irqsave(&hbus->device_list_lock, flags);
1351 list_for_each_entry(iter, &hbus->children, list_entry) {
1352 if (iter->desc.win_slot.slot == wslot) {
1354 get_pcichild(hpdev, hv_pcidev_ref_by_slot);
1358 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1364 * pci_devices_present_work() - Handle new list of child devices
1365 * @work: Work struct embedded in struct hv_dr_work
1367 * "Bus Relations" is the Windows term for "children of this
1368 * bus." The terminology is preserved here for people trying to
1369 * debug the interaction between Hyper-V and Linux. This
1370 * function is called when the parent partition reports a list
1371 * of functions that should be observed under this PCI Express
1374 * This function updates the list, and must tolerate being
1375 * called multiple times with the same information. The typical
1376 * number of child devices is one, with very atypical cases
1377 * involving three or four, so the algorithms used here can be
1378 * simple and inefficient.
1380 * It must also treat the omission of a previously observed device as
1381 * notification that the device no longer exists.
1383 * Note that this function is a work item, and it may not be
1384 * invoked in the order that it was queued. Back to back
1385 * updates of the list of present devices may involve queuing
1386 * multiple work items, and this one may run before ones that
1387 * were sent later. As such, this function only does something
1388 * if is the last one in the queue.
1390 static void pci_devices_present_work(struct work_struct *work)
1394 struct list_head *iter;
1395 struct pci_function_description *new_desc;
1396 struct hv_pci_dev *hpdev;
1397 struct hv_pcibus_device *hbus;
1398 struct list_head removed;
1399 struct hv_dr_work *dr_wrk;
1400 struct hv_dr_state *dr = NULL;
1401 unsigned long flags;
1403 dr_wrk = container_of(work, struct hv_dr_work, wrk);
1407 INIT_LIST_HEAD(&removed);
1409 if (down_interruptible(&hbus->enum_sem)) {
1414 /* Pull this off the queue and process it if it was the last one. */
1415 spin_lock_irqsave(&hbus->device_list_lock, flags);
1416 while (!list_empty(&hbus->dr_list)) {
1417 dr = list_first_entry(&hbus->dr_list, struct hv_dr_state,
1419 list_del(&dr->list_entry);
1421 /* Throw this away if the list still has stuff in it. */
1422 if (!list_empty(&hbus->dr_list)) {
1427 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1430 up(&hbus->enum_sem);
1435 /* First, mark all existing children as reported missing. */
1436 spin_lock_irqsave(&hbus->device_list_lock, flags);
1437 list_for_each(iter, &hbus->children) {
1438 hpdev = container_of(iter, struct hv_pci_dev,
1440 hpdev->reported_missing = true;
1442 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1444 /* Next, add back any reported devices. */
1445 for (child_no = 0; child_no < dr->device_count; child_no++) {
1447 new_desc = &dr->func[child_no];
1449 spin_lock_irqsave(&hbus->device_list_lock, flags);
1450 list_for_each(iter, &hbus->children) {
1451 hpdev = container_of(iter, struct hv_pci_dev,
1453 if ((hpdev->desc.win_slot.slot ==
1454 new_desc->win_slot.slot) &&
1455 (hpdev->desc.v_id == new_desc->v_id) &&
1456 (hpdev->desc.d_id == new_desc->d_id) &&
1457 (hpdev->desc.ser == new_desc->ser)) {
1458 hpdev->reported_missing = false;
1462 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1465 hpdev = new_pcichild_device(hbus, new_desc);
1467 dev_err(&hbus->hdev->device,
1468 "couldn't record a child device.\n");
1472 /* Move missing children to a list on the stack. */
1473 spin_lock_irqsave(&hbus->device_list_lock, flags);
1476 list_for_each(iter, &hbus->children) {
1477 hpdev = container_of(iter, struct hv_pci_dev,
1479 if (hpdev->reported_missing) {
1481 put_pcichild(hpdev, hv_pcidev_ref_childlist);
1482 list_move_tail(&hpdev->list_entry, &removed);
1487 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1489 /* Delete everything that should no longer exist. */
1490 while (!list_empty(&removed)) {
1491 hpdev = list_first_entry(&removed, struct hv_pci_dev,
1493 list_del(&hpdev->list_entry);
1494 put_pcichild(hpdev, hv_pcidev_ref_initial);
1497 switch(hbus->state) {
1498 case hv_pcibus_installed:
1500 * Tell the core to rescan bus
1501 * because there may have been changes.
1503 pci_lock_rescan_remove();
1504 pci_scan_child_bus(hbus->pci_bus);
1505 pci_unlock_rescan_remove();
1508 case hv_pcibus_init:
1509 case hv_pcibus_probed:
1510 survey_child_resources(hbus);
1517 up(&hbus->enum_sem);
1523 * hv_pci_devices_present() - Handles list of new children
1524 * @hbus: Root PCI bus, as understood by this driver
1525 * @relations: Packet from host listing children
1527 * This function is invoked whenever a new list of devices for
1530 static void hv_pci_devices_present(struct hv_pcibus_device *hbus,
1531 struct pci_bus_relations *relations)
1533 struct hv_dr_state *dr;
1534 struct hv_dr_work *dr_wrk;
1535 unsigned long flags;
1537 dr_wrk = kzalloc(sizeof(*dr_wrk), GFP_NOWAIT);
1541 dr = kzalloc(offsetof(struct hv_dr_state, func) +
1542 (sizeof(struct pci_function_description) *
1543 (relations->device_count)), GFP_NOWAIT);
1549 INIT_WORK(&dr_wrk->wrk, pci_devices_present_work);
1551 dr->device_count = relations->device_count;
1552 if (dr->device_count != 0) {
1553 memcpy(dr->func, relations->func,
1554 sizeof(struct pci_function_description) *
1558 spin_lock_irqsave(&hbus->device_list_lock, flags);
1559 list_add_tail(&dr->list_entry, &hbus->dr_list);
1560 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1563 schedule_work(&dr_wrk->wrk);
1567 * hv_eject_device_work() - Asynchronously handles ejection
1568 * @work: Work struct embedded in internal device struct
1570 * This function handles ejecting a device. Windows will
1571 * attempt to gracefully eject a device, waiting 60 seconds to
1572 * hear back from the guest OS that this completed successfully.
1573 * If this timer expires, the device will be forcibly removed.
1575 static void hv_eject_device_work(struct work_struct *work)
1577 struct pci_eject_response *ejct_pkt;
1578 struct hv_pcibus_device *hbus;
1579 struct hv_pci_dev *hpdev;
1580 struct pci_dev *pdev;
1581 unsigned long flags;
1584 struct pci_packet pkt;
1585 u8 buffer[sizeof(struct pci_eject_response)];
1588 hpdev = container_of(work, struct hv_pci_dev, wrk);
1591 if (hpdev->state != hv_pcichild_ejecting) {
1592 put_pcichild(hpdev, hv_pcidev_ref_pnp);
1597 * Ejection can come before or after the PCI bus has been set up, so
1598 * attempt to find it and tear down the bus state, if it exists. This
1599 * must be done without constructs like pci_domain_nr(hbus->pci_bus)
1600 * because hbus->pci_bus may not exist yet.
1602 wslot = wslot_to_devfn(hpdev->desc.win_slot.slot);
1603 pdev = pci_get_domain_bus_and_slot(hbus->sysdata.domain, 0, wslot);
1605 pci_lock_rescan_remove();
1606 pci_stop_and_remove_bus_device(pdev);
1608 pci_unlock_rescan_remove();
1611 spin_lock_irqsave(&hbus->device_list_lock, flags);
1612 list_del(&hpdev->list_entry);
1613 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1615 memset(&ctxt, 0, sizeof(ctxt));
1616 ejct_pkt = (struct pci_eject_response *)&ctxt.pkt.message;
1617 ejct_pkt->message_type.type = PCI_EJECTION_COMPLETE;
1618 ejct_pkt->wslot.slot = hpdev->desc.win_slot.slot;
1619 vmbus_sendpacket(hbus->hdev->channel, ejct_pkt,
1620 sizeof(*ejct_pkt), (unsigned long)&ctxt.pkt,
1621 VM_PKT_DATA_INBAND, 0);
1623 put_pcichild(hpdev, hv_pcidev_ref_childlist);
1624 put_pcichild(hpdev, hv_pcidev_ref_initial);
1625 put_pcichild(hpdev, hv_pcidev_ref_pnp);
1627 /* hpdev has been freed. Do not use it any more. */
1632 * hv_pci_eject_device() - Handles device ejection
1633 * @hpdev: Internal device tracking struct
1635 * This function is invoked when an ejection packet arrives. It
1636 * just schedules work so that we don't re-enter the packet
1637 * delivery code handling the ejection.
1639 static void hv_pci_eject_device(struct hv_pci_dev *hpdev)
1641 hpdev->state = hv_pcichild_ejecting;
1642 get_pcichild(hpdev, hv_pcidev_ref_pnp);
1643 INIT_WORK(&hpdev->wrk, hv_eject_device_work);
1644 get_hvpcibus(hpdev->hbus);
1645 schedule_work(&hpdev->wrk);
1649 * hv_pci_onchannelcallback() - Handles incoming packets
1650 * @context: Internal bus tracking struct
1652 * This function is invoked whenever the host sends a packet to
1653 * this channel (which is private to this root PCI bus).
1655 static void hv_pci_onchannelcallback(void *context)
1657 const int packet_size = 0x100;
1659 struct hv_pcibus_device *hbus = context;
1662 struct vmpacket_descriptor *desc;
1663 unsigned char *buffer;
1664 int bufferlen = packet_size;
1665 struct pci_packet *comp_packet;
1666 struct pci_response *response;
1667 struct pci_incoming_message *new_message;
1668 struct pci_bus_relations *bus_rel;
1669 struct pci_dev_incoming *dev_message;
1670 struct hv_pci_dev *hpdev;
1672 buffer = kmalloc(bufferlen, GFP_ATOMIC);
1677 ret = vmbus_recvpacket_raw(hbus->hdev->channel, buffer,
1678 bufferlen, &bytes_recvd, &req_id);
1680 if (ret == -ENOBUFS) {
1682 /* Handle large packet */
1683 bufferlen = bytes_recvd;
1684 buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
1690 /* Zero length indicates there are no more packets. */
1691 if (ret || !bytes_recvd)
1695 * All incoming packets must be at least as large as a
1698 if (bytes_recvd <= sizeof(struct pci_response))
1700 desc = (struct vmpacket_descriptor *)buffer;
1702 switch (desc->type) {
1706 * The host is trusted, and thus it's safe to interpret
1707 * this transaction ID as a pointer.
1709 comp_packet = (struct pci_packet *)req_id;
1710 response = (struct pci_response *)buffer;
1711 comp_packet->completion_func(comp_packet->compl_ctxt,
1716 case VM_PKT_DATA_INBAND:
1718 new_message = (struct pci_incoming_message *)buffer;
1719 switch (new_message->message_type.type) {
1720 case PCI_BUS_RELATIONS:
1722 bus_rel = (struct pci_bus_relations *)buffer;
1724 offsetof(struct pci_bus_relations, func) +
1725 (sizeof(struct pci_function_description) *
1726 (bus_rel->device_count))) {
1727 dev_err(&hbus->hdev->device,
1728 "bus relations too small\n");
1732 hv_pci_devices_present(hbus, bus_rel);
1737 dev_message = (struct pci_dev_incoming *)buffer;
1738 hpdev = get_pcichild_wslot(hbus,
1739 dev_message->wslot.slot);
1741 hv_pci_eject_device(hpdev);
1743 hv_pcidev_ref_by_slot);
1748 dev_warn(&hbus->hdev->device,
1749 "Unimplemented protocol message %x\n",
1750 new_message->message_type.type);
1756 dev_err(&hbus->hdev->device,
1757 "unhandled packet type %d, tid %llx len %d\n",
1758 desc->type, req_id, bytes_recvd);
1767 * hv_pci_protocol_negotiation() - Set up protocol
1768 * @hdev: VMBus's tracking struct for this root PCI bus
1770 * This driver is intended to support running on Windows 10
1771 * (server) and later versions. It will not run on earlier
1772 * versions, as they assume that many of the operations which
1773 * Linux needs accomplished with a spinlock held were done via
1774 * asynchronous messaging via VMBus. Windows 10 increases the
1775 * surface area of PCI emulation so that these actions can take
1776 * place by suspending a virtual processor for their duration.
1778 * This function negotiates the channel protocol version,
1779 * failing if the host doesn't support the necessary protocol
1782 static int hv_pci_protocol_negotiation(struct hv_device *hdev)
1784 struct pci_version_request *version_req;
1785 struct hv_pci_compl comp_pkt;
1786 struct pci_packet *pkt;
1790 * Initiate the handshake with the host and negotiate
1791 * a version that the host can support. We start with the
1792 * highest version number and go down if the host cannot
1795 pkt = kzalloc(sizeof(*pkt) + sizeof(*version_req), GFP_KERNEL);
1799 init_completion(&comp_pkt.host_event);
1800 pkt->completion_func = hv_pci_generic_compl;
1801 pkt->compl_ctxt = &comp_pkt;
1802 version_req = (struct pci_version_request *)&pkt->message;
1803 version_req->message_type.type = PCI_QUERY_PROTOCOL_VERSION;
1804 version_req->protocol_version = PCI_PROTOCOL_VERSION_CURRENT;
1806 ret = vmbus_sendpacket(hdev->channel, version_req,
1807 sizeof(struct pci_version_request),
1808 (unsigned long)pkt, VM_PKT_DATA_INBAND,
1809 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1813 wait_for_completion(&comp_pkt.host_event);
1815 if (comp_pkt.completion_status < 0) {
1816 dev_err(&hdev->device,
1817 "PCI Pass-through VSP failed version request %x\n",
1818 comp_pkt.completion_status);
1831 * hv_pci_free_bridge_windows() - Release memory regions for the
1833 * @hbus: Root PCI bus, as understood by this driver
1835 static void hv_pci_free_bridge_windows(struct hv_pcibus_device *hbus)
1838 * Set the resources back to the way they looked when they
1839 * were allocated by setting IORESOURCE_BUSY again.
1842 if (hbus->low_mmio_space && hbus->low_mmio_res) {
1843 hbus->low_mmio_res->flags |= IORESOURCE_BUSY;
1844 vmbus_free_mmio(hbus->low_mmio_res->start,
1845 resource_size(hbus->low_mmio_res));
1848 if (hbus->high_mmio_space && hbus->high_mmio_res) {
1849 hbus->high_mmio_res->flags |= IORESOURCE_BUSY;
1850 vmbus_free_mmio(hbus->high_mmio_res->start,
1851 resource_size(hbus->high_mmio_res));
1856 * hv_pci_allocate_bridge_windows() - Allocate memory regions
1858 * @hbus: Root PCI bus, as understood by this driver
1860 * This function calls vmbus_allocate_mmio(), which is itself a
1861 * bit of a compromise. Ideally, we might change the pnp layer
1862 * in the kernel such that it comprehends either PCI devices
1863 * which are "grandchildren of ACPI," with some intermediate bus
1864 * node (in this case, VMBus) or change it such that it
1865 * understands VMBus. The pnp layer, however, has been declared
1866 * deprecated, and not subject to change.
1868 * The workaround, implemented here, is to ask VMBus to allocate
1869 * MMIO space for this bus. VMBus itself knows which ranges are
1870 * appropriate by looking at its own ACPI objects. Then, after
1871 * these ranges are claimed, they're modified to look like they
1872 * would have looked if the ACPI and pnp code had allocated
1873 * bridge windows. These descriptors have to exist in this form
1874 * in order to satisfy the code which will get invoked when the
1875 * endpoint PCI function driver calls request_mem_region() or
1876 * request_mem_region_exclusive().
1878 * Return: 0 on success, -errno on failure
1880 static int hv_pci_allocate_bridge_windows(struct hv_pcibus_device *hbus)
1882 resource_size_t align;
1885 if (hbus->low_mmio_space) {
1886 align = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
1887 ret = vmbus_allocate_mmio(&hbus->low_mmio_res, hbus->hdev, 0,
1888 (u64)(u32)0xffffffff,
1889 hbus->low_mmio_space,
1892 dev_err(&hbus->hdev->device,
1893 "Need %#llx of low MMIO space. Consider reconfiguring the VM.\n",
1894 hbus->low_mmio_space);
1898 /* Modify this resource to become a bridge window. */
1899 hbus->low_mmio_res->flags |= IORESOURCE_WINDOW;
1900 hbus->low_mmio_res->flags &= ~IORESOURCE_BUSY;
1901 pci_add_resource(&hbus->resources_for_children,
1902 hbus->low_mmio_res);
1905 if (hbus->high_mmio_space) {
1906 align = 1ULL << (63 - __builtin_clzll(hbus->high_mmio_space));
1907 ret = vmbus_allocate_mmio(&hbus->high_mmio_res, hbus->hdev,
1909 hbus->high_mmio_space, align,
1912 dev_err(&hbus->hdev->device,
1913 "Need %#llx of high MMIO space. Consider reconfiguring the VM.\n",
1914 hbus->high_mmio_space);
1915 goto release_low_mmio;
1918 /* Modify this resource to become a bridge window. */
1919 hbus->high_mmio_res->flags |= IORESOURCE_WINDOW;
1920 hbus->high_mmio_res->flags &= ~IORESOURCE_BUSY;
1921 pci_add_resource(&hbus->resources_for_children,
1922 hbus->high_mmio_res);
1928 if (hbus->low_mmio_res) {
1929 vmbus_free_mmio(hbus->low_mmio_res->start,
1930 resource_size(hbus->low_mmio_res));
1937 * hv_allocate_config_window() - Find MMIO space for PCI Config
1938 * @hbus: Root PCI bus, as understood by this driver
1940 * This function claims memory-mapped I/O space for accessing
1941 * configuration space for the functions on this bus.
1943 * Return: 0 on success, -errno on failure
1945 static int hv_allocate_config_window(struct hv_pcibus_device *hbus)
1950 * Set up a region of MMIO space to use for accessing configuration
1953 ret = vmbus_allocate_mmio(&hbus->mem_config, hbus->hdev, 0, -1,
1954 PCI_CONFIG_MMIO_LENGTH, 0x1000, false);
1959 * vmbus_allocate_mmio() gets used for allocating both device endpoint
1960 * resource claims (those which cannot be overlapped) and the ranges
1961 * which are valid for the children of this bus, which are intended
1962 * to be overlapped by those children. Set the flag on this claim
1963 * meaning that this region can't be overlapped.
1966 hbus->mem_config->flags |= IORESOURCE_BUSY;
1971 static void hv_free_config_window(struct hv_pcibus_device *hbus)
1973 vmbus_free_mmio(hbus->mem_config->start, PCI_CONFIG_MMIO_LENGTH);
1977 * hv_pci_enter_d0() - Bring the "bus" into the D0 power state
1978 * @hdev: VMBus's tracking struct for this root PCI bus
1980 * Return: 0 on success, -errno on failure
1982 static int hv_pci_enter_d0(struct hv_device *hdev)
1984 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
1985 struct pci_bus_d0_entry *d0_entry;
1986 struct hv_pci_compl comp_pkt;
1987 struct pci_packet *pkt;
1991 * Tell the host that the bus is ready to use, and moved into the
1992 * powered-on state. This includes telling the host which region
1993 * of memory-mapped I/O space has been chosen for configuration space
1996 pkt = kzalloc(sizeof(*pkt) + sizeof(*d0_entry), GFP_KERNEL);
2000 init_completion(&comp_pkt.host_event);
2001 pkt->completion_func = hv_pci_generic_compl;
2002 pkt->compl_ctxt = &comp_pkt;
2003 d0_entry = (struct pci_bus_d0_entry *)&pkt->message;
2004 d0_entry->message_type.type = PCI_BUS_D0ENTRY;
2005 d0_entry->mmio_base = hbus->mem_config->start;
2007 ret = vmbus_sendpacket(hdev->channel, d0_entry, sizeof(*d0_entry),
2008 (unsigned long)pkt, VM_PKT_DATA_INBAND,
2009 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2013 wait_for_completion(&comp_pkt.host_event);
2015 if (comp_pkt.completion_status < 0) {
2016 dev_err(&hdev->device,
2017 "PCI Pass-through VSP failed D0 Entry with status %x\n",
2018 comp_pkt.completion_status);
2031 * hv_pci_query_relations() - Ask host to send list of child
2033 * @hdev: VMBus's tracking struct for this root PCI bus
2035 * Return: 0 on success, -errno on failure
2037 static int hv_pci_query_relations(struct hv_device *hdev)
2039 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2040 struct pci_message message;
2041 struct completion comp;
2044 /* Ask the host to send along the list of child devices */
2045 init_completion(&comp);
2046 if (cmpxchg(&hbus->survey_event, NULL, &comp))
2049 memset(&message, 0, sizeof(message));
2050 message.type = PCI_QUERY_BUS_RELATIONS;
2052 ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
2053 0, VM_PKT_DATA_INBAND, 0);
2057 wait_for_completion(&comp);
2062 * hv_send_resources_allocated() - Report local resource choices
2063 * @hdev: VMBus's tracking struct for this root PCI bus
2065 * The host OS is expecting to be sent a request as a message
2066 * which contains all the resources that the device will use.
2067 * The response contains those same resources, "translated"
2068 * which is to say, the values which should be used by the
2069 * hardware, when it delivers an interrupt. (MMIO resources are
2070 * used in local terms.) This is nice for Windows, and lines up
2071 * with the FDO/PDO split, which doesn't exist in Linux. Linux
2072 * is deeply expecting to scan an emulated PCI configuration
2073 * space. So this message is sent here only to drive the state
2074 * machine on the host forward.
2076 * Return: 0 on success, -errno on failure
2078 static int hv_send_resources_allocated(struct hv_device *hdev)
2080 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2081 struct pci_resources_assigned *res_assigned;
2082 struct hv_pci_compl comp_pkt;
2083 struct hv_pci_dev *hpdev;
2084 struct pci_packet *pkt;
2088 pkt = kmalloc(sizeof(*pkt) + sizeof(*res_assigned), GFP_KERNEL);
2094 for (wslot = 0; wslot < 256; wslot++) {
2095 hpdev = get_pcichild_wslot(hbus, wslot);
2099 memset(pkt, 0, sizeof(*pkt) + sizeof(*res_assigned));
2100 init_completion(&comp_pkt.host_event);
2101 pkt->completion_func = hv_pci_generic_compl;
2102 pkt->compl_ctxt = &comp_pkt;
2103 res_assigned = (struct pci_resources_assigned *)&pkt->message;
2104 res_assigned->message_type.type = PCI_RESOURCES_ASSIGNED;
2105 res_assigned->wslot.slot = hpdev->desc.win_slot.slot;
2107 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
2109 ret = vmbus_sendpacket(
2110 hdev->channel, &pkt->message,
2111 sizeof(*res_assigned),
2114 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2118 wait_for_completion(&comp_pkt.host_event);
2120 if (comp_pkt.completion_status < 0) {
2122 dev_err(&hdev->device,
2123 "resource allocated returned 0x%x",
2124 comp_pkt.completion_status);
2134 * hv_send_resources_released() - Report local resources
2136 * @hdev: VMBus's tracking struct for this root PCI bus
2138 * Return: 0 on success, -errno on failure
2140 static int hv_send_resources_released(struct hv_device *hdev)
2142 struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2143 struct pci_child_message pkt;
2144 struct hv_pci_dev *hpdev;
2148 for (wslot = 0; wslot < 256; wslot++) {
2149 hpdev = get_pcichild_wslot(hbus, wslot);
2153 memset(&pkt, 0, sizeof(pkt));
2154 pkt.message_type.type = PCI_RESOURCES_RELEASED;
2155 pkt.wslot.slot = hpdev->desc.win_slot.slot;
2157 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
2159 ret = vmbus_sendpacket(hdev->channel, &pkt, sizeof(pkt), 0,
2160 VM_PKT_DATA_INBAND, 0);
2168 static void get_hvpcibus(struct hv_pcibus_device *hbus)
2170 atomic_inc(&hbus->remove_lock);
2173 static void put_hvpcibus(struct hv_pcibus_device *hbus)
2175 if (atomic_dec_and_test(&hbus->remove_lock))
2176 complete(&hbus->remove_event);
2180 * hv_pci_probe() - New VMBus channel probe, for a root PCI bus
2181 * @hdev: VMBus's tracking struct for this root PCI bus
2182 * @dev_id: Identifies the device itself
2184 * Return: 0 on success, -errno on failure
2186 static int hv_pci_probe(struct hv_device *hdev,
2187 const struct hv_vmbus_device_id *dev_id)
2189 struct hv_pcibus_device *hbus;
2192 hbus = kzalloc(sizeof(*hbus), GFP_KERNEL);
2195 hbus->state = hv_pcibus_init;
2198 * The PCI bus "domain" is what is called "segment" in ACPI and
2199 * other specs. Pull it from the instance ID, to get something
2200 * unique. Bytes 8 and 9 are what is used in Windows guests, so
2201 * do the same thing for consistency. Note that, since this code
2202 * only runs in a Hyper-V VM, Hyper-V can (and does) guarantee
2203 * that (1) the only domain in use for something that looks like
2204 * a physical PCI bus (which is actually emulated by the
2205 * hypervisor) is domain 0 and (2) there will be no overlap
2206 * between domains derived from these instance IDs in the same
2209 hbus->sysdata.domain = hdev->dev_instance.b[9] |
2210 hdev->dev_instance.b[8] << 8;
2213 atomic_inc(&hbus->remove_lock);
2214 INIT_LIST_HEAD(&hbus->children);
2215 INIT_LIST_HEAD(&hbus->dr_list);
2216 INIT_LIST_HEAD(&hbus->resources_for_children);
2217 spin_lock_init(&hbus->config_lock);
2218 spin_lock_init(&hbus->device_list_lock);
2219 sema_init(&hbus->enum_sem, 1);
2220 init_completion(&hbus->remove_event);
2222 ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
2223 hv_pci_onchannelcallback, hbus);
2227 hv_set_drvdata(hdev, hbus);
2229 ret = hv_pci_protocol_negotiation(hdev);
2233 ret = hv_allocate_config_window(hbus);
2237 hbus->cfg_addr = ioremap(hbus->mem_config->start,
2238 PCI_CONFIG_MMIO_LENGTH);
2239 if (!hbus->cfg_addr) {
2240 dev_err(&hdev->device,
2241 "Unable to map a virtual address for config space\n");
2246 hbus->sysdata.fwnode = irq_domain_alloc_fwnode(hbus);
2247 if (!hbus->sysdata.fwnode) {
2252 ret = hv_pcie_init_irq_domain(hbus);
2256 ret = hv_pci_query_relations(hdev);
2258 goto free_irq_domain;
2260 ret = hv_pci_enter_d0(hdev);
2262 goto free_irq_domain;
2264 ret = hv_pci_allocate_bridge_windows(hbus);
2266 goto free_irq_domain;
2268 ret = hv_send_resources_allocated(hdev);
2272 prepopulate_bars(hbus);
2274 hbus->state = hv_pcibus_probed;
2276 ret = create_root_hv_pci_bus(hbus);
2283 hv_pci_free_bridge_windows(hbus);
2285 irq_domain_remove(hbus->irq_domain);
2287 irq_domain_free_fwnode(hbus->sysdata.fwnode);
2289 iounmap(hbus->cfg_addr);
2291 hv_free_config_window(hbus);
2293 vmbus_close(hdev->channel);
2300 * hv_pci_remove() - Remove routine for this VMBus channel
2301 * @hdev: VMBus's tracking struct for this root PCI bus
2303 * Return: 0 on success, -errno on failure
2305 static int hv_pci_remove(struct hv_device *hdev)
2308 struct hv_pcibus_device *hbus;
2310 struct pci_packet teardown_packet;
2313 struct pci_bus_relations relations;
2314 struct hv_pci_compl comp_pkt;
2316 hbus = hv_get_drvdata(hdev);
2318 memset(&pkt.teardown_packet, 0, sizeof(pkt.teardown_packet));
2319 init_completion(&comp_pkt.host_event);
2320 pkt.teardown_packet.completion_func = hv_pci_generic_compl;
2321 pkt.teardown_packet.compl_ctxt = &comp_pkt;
2322 pkt.teardown_packet.message[0].type = PCI_BUS_D0EXIT;
2324 ret = vmbus_sendpacket(hdev->channel, &pkt.teardown_packet.message,
2325 sizeof(struct pci_message),
2326 (unsigned long)&pkt.teardown_packet,
2328 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2330 wait_for_completion_timeout(&comp_pkt.host_event, 10 * HZ);
2332 if (hbus->state == hv_pcibus_installed) {
2333 /* Remove the bus from PCI's point of view. */
2334 pci_lock_rescan_remove();
2335 pci_stop_root_bus(hbus->pci_bus);
2336 pci_remove_root_bus(hbus->pci_bus);
2337 pci_unlock_rescan_remove();
2338 hbus->state = hv_pcibus_removed;
2341 ret = hv_send_resources_released(hdev);
2343 dev_err(&hdev->device,
2344 "Couldn't send resources released packet(s)\n");
2346 vmbus_close(hdev->channel);
2348 /* Delete any children which might still exist. */
2349 memset(&relations, 0, sizeof(relations));
2350 hv_pci_devices_present(hbus, &relations);
2352 iounmap(hbus->cfg_addr);
2353 hv_free_config_window(hbus);
2354 pci_free_resource_list(&hbus->resources_for_children);
2355 hv_pci_free_bridge_windows(hbus);
2356 irq_domain_remove(hbus->irq_domain);
2357 irq_domain_free_fwnode(hbus->sysdata.fwnode);
2359 wait_for_completion(&hbus->remove_event);
2364 static const struct hv_vmbus_device_id hv_pci_id_table[] = {
2365 /* PCI Pass-through Class ID */
2366 /* 44C4F61D-4444-4400-9D52-802E27EDE19F */
2371 MODULE_DEVICE_TABLE(vmbus, hv_pci_id_table);
2373 static struct hv_driver hv_pci_drv = {
2375 .id_table = hv_pci_id_table,
2376 .probe = hv_pci_probe,
2377 .remove = hv_pci_remove,
2380 static void __exit exit_hv_pci_drv(void)
2382 vmbus_driver_unregister(&hv_pci_drv);
2385 static int __init init_hv_pci_drv(void)
2387 return vmbus_driver_register(&hv_pci_drv);
2390 module_init(init_hv_pci_drv);
2391 module_exit(exit_hv_pci_drv);
2393 MODULE_DESCRIPTION("Hyper-V PCI");
2394 MODULE_LICENSE("GPL v2");