GNU Linux-libre 6.7.9-gnu
[releases.git] / drivers / pci / controller / pci-hyperv.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) Microsoft Corporation.
4  *
5  * Author:
6  *   Jake Oshins <jakeo@microsoft.com>
7  *
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.
15  *
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.
21  *
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.
31  *
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.
38  */
39
40 #include <linux/kernel.h>
41 #include <linux/module.h>
42 #include <linux/pci.h>
43 #include <linux/pci-ecam.h>
44 #include <linux/delay.h>
45 #include <linux/semaphore.h>
46 #include <linux/irq.h>
47 #include <linux/msi.h>
48 #include <linux/hyperv.h>
49 #include <linux/refcount.h>
50 #include <linux/irqdomain.h>
51 #include <linux/acpi.h>
52 #include <asm/mshyperv.h>
53
54 /*
55  * Protocol versions. The low word is the minor version, the high word the
56  * major version.
57  */
58
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)
62
63 enum pci_protocol_version_t {
64         PCI_PROTOCOL_VERSION_1_1 = PCI_MAKE_VERSION(1, 1),      /* Win10 */
65         PCI_PROTOCOL_VERSION_1_2 = PCI_MAKE_VERSION(1, 2),      /* RS1 */
66         PCI_PROTOCOL_VERSION_1_3 = PCI_MAKE_VERSION(1, 3),      /* Vibranium */
67         PCI_PROTOCOL_VERSION_1_4 = PCI_MAKE_VERSION(1, 4),      /* WS2022 */
68 };
69
70 #define CPU_AFFINITY_ALL        -1ULL
71
72 /*
73  * Supported protocol versions in the order of probing - highest go
74  * first.
75  */
76 static enum pci_protocol_version_t pci_protocol_versions[] = {
77         PCI_PROTOCOL_VERSION_1_4,
78         PCI_PROTOCOL_VERSION_1_3,
79         PCI_PROTOCOL_VERSION_1_2,
80         PCI_PROTOCOL_VERSION_1_1,
81 };
82
83 #define PCI_CONFIG_MMIO_LENGTH  0x2000
84 #define CFG_PAGE_OFFSET 0x1000
85 #define CFG_PAGE_SIZE (PCI_CONFIG_MMIO_LENGTH - CFG_PAGE_OFFSET)
86
87 #define MAX_SUPPORTED_MSI_MESSAGES 0x400
88
89 #define STATUS_REVISION_MISMATCH 0xC0000059
90
91 /* space for 32bit serial number as string */
92 #define SLOT_NAME_SIZE 11
93
94 /*
95  * Size of requestor for VMbus; the value is based on the observation
96  * that having more than one request outstanding is 'rare', and so 64
97  * should be generous in ensuring that we don't ever run out.
98  */
99 #define HV_PCI_RQSTOR_SIZE 64
100
101 /*
102  * Message Types
103  */
104
105 enum pci_message_type {
106         /*
107          * Version 1.1
108          */
109         PCI_MESSAGE_BASE                = 0x42490000,
110         PCI_BUS_RELATIONS               = PCI_MESSAGE_BASE + 0,
111         PCI_QUERY_BUS_RELATIONS         = PCI_MESSAGE_BASE + 1,
112         PCI_POWER_STATE_CHANGE          = PCI_MESSAGE_BASE + 4,
113         PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5,
114         PCI_QUERY_RESOURCE_RESOURCES    = PCI_MESSAGE_BASE + 6,
115         PCI_BUS_D0ENTRY                 = PCI_MESSAGE_BASE + 7,
116         PCI_BUS_D0EXIT                  = PCI_MESSAGE_BASE + 8,
117         PCI_READ_BLOCK                  = PCI_MESSAGE_BASE + 9,
118         PCI_WRITE_BLOCK                 = PCI_MESSAGE_BASE + 0xA,
119         PCI_EJECT                       = PCI_MESSAGE_BASE + 0xB,
120         PCI_QUERY_STOP                  = PCI_MESSAGE_BASE + 0xC,
121         PCI_REENABLE                    = PCI_MESSAGE_BASE + 0xD,
122         PCI_QUERY_STOP_FAILED           = PCI_MESSAGE_BASE + 0xE,
123         PCI_EJECTION_COMPLETE           = PCI_MESSAGE_BASE + 0xF,
124         PCI_RESOURCES_ASSIGNED          = PCI_MESSAGE_BASE + 0x10,
125         PCI_RESOURCES_RELEASED          = PCI_MESSAGE_BASE + 0x11,
126         PCI_INVALIDATE_BLOCK            = PCI_MESSAGE_BASE + 0x12,
127         PCI_QUERY_PROTOCOL_VERSION      = PCI_MESSAGE_BASE + 0x13,
128         PCI_CREATE_INTERRUPT_MESSAGE    = PCI_MESSAGE_BASE + 0x14,
129         PCI_DELETE_INTERRUPT_MESSAGE    = PCI_MESSAGE_BASE + 0x15,
130         PCI_RESOURCES_ASSIGNED2         = PCI_MESSAGE_BASE + 0x16,
131         PCI_CREATE_INTERRUPT_MESSAGE2   = PCI_MESSAGE_BASE + 0x17,
132         PCI_DELETE_INTERRUPT_MESSAGE2   = PCI_MESSAGE_BASE + 0x18, /* unused */
133         PCI_BUS_RELATIONS2              = PCI_MESSAGE_BASE + 0x19,
134         PCI_RESOURCES_ASSIGNED3         = PCI_MESSAGE_BASE + 0x1A,
135         PCI_CREATE_INTERRUPT_MESSAGE3   = PCI_MESSAGE_BASE + 0x1B,
136         PCI_MESSAGE_MAXIMUM
137 };
138
139 /*
140  * Structures defining the virtual PCI Express protocol.
141  */
142
143 union pci_version {
144         struct {
145                 u16 minor_version;
146                 u16 major_version;
147         } parts;
148         u32 version;
149 } __packed;
150
151 /*
152  * Function numbers are 8-bits wide on Express, as interpreted through ARI,
153  * which is all this driver does.  This representation is the one used in
154  * Windows, which is what is expected when sending this back and forth with
155  * the Hyper-V parent partition.
156  */
157 union win_slot_encoding {
158         struct {
159                 u32     dev:5;
160                 u32     func:3;
161                 u32     reserved:24;
162         } bits;
163         u32 slot;
164 } __packed;
165
166 /*
167  * Pretty much as defined in the PCI Specifications.
168  */
169 struct pci_function_description {
170         u16     v_id;   /* vendor ID */
171         u16     d_id;   /* device ID */
172         u8      rev;
173         u8      prog_intf;
174         u8      subclass;
175         u8      base_class;
176         u32     subsystem_id;
177         union win_slot_encoding win_slot;
178         u32     ser;    /* serial number */
179 } __packed;
180
181 enum pci_device_description_flags {
182         HV_PCI_DEVICE_FLAG_NONE                 = 0x0,
183         HV_PCI_DEVICE_FLAG_NUMA_AFFINITY        = 0x1,
184 };
185
186 struct pci_function_description2 {
187         u16     v_id;   /* vendor ID */
188         u16     d_id;   /* device ID */
189         u8      rev;
190         u8      prog_intf;
191         u8      subclass;
192         u8      base_class;
193         u32     subsystem_id;
194         union   win_slot_encoding win_slot;
195         u32     ser;    /* serial number */
196         u32     flags;
197         u16     virtual_numa_node;
198         u16     reserved;
199 } __packed;
200
201 /**
202  * struct hv_msi_desc
203  * @vector:             IDT entry
204  * @delivery_mode:      As defined in Intel's Programmer's
205  *                      Reference Manual, Volume 3, Chapter 8.
206  * @vector_count:       Number of contiguous entries in the
207  *                      Interrupt Descriptor Table that are
208  *                      occupied by this Message-Signaled
209  *                      Interrupt. For "MSI", as first defined
210  *                      in PCI 2.2, this can be between 1 and
211  *                      32. For "MSI-X," as first defined in PCI
212  *                      3.0, this must be 1, as each MSI-X table
213  *                      entry would have its own descriptor.
214  * @reserved:           Empty space
215  * @cpu_mask:           All the target virtual processors.
216  */
217 struct hv_msi_desc {
218         u8      vector;
219         u8      delivery_mode;
220         u16     vector_count;
221         u32     reserved;
222         u64     cpu_mask;
223 } __packed;
224
225 /**
226  * struct hv_msi_desc2 - 1.2 version of hv_msi_desc
227  * @vector:             IDT entry
228  * @delivery_mode:      As defined in Intel's Programmer's
229  *                      Reference Manual, Volume 3, Chapter 8.
230  * @vector_count:       Number of contiguous entries in the
231  *                      Interrupt Descriptor Table that are
232  *                      occupied by this Message-Signaled
233  *                      Interrupt. For "MSI", as first defined
234  *                      in PCI 2.2, this can be between 1 and
235  *                      32. For "MSI-X," as first defined in PCI
236  *                      3.0, this must be 1, as each MSI-X table
237  *                      entry would have its own descriptor.
238  * @processor_count:    number of bits enabled in array.
239  * @processor_array:    All the target virtual processors.
240  */
241 struct hv_msi_desc2 {
242         u8      vector;
243         u8      delivery_mode;
244         u16     vector_count;
245         u16     processor_count;
246         u16     processor_array[32];
247 } __packed;
248
249 /*
250  * struct hv_msi_desc3 - 1.3 version of hv_msi_desc
251  *      Everything is the same as in 'hv_msi_desc2' except that the size of the
252  *      'vector' field is larger to support bigger vector values. For ex: LPI
253  *      vectors on ARM.
254  */
255 struct hv_msi_desc3 {
256         u32     vector;
257         u8      delivery_mode;
258         u8      reserved;
259         u16     vector_count;
260         u16     processor_count;
261         u16     processor_array[32];
262 } __packed;
263
264 /**
265  * struct tran_int_desc
266  * @reserved:           unused, padding
267  * @vector_count:       same as in hv_msi_desc
268  * @data:               This is the "data payload" value that is
269  *                      written by the device when it generates
270  *                      a message-signaled interrupt, either MSI
271  *                      or MSI-X.
272  * @address:            This is the address to which the data
273  *                      payload is written on interrupt
274  *                      generation.
275  */
276 struct tran_int_desc {
277         u16     reserved;
278         u16     vector_count;
279         u32     data;
280         u64     address;
281 } __packed;
282
283 /*
284  * A generic message format for virtual PCI.
285  * Specific message formats are defined later in the file.
286  */
287
288 struct pci_message {
289         u32 type;
290 } __packed;
291
292 struct pci_child_message {
293         struct pci_message message_type;
294         union win_slot_encoding wslot;
295 } __packed;
296
297 struct pci_incoming_message {
298         struct vmpacket_descriptor hdr;
299         struct pci_message message_type;
300 } __packed;
301
302 struct pci_response {
303         struct vmpacket_descriptor hdr;
304         s32 status;                     /* negative values are failures */
305 } __packed;
306
307 struct pci_packet {
308         void (*completion_func)(void *context, struct pci_response *resp,
309                                 int resp_packet_size);
310         void *compl_ctxt;
311
312         struct pci_message message[];
313 };
314
315 /*
316  * Specific message types supporting the PCI protocol.
317  */
318
319 /*
320  * Version negotiation message. Sent from the guest to the host.
321  * The guest is free to try different versions until the host
322  * accepts the version.
323  *
324  * pci_version: The protocol version requested.
325  * is_last_attempt: If TRUE, this is the last version guest will request.
326  * reservedz: Reserved field, set to zero.
327  */
328
329 struct pci_version_request {
330         struct pci_message message_type;
331         u32 protocol_version;
332 } __packed;
333
334 /*
335  * Bus D0 Entry.  This is sent from the guest to the host when the virtual
336  * bus (PCI Express port) is ready for action.
337  */
338
339 struct pci_bus_d0_entry {
340         struct pci_message message_type;
341         u32 reserved;
342         u64 mmio_base;
343 } __packed;
344
345 struct pci_bus_relations {
346         struct pci_incoming_message incoming;
347         u32 device_count;
348         struct pci_function_description func[];
349 } __packed;
350
351 struct pci_bus_relations2 {
352         struct pci_incoming_message incoming;
353         u32 device_count;
354         struct pci_function_description2 func[];
355 } __packed;
356
357 struct pci_q_res_req_response {
358         struct vmpacket_descriptor hdr;
359         s32 status;                     /* negative values are failures */
360         u32 probed_bar[PCI_STD_NUM_BARS];
361 } __packed;
362
363 struct pci_set_power {
364         struct pci_message message_type;
365         union win_slot_encoding wslot;
366         u32 power_state;                /* In Windows terms */
367         u32 reserved;
368 } __packed;
369
370 struct pci_set_power_response {
371         struct vmpacket_descriptor hdr;
372         s32 status;                     /* negative values are failures */
373         union win_slot_encoding wslot;
374         u32 resultant_state;            /* In Windows terms */
375         u32 reserved;
376 } __packed;
377
378 struct pci_resources_assigned {
379         struct pci_message message_type;
380         union win_slot_encoding wslot;
381         u8 memory_range[0x14][6];       /* not used here */
382         u32 msi_descriptors;
383         u32 reserved[4];
384 } __packed;
385
386 struct pci_resources_assigned2 {
387         struct pci_message message_type;
388         union win_slot_encoding wslot;
389         u8 memory_range[0x14][6];       /* not used here */
390         u32 msi_descriptor_count;
391         u8 reserved[70];
392 } __packed;
393
394 struct pci_create_interrupt {
395         struct pci_message message_type;
396         union win_slot_encoding wslot;
397         struct hv_msi_desc int_desc;
398 } __packed;
399
400 struct pci_create_int_response {
401         struct pci_response response;
402         u32 reserved;
403         struct tran_int_desc int_desc;
404 } __packed;
405
406 struct pci_create_interrupt2 {
407         struct pci_message message_type;
408         union win_slot_encoding wslot;
409         struct hv_msi_desc2 int_desc;
410 } __packed;
411
412 struct pci_create_interrupt3 {
413         struct pci_message message_type;
414         union win_slot_encoding wslot;
415         struct hv_msi_desc3 int_desc;
416 } __packed;
417
418 struct pci_delete_interrupt {
419         struct pci_message message_type;
420         union win_slot_encoding wslot;
421         struct tran_int_desc int_desc;
422 } __packed;
423
424 /*
425  * Note: the VM must pass a valid block id, wslot and bytes_requested.
426  */
427 struct pci_read_block {
428         struct pci_message message_type;
429         u32 block_id;
430         union win_slot_encoding wslot;
431         u32 bytes_requested;
432 } __packed;
433
434 struct pci_read_block_response {
435         struct vmpacket_descriptor hdr;
436         u32 status;
437         u8 bytes[HV_CONFIG_BLOCK_SIZE_MAX];
438 } __packed;
439
440 /*
441  * Note: the VM must pass a valid block id, wslot and byte_count.
442  */
443 struct pci_write_block {
444         struct pci_message message_type;
445         u32 block_id;
446         union win_slot_encoding wslot;
447         u32 byte_count;
448         u8 bytes[HV_CONFIG_BLOCK_SIZE_MAX];
449 } __packed;
450
451 struct pci_dev_inval_block {
452         struct pci_incoming_message incoming;
453         union win_slot_encoding wslot;
454         u64 block_mask;
455 } __packed;
456
457 struct pci_dev_incoming {
458         struct pci_incoming_message incoming;
459         union win_slot_encoding wslot;
460 } __packed;
461
462 struct pci_eject_response {
463         struct pci_message message_type;
464         union win_slot_encoding wslot;
465         u32 status;
466 } __packed;
467
468 static int pci_ring_size = (4 * PAGE_SIZE);
469
470 /*
471  * Driver specific state.
472  */
473
474 enum hv_pcibus_state {
475         hv_pcibus_init = 0,
476         hv_pcibus_probed,
477         hv_pcibus_installed,
478         hv_pcibus_removing,
479         hv_pcibus_maximum
480 };
481
482 struct hv_pcibus_device {
483 #ifdef CONFIG_X86
484         struct pci_sysdata sysdata;
485 #elif defined(CONFIG_ARM64)
486         struct pci_config_window sysdata;
487 #endif
488         struct pci_host_bridge *bridge;
489         struct fwnode_handle *fwnode;
490         /* Protocol version negotiated with the host */
491         enum pci_protocol_version_t protocol_version;
492
493         struct mutex state_lock;
494         enum hv_pcibus_state state;
495
496         struct hv_device *hdev;
497         resource_size_t low_mmio_space;
498         resource_size_t high_mmio_space;
499         struct resource *mem_config;
500         struct resource *low_mmio_res;
501         struct resource *high_mmio_res;
502         struct completion *survey_event;
503         struct pci_bus *pci_bus;
504         spinlock_t config_lock; /* Avoid two threads writing index page */
505         spinlock_t device_list_lock;    /* Protect lists below */
506         void __iomem *cfg_addr;
507
508         struct list_head children;
509         struct list_head dr_list;
510
511         struct msi_domain_info msi_info;
512         struct irq_domain *irq_domain;
513
514         struct workqueue_struct *wq;
515
516         /* Highest slot of child device with resources allocated */
517         int wslot_res_allocated;
518         bool use_calls; /* Use hypercalls to access mmio cfg space */
519 };
520
521 /*
522  * Tracks "Device Relations" messages from the host, which must be both
523  * processed in order and deferred so that they don't run in the context
524  * of the incoming packet callback.
525  */
526 struct hv_dr_work {
527         struct work_struct wrk;
528         struct hv_pcibus_device *bus;
529 };
530
531 struct hv_pcidev_description {
532         u16     v_id;   /* vendor ID */
533         u16     d_id;   /* device ID */
534         u8      rev;
535         u8      prog_intf;
536         u8      subclass;
537         u8      base_class;
538         u32     subsystem_id;
539         union   win_slot_encoding win_slot;
540         u32     ser;    /* serial number */
541         u32     flags;
542         u16     virtual_numa_node;
543 };
544
545 struct hv_dr_state {
546         struct list_head list_entry;
547         u32 device_count;
548         struct hv_pcidev_description func[] __counted_by(device_count);
549 };
550
551 struct hv_pci_dev {
552         /* List protected by pci_rescan_remove_lock */
553         struct list_head list_entry;
554         refcount_t refs;
555         struct pci_slot *pci_slot;
556         struct hv_pcidev_description desc;
557         bool reported_missing;
558         struct hv_pcibus_device *hbus;
559         struct work_struct wrk;
560
561         void (*block_invalidate)(void *context, u64 block_mask);
562         void *invalidate_context;
563
564         /*
565          * What would be observed if one wrote 0xFFFFFFFF to a BAR and then
566          * read it back, for each of the BAR offsets within config space.
567          */
568         u32 probed_bar[PCI_STD_NUM_BARS];
569 };
570
571 struct hv_pci_compl {
572         struct completion host_event;
573         s32 completion_status;
574 };
575
576 static void hv_pci_onchannelcallback(void *context);
577
578 #ifdef CONFIG_X86
579 #define DELIVERY_MODE   APIC_DELIVERY_MODE_FIXED
580 #define FLOW_HANDLER    handle_edge_irq
581 #define FLOW_NAME       "edge"
582
583 static int hv_pci_irqchip_init(void)
584 {
585         return 0;
586 }
587
588 static struct irq_domain *hv_pci_get_root_domain(void)
589 {
590         return x86_vector_domain;
591 }
592
593 static unsigned int hv_msi_get_int_vector(struct irq_data *data)
594 {
595         struct irq_cfg *cfg = irqd_cfg(data);
596
597         return cfg->vector;
598 }
599
600 #define hv_msi_prepare          pci_msi_prepare
601
602 /**
603  * hv_arch_irq_unmask() - "Unmask" the IRQ by setting its current
604  * affinity.
605  * @data:       Describes the IRQ
606  *
607  * Build new a destination for the MSI and make a hypercall to
608  * update the Interrupt Redirection Table. "Device Logical ID"
609  * is built out of this PCI bus's instance GUID and the function
610  * number of the device.
611  */
612 static void hv_arch_irq_unmask(struct irq_data *data)
613 {
614         struct msi_desc *msi_desc = irq_data_get_msi_desc(data);
615         struct hv_retarget_device_interrupt *params;
616         struct tran_int_desc *int_desc;
617         struct hv_pcibus_device *hbus;
618         const struct cpumask *dest;
619         cpumask_var_t tmp;
620         struct pci_bus *pbus;
621         struct pci_dev *pdev;
622         unsigned long flags;
623         u32 var_size = 0;
624         int cpu, nr_bank;
625         u64 res;
626
627         dest = irq_data_get_effective_affinity_mask(data);
628         pdev = msi_desc_to_pci_dev(msi_desc);
629         pbus = pdev->bus;
630         hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
631         int_desc = data->chip_data;
632         if (!int_desc) {
633                 dev_warn(&hbus->hdev->device, "%s() can not unmask irq %u\n",
634                          __func__, data->irq);
635                 return;
636         }
637
638         local_irq_save(flags);
639
640         params = *this_cpu_ptr(hyperv_pcpu_input_arg);
641         memset(params, 0, sizeof(*params));
642         params->partition_id = HV_PARTITION_ID_SELF;
643         params->int_entry.source = HV_INTERRUPT_SOURCE_MSI;
644         params->int_entry.msi_entry.address.as_uint32 = int_desc->address & 0xffffffff;
645         params->int_entry.msi_entry.data.as_uint32 = int_desc->data;
646         params->device_id = (hbus->hdev->dev_instance.b[5] << 24) |
647                            (hbus->hdev->dev_instance.b[4] << 16) |
648                            (hbus->hdev->dev_instance.b[7] << 8) |
649                            (hbus->hdev->dev_instance.b[6] & 0xf8) |
650                            PCI_FUNC(pdev->devfn);
651         params->int_target.vector = hv_msi_get_int_vector(data);
652
653         /*
654          * Honoring apic->delivery_mode set to APIC_DELIVERY_MODE_FIXED by
655          * setting the HV_DEVICE_INTERRUPT_TARGET_MULTICAST flag results in a
656          * spurious interrupt storm. Not doing so does not seem to have a
657          * negative effect (yet?).
658          */
659
660         if (hbus->protocol_version >= PCI_PROTOCOL_VERSION_1_2) {
661                 /*
662                  * PCI_PROTOCOL_VERSION_1_2 supports the VP_SET version of the
663                  * HVCALL_RETARGET_INTERRUPT hypercall, which also coincides
664                  * with >64 VP support.
665                  * ms_hyperv.hints & HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED
666                  * is not sufficient for this hypercall.
667                  */
668                 params->int_target.flags |=
669                         HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET;
670
671                 if (!alloc_cpumask_var(&tmp, GFP_ATOMIC)) {
672                         res = 1;
673                         goto out;
674                 }
675
676                 cpumask_and(tmp, dest, cpu_online_mask);
677                 nr_bank = cpumask_to_vpset(&params->int_target.vp_set, tmp);
678                 free_cpumask_var(tmp);
679
680                 if (nr_bank <= 0) {
681                         res = 1;
682                         goto out;
683                 }
684
685                 /*
686                  * var-sized hypercall, var-size starts after vp_mask (thus
687                  * vp_set.format does not count, but vp_set.valid_bank_mask
688                  * does).
689                  */
690                 var_size = 1 + nr_bank;
691         } else {
692                 for_each_cpu_and(cpu, dest, cpu_online_mask) {
693                         params->int_target.vp_mask |=
694                                 (1ULL << hv_cpu_number_to_vp_number(cpu));
695                 }
696         }
697
698         res = hv_do_hypercall(HVCALL_RETARGET_INTERRUPT | (var_size << 17),
699                               params, NULL);
700
701 out:
702         local_irq_restore(flags);
703
704         /*
705          * During hibernation, when a CPU is offlined, the kernel tries
706          * to move the interrupt to the remaining CPUs that haven't
707          * been offlined yet. In this case, the below hv_do_hypercall()
708          * always fails since the vmbus channel has been closed:
709          * refer to cpu_disable_common() -> fixup_irqs() ->
710          * irq_migrate_all_off_this_cpu() -> migrate_one_irq().
711          *
712          * Suppress the error message for hibernation because the failure
713          * during hibernation does not matter (at this time all the devices
714          * have been frozen). Note: the correct affinity info is still updated
715          * into the irqdata data structure in migrate_one_irq() ->
716          * irq_do_set_affinity(), so later when the VM resumes,
717          * hv_pci_restore_msi_state() is able to correctly restore the
718          * interrupt with the correct affinity.
719          */
720         if (!hv_result_success(res) && hbus->state != hv_pcibus_removing)
721                 dev_err(&hbus->hdev->device,
722                         "%s() failed: %#llx", __func__, res);
723 }
724 #elif defined(CONFIG_ARM64)
725 /*
726  * SPI vectors to use for vPCI; arch SPIs range is [32, 1019], but leaving a bit
727  * of room at the start to allow for SPIs to be specified through ACPI and
728  * starting with a power of two to satisfy power of 2 multi-MSI requirement.
729  */
730 #define HV_PCI_MSI_SPI_START    64
731 #define HV_PCI_MSI_SPI_NR       (1020 - HV_PCI_MSI_SPI_START)
732 #define DELIVERY_MODE           0
733 #define FLOW_HANDLER            NULL
734 #define FLOW_NAME               NULL
735 #define hv_msi_prepare          NULL
736
737 struct hv_pci_chip_data {
738         DECLARE_BITMAP(spi_map, HV_PCI_MSI_SPI_NR);
739         struct mutex    map_lock;
740 };
741
742 /* Hyper-V vPCI MSI GIC IRQ domain */
743 static struct irq_domain *hv_msi_gic_irq_domain;
744
745 /* Hyper-V PCI MSI IRQ chip */
746 static struct irq_chip hv_arm64_msi_irq_chip = {
747         .name = "MSI",
748         .irq_set_affinity = irq_chip_set_affinity_parent,
749         .irq_eoi = irq_chip_eoi_parent,
750         .irq_mask = irq_chip_mask_parent,
751         .irq_unmask = irq_chip_unmask_parent
752 };
753
754 static unsigned int hv_msi_get_int_vector(struct irq_data *irqd)
755 {
756         return irqd->parent_data->hwirq;
757 }
758
759 /*
760  * @nr_bm_irqs:         Indicates the number of IRQs that were allocated from
761  *                      the bitmap.
762  * @nr_dom_irqs:        Indicates the number of IRQs that were allocated from
763  *                      the parent domain.
764  */
765 static void hv_pci_vec_irq_free(struct irq_domain *domain,
766                                 unsigned int virq,
767                                 unsigned int nr_bm_irqs,
768                                 unsigned int nr_dom_irqs)
769 {
770         struct hv_pci_chip_data *chip_data = domain->host_data;
771         struct irq_data *d = irq_domain_get_irq_data(domain, virq);
772         int first = d->hwirq - HV_PCI_MSI_SPI_START;
773         int i;
774
775         mutex_lock(&chip_data->map_lock);
776         bitmap_release_region(chip_data->spi_map,
777                               first,
778                               get_count_order(nr_bm_irqs));
779         mutex_unlock(&chip_data->map_lock);
780         for (i = 0; i < nr_dom_irqs; i++) {
781                 if (i)
782                         d = irq_domain_get_irq_data(domain, virq + i);
783                 irq_domain_reset_irq_data(d);
784         }
785
786         irq_domain_free_irqs_parent(domain, virq, nr_dom_irqs);
787 }
788
789 static void hv_pci_vec_irq_domain_free(struct irq_domain *domain,
790                                        unsigned int virq,
791                                        unsigned int nr_irqs)
792 {
793         hv_pci_vec_irq_free(domain, virq, nr_irqs, nr_irqs);
794 }
795
796 static int hv_pci_vec_alloc_device_irq(struct irq_domain *domain,
797                                        unsigned int nr_irqs,
798                                        irq_hw_number_t *hwirq)
799 {
800         struct hv_pci_chip_data *chip_data = domain->host_data;
801         int index;
802
803         /* Find and allocate region from the SPI bitmap */
804         mutex_lock(&chip_data->map_lock);
805         index = bitmap_find_free_region(chip_data->spi_map,
806                                         HV_PCI_MSI_SPI_NR,
807                                         get_count_order(nr_irqs));
808         mutex_unlock(&chip_data->map_lock);
809         if (index < 0)
810                 return -ENOSPC;
811
812         *hwirq = index + HV_PCI_MSI_SPI_START;
813
814         return 0;
815 }
816
817 static int hv_pci_vec_irq_gic_domain_alloc(struct irq_domain *domain,
818                                            unsigned int virq,
819                                            irq_hw_number_t hwirq)
820 {
821         struct irq_fwspec fwspec;
822         struct irq_data *d;
823         int ret;
824
825         fwspec.fwnode = domain->parent->fwnode;
826         fwspec.param_count = 2;
827         fwspec.param[0] = hwirq;
828         fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
829
830         ret = irq_domain_alloc_irqs_parent(domain, virq, 1, &fwspec);
831         if (ret)
832                 return ret;
833
834         /*
835          * Since the interrupt specifier is not coming from ACPI or DT, the
836          * trigger type will need to be set explicitly. Otherwise, it will be
837          * set to whatever is in the GIC configuration.
838          */
839         d = irq_domain_get_irq_data(domain->parent, virq);
840
841         return d->chip->irq_set_type(d, IRQ_TYPE_EDGE_RISING);
842 }
843
844 static int hv_pci_vec_irq_domain_alloc(struct irq_domain *domain,
845                                        unsigned int virq, unsigned int nr_irqs,
846                                        void *args)
847 {
848         irq_hw_number_t hwirq;
849         unsigned int i;
850         int ret;
851
852         ret = hv_pci_vec_alloc_device_irq(domain, nr_irqs, &hwirq);
853         if (ret)
854                 return ret;
855
856         for (i = 0; i < nr_irqs; i++) {
857                 ret = hv_pci_vec_irq_gic_domain_alloc(domain, virq + i,
858                                                       hwirq + i);
859                 if (ret) {
860                         hv_pci_vec_irq_free(domain, virq, nr_irqs, i);
861                         return ret;
862                 }
863
864                 irq_domain_set_hwirq_and_chip(domain, virq + i,
865                                               hwirq + i,
866                                               &hv_arm64_msi_irq_chip,
867                                               domain->host_data);
868                 pr_debug("pID:%d vID:%u\n", (int)(hwirq + i), virq + i);
869         }
870
871         return 0;
872 }
873
874 /*
875  * Pick the first cpu as the irq affinity that can be temporarily used for
876  * composing MSI from the hypervisor. GIC will eventually set the right
877  * affinity for the irq and the 'unmask' will retarget the interrupt to that
878  * cpu.
879  */
880 static int hv_pci_vec_irq_domain_activate(struct irq_domain *domain,
881                                           struct irq_data *irqd, bool reserve)
882 {
883         int cpu = cpumask_first(cpu_present_mask);
884
885         irq_data_update_effective_affinity(irqd, cpumask_of(cpu));
886
887         return 0;
888 }
889
890 static const struct irq_domain_ops hv_pci_domain_ops = {
891         .alloc  = hv_pci_vec_irq_domain_alloc,
892         .free   = hv_pci_vec_irq_domain_free,
893         .activate = hv_pci_vec_irq_domain_activate,
894 };
895
896 static int hv_pci_irqchip_init(void)
897 {
898         static struct hv_pci_chip_data *chip_data;
899         struct fwnode_handle *fn = NULL;
900         int ret = -ENOMEM;
901
902         chip_data = kzalloc(sizeof(*chip_data), GFP_KERNEL);
903         if (!chip_data)
904                 return ret;
905
906         mutex_init(&chip_data->map_lock);
907         fn = irq_domain_alloc_named_fwnode("hv_vpci_arm64");
908         if (!fn)
909                 goto free_chip;
910
911         /*
912          * IRQ domain once enabled, should not be removed since there is no
913          * way to ensure that all the corresponding devices are also gone and
914          * no interrupts will be generated.
915          */
916         hv_msi_gic_irq_domain = acpi_irq_create_hierarchy(0, HV_PCI_MSI_SPI_NR,
917                                                           fn, &hv_pci_domain_ops,
918                                                           chip_data);
919
920         if (!hv_msi_gic_irq_domain) {
921                 pr_err("Failed to create Hyper-V arm64 vPCI MSI IRQ domain\n");
922                 goto free_chip;
923         }
924
925         return 0;
926
927 free_chip:
928         kfree(chip_data);
929         if (fn)
930                 irq_domain_free_fwnode(fn);
931
932         return ret;
933 }
934
935 static struct irq_domain *hv_pci_get_root_domain(void)
936 {
937         return hv_msi_gic_irq_domain;
938 }
939
940 /*
941  * SPIs are used for interrupts of PCI devices and SPIs is managed via GICD
942  * registers which Hyper-V already supports, so no hypercall needed.
943  */
944 static void hv_arch_irq_unmask(struct irq_data *data) { }
945 #endif /* CONFIG_ARM64 */
946
947 /**
948  * hv_pci_generic_compl() - Invoked for a completion packet
949  * @context:            Set up by the sender of the packet.
950  * @resp:               The response packet
951  * @resp_packet_size:   Size in bytes of the packet
952  *
953  * This function is used to trigger an event and report status
954  * for any message for which the completion packet contains a
955  * status and nothing else.
956  */
957 static void hv_pci_generic_compl(void *context, struct pci_response *resp,
958                                  int resp_packet_size)
959 {
960         struct hv_pci_compl *comp_pkt = context;
961
962         comp_pkt->completion_status = resp->status;
963         complete(&comp_pkt->host_event);
964 }
965
966 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
967                                                 u32 wslot);
968
969 static void get_pcichild(struct hv_pci_dev *hpdev)
970 {
971         refcount_inc(&hpdev->refs);
972 }
973
974 static void put_pcichild(struct hv_pci_dev *hpdev)
975 {
976         if (refcount_dec_and_test(&hpdev->refs))
977                 kfree(hpdev);
978 }
979
980 /*
981  * There is no good way to get notified from vmbus_onoffer_rescind(),
982  * so let's use polling here, since this is not a hot path.
983  */
984 static int wait_for_response(struct hv_device *hdev,
985                              struct completion *comp)
986 {
987         while (true) {
988                 if (hdev->channel->rescind) {
989                         dev_warn_once(&hdev->device, "The device is gone.\n");
990                         return -ENODEV;
991                 }
992
993                 if (wait_for_completion_timeout(comp, HZ / 10))
994                         break;
995         }
996
997         return 0;
998 }
999
1000 /**
1001  * devfn_to_wslot() - Convert from Linux PCI slot to Windows
1002  * @devfn:      The Linux representation of PCI slot
1003  *
1004  * Windows uses a slightly different representation of PCI slot.
1005  *
1006  * Return: The Windows representation
1007  */
1008 static u32 devfn_to_wslot(int devfn)
1009 {
1010         union win_slot_encoding wslot;
1011
1012         wslot.slot = 0;
1013         wslot.bits.dev = PCI_SLOT(devfn);
1014         wslot.bits.func = PCI_FUNC(devfn);
1015
1016         return wslot.slot;
1017 }
1018
1019 /**
1020  * wslot_to_devfn() - Convert from Windows PCI slot to Linux
1021  * @wslot:      The Windows representation of PCI slot
1022  *
1023  * Windows uses a slightly different representation of PCI slot.
1024  *
1025  * Return: The Linux representation
1026  */
1027 static int wslot_to_devfn(u32 wslot)
1028 {
1029         union win_slot_encoding slot_no;
1030
1031         slot_no.slot = wslot;
1032         return PCI_DEVFN(slot_no.bits.dev, slot_no.bits.func);
1033 }
1034
1035 static void hv_pci_read_mmio(struct device *dev, phys_addr_t gpa, int size, u32 *val)
1036 {
1037         struct hv_mmio_read_input *in;
1038         struct hv_mmio_read_output *out;
1039         u64 ret;
1040
1041         /*
1042          * Must be called with interrupts disabled so it is safe
1043          * to use the per-cpu input argument page.  Use it for
1044          * both input and output.
1045          */
1046         in = *this_cpu_ptr(hyperv_pcpu_input_arg);
1047         out = *this_cpu_ptr(hyperv_pcpu_input_arg) + sizeof(*in);
1048         in->gpa = gpa;
1049         in->size = size;
1050
1051         ret = hv_do_hypercall(HVCALL_MMIO_READ, in, out);
1052         if (hv_result_success(ret)) {
1053                 switch (size) {
1054                 case 1:
1055                         *val = *(u8 *)(out->data);
1056                         break;
1057                 case 2:
1058                         *val = *(u16 *)(out->data);
1059                         break;
1060                 default:
1061                         *val = *(u32 *)(out->data);
1062                         break;
1063                 }
1064         } else
1065                 dev_err(dev, "MMIO read hypercall error %llx addr %llx size %d\n",
1066                                 ret, gpa, size);
1067 }
1068
1069 static void hv_pci_write_mmio(struct device *dev, phys_addr_t gpa, int size, u32 val)
1070 {
1071         struct hv_mmio_write_input *in;
1072         u64 ret;
1073
1074         /*
1075          * Must be called with interrupts disabled so it is safe
1076          * to use the per-cpu input argument memory.
1077          */
1078         in = *this_cpu_ptr(hyperv_pcpu_input_arg);
1079         in->gpa = gpa;
1080         in->size = size;
1081         switch (size) {
1082         case 1:
1083                 *(u8 *)(in->data) = val;
1084                 break;
1085         case 2:
1086                 *(u16 *)(in->data) = val;
1087                 break;
1088         default:
1089                 *(u32 *)(in->data) = val;
1090                 break;
1091         }
1092
1093         ret = hv_do_hypercall(HVCALL_MMIO_WRITE, in, NULL);
1094         if (!hv_result_success(ret))
1095                 dev_err(dev, "MMIO write hypercall error %llx addr %llx size %d\n",
1096                                 ret, gpa, size);
1097 }
1098
1099 /*
1100  * PCI Configuration Space for these root PCI buses is implemented as a pair
1101  * of pages in memory-mapped I/O space.  Writing to the first page chooses
1102  * the PCI function being written or read.  Once the first page has been
1103  * written to, the following page maps in the entire configuration space of
1104  * the function.
1105  */
1106
1107 /**
1108  * _hv_pcifront_read_config() - Internal PCI config read
1109  * @hpdev:      The PCI driver's representation of the device
1110  * @where:      Offset within config space
1111  * @size:       Size of the transfer
1112  * @val:        Pointer to the buffer receiving the data
1113  */
1114 static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where,
1115                                      int size, u32 *val)
1116 {
1117         struct hv_pcibus_device *hbus = hpdev->hbus;
1118         struct device *dev = &hbus->hdev->device;
1119         int offset = where + CFG_PAGE_OFFSET;
1120         unsigned long flags;
1121
1122         /*
1123          * If the attempt is to read the IDs or the ROM BAR, simulate that.
1124          */
1125         if (where + size <= PCI_COMMAND) {
1126                 memcpy(val, ((u8 *)&hpdev->desc.v_id) + where, size);
1127         } else if (where >= PCI_CLASS_REVISION && where + size <=
1128                    PCI_CACHE_LINE_SIZE) {
1129                 memcpy(val, ((u8 *)&hpdev->desc.rev) + where -
1130                        PCI_CLASS_REVISION, size);
1131         } else if (where >= PCI_SUBSYSTEM_VENDOR_ID && where + size <=
1132                    PCI_ROM_ADDRESS) {
1133                 memcpy(val, (u8 *)&hpdev->desc.subsystem_id + where -
1134                        PCI_SUBSYSTEM_VENDOR_ID, size);
1135         } else if (where >= PCI_ROM_ADDRESS && where + size <=
1136                    PCI_CAPABILITY_LIST) {
1137                 /* ROM BARs are unimplemented */
1138                 *val = 0;
1139         } else if (where >= PCI_INTERRUPT_LINE && where + size <=
1140                    PCI_INTERRUPT_PIN) {
1141                 /*
1142                  * Interrupt Line and Interrupt PIN are hard-wired to zero
1143                  * because this front-end only supports message-signaled
1144                  * interrupts.
1145                  */
1146                 *val = 0;
1147         } else if (where + size <= CFG_PAGE_SIZE) {
1148
1149                 spin_lock_irqsave(&hbus->config_lock, flags);
1150                 if (hbus->use_calls) {
1151                         phys_addr_t addr = hbus->mem_config->start + offset;
1152
1153                         hv_pci_write_mmio(dev, hbus->mem_config->start, 4,
1154                                                 hpdev->desc.win_slot.slot);
1155                         hv_pci_read_mmio(dev, addr, size, val);
1156                 } else {
1157                         void __iomem *addr = hbus->cfg_addr + offset;
1158
1159                         /* Choose the function to be read. (See comment above) */
1160                         writel(hpdev->desc.win_slot.slot, hbus->cfg_addr);
1161                         /* Make sure the function was chosen before reading. */
1162                         mb();
1163                         /* Read from that function's config space. */
1164                         switch (size) {
1165                         case 1:
1166                                 *val = readb(addr);
1167                                 break;
1168                         case 2:
1169                                 *val = readw(addr);
1170                                 break;
1171                         default:
1172                                 *val = readl(addr);
1173                                 break;
1174                         }
1175                         /*
1176                          * Make sure the read was done before we release the
1177                          * spinlock allowing consecutive reads/writes.
1178                          */
1179                         mb();
1180                 }
1181                 spin_unlock_irqrestore(&hbus->config_lock, flags);
1182         } else {
1183                 dev_err(dev, "Attempt to read beyond a function's config space.\n");
1184         }
1185 }
1186
1187 static u16 hv_pcifront_get_vendor_id(struct hv_pci_dev *hpdev)
1188 {
1189         struct hv_pcibus_device *hbus = hpdev->hbus;
1190         struct device *dev = &hbus->hdev->device;
1191         u32 val;
1192         u16 ret;
1193         unsigned long flags;
1194
1195         spin_lock_irqsave(&hbus->config_lock, flags);
1196
1197         if (hbus->use_calls) {
1198                 phys_addr_t addr = hbus->mem_config->start +
1199                                          CFG_PAGE_OFFSET + PCI_VENDOR_ID;
1200
1201                 hv_pci_write_mmio(dev, hbus->mem_config->start, 4,
1202                                         hpdev->desc.win_slot.slot);
1203                 hv_pci_read_mmio(dev, addr, 2, &val);
1204                 ret = val;  /* Truncates to 16 bits */
1205         } else {
1206                 void __iomem *addr = hbus->cfg_addr + CFG_PAGE_OFFSET +
1207                                              PCI_VENDOR_ID;
1208                 /* Choose the function to be read. (See comment above) */
1209                 writel(hpdev->desc.win_slot.slot, hbus->cfg_addr);
1210                 /* Make sure the function was chosen before we start reading. */
1211                 mb();
1212                 /* Read from that function's config space. */
1213                 ret = readw(addr);
1214                 /*
1215                  * mb() is not required here, because the
1216                  * spin_unlock_irqrestore() is a barrier.
1217                  */
1218         }
1219
1220         spin_unlock_irqrestore(&hbus->config_lock, flags);
1221
1222         return ret;
1223 }
1224
1225 /**
1226  * _hv_pcifront_write_config() - Internal PCI config write
1227  * @hpdev:      The PCI driver's representation of the device
1228  * @where:      Offset within config space
1229  * @size:       Size of the transfer
1230  * @val:        The data being transferred
1231  */
1232 static void _hv_pcifront_write_config(struct hv_pci_dev *hpdev, int where,
1233                                       int size, u32 val)
1234 {
1235         struct hv_pcibus_device *hbus = hpdev->hbus;
1236         struct device *dev = &hbus->hdev->device;
1237         int offset = where + CFG_PAGE_OFFSET;
1238         unsigned long flags;
1239
1240         if (where >= PCI_SUBSYSTEM_VENDOR_ID &&
1241             where + size <= PCI_CAPABILITY_LIST) {
1242                 /* SSIDs and ROM BARs are read-only */
1243         } else if (where >= PCI_COMMAND && where + size <= CFG_PAGE_SIZE) {
1244                 spin_lock_irqsave(&hbus->config_lock, flags);
1245
1246                 if (hbus->use_calls) {
1247                         phys_addr_t addr = hbus->mem_config->start + offset;
1248
1249                         hv_pci_write_mmio(dev, hbus->mem_config->start, 4,
1250                                                 hpdev->desc.win_slot.slot);
1251                         hv_pci_write_mmio(dev, addr, size, val);
1252                 } else {
1253                         void __iomem *addr = hbus->cfg_addr + offset;
1254
1255                         /* Choose the function to write. (See comment above) */
1256                         writel(hpdev->desc.win_slot.slot, hbus->cfg_addr);
1257                         /* Make sure the function was chosen before writing. */
1258                         wmb();
1259                         /* Write to that function's config space. */
1260                         switch (size) {
1261                         case 1:
1262                                 writeb(val, addr);
1263                                 break;
1264                         case 2:
1265                                 writew(val, addr);
1266                                 break;
1267                         default:
1268                                 writel(val, addr);
1269                                 break;
1270                         }
1271                         /*
1272                          * Make sure the write was done before we release the
1273                          * spinlock allowing consecutive reads/writes.
1274                          */
1275                         mb();
1276                 }
1277                 spin_unlock_irqrestore(&hbus->config_lock, flags);
1278         } else {
1279                 dev_err(dev, "Attempt to write beyond a function's config space.\n");
1280         }
1281 }
1282
1283 /**
1284  * hv_pcifront_read_config() - Read configuration space
1285  * @bus: PCI Bus structure
1286  * @devfn: Device/function
1287  * @where: Offset from base
1288  * @size: Byte/word/dword
1289  * @val: Value to be read
1290  *
1291  * Return: PCIBIOS_SUCCESSFUL on success
1292  *         PCIBIOS_DEVICE_NOT_FOUND on failure
1293  */
1294 static int hv_pcifront_read_config(struct pci_bus *bus, unsigned int devfn,
1295                                    int where, int size, u32 *val)
1296 {
1297         struct hv_pcibus_device *hbus =
1298                 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
1299         struct hv_pci_dev *hpdev;
1300
1301         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
1302         if (!hpdev)
1303                 return PCIBIOS_DEVICE_NOT_FOUND;
1304
1305         _hv_pcifront_read_config(hpdev, where, size, val);
1306
1307         put_pcichild(hpdev);
1308         return PCIBIOS_SUCCESSFUL;
1309 }
1310
1311 /**
1312  * hv_pcifront_write_config() - Write configuration space
1313  * @bus: PCI Bus structure
1314  * @devfn: Device/function
1315  * @where: Offset from base
1316  * @size: Byte/word/dword
1317  * @val: Value to be written to device
1318  *
1319  * Return: PCIBIOS_SUCCESSFUL on success
1320  *         PCIBIOS_DEVICE_NOT_FOUND on failure
1321  */
1322 static int hv_pcifront_write_config(struct pci_bus *bus, unsigned int devfn,
1323                                     int where, int size, u32 val)
1324 {
1325         struct hv_pcibus_device *hbus =
1326             container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
1327         struct hv_pci_dev *hpdev;
1328
1329         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
1330         if (!hpdev)
1331                 return PCIBIOS_DEVICE_NOT_FOUND;
1332
1333         _hv_pcifront_write_config(hpdev, where, size, val);
1334
1335         put_pcichild(hpdev);
1336         return PCIBIOS_SUCCESSFUL;
1337 }
1338
1339 /* PCIe operations */
1340 static struct pci_ops hv_pcifront_ops = {
1341         .read  = hv_pcifront_read_config,
1342         .write = hv_pcifront_write_config,
1343 };
1344
1345 /*
1346  * Paravirtual backchannel
1347  *
1348  * Hyper-V SR-IOV provides a backchannel mechanism in software for
1349  * communication between a VF driver and a PF driver.  These
1350  * "configuration blocks" are similar in concept to PCI configuration space,
1351  * but instead of doing reads and writes in 32-bit chunks through a very slow
1352  * path, packets of up to 128 bytes can be sent or received asynchronously.
1353  *
1354  * Nearly every SR-IOV device contains just such a communications channel in
1355  * hardware, so using this one in software is usually optional.  Using the
1356  * software channel, however, allows driver implementers to leverage software
1357  * tools that fuzz the communications channel looking for vulnerabilities.
1358  *
1359  * The usage model for these packets puts the responsibility for reading or
1360  * writing on the VF driver.  The VF driver sends a read or a write packet,
1361  * indicating which "block" is being referred to by number.
1362  *
1363  * If the PF driver wishes to initiate communication, it can "invalidate" one or
1364  * more of the first 64 blocks.  This invalidation is delivered via a callback
1365  * supplied by the VF driver by this driver.
1366  *
1367  * No protocol is implied, except that supplied by the PF and VF drivers.
1368  */
1369
1370 struct hv_read_config_compl {
1371         struct hv_pci_compl comp_pkt;
1372         void *buf;
1373         unsigned int len;
1374         unsigned int bytes_returned;
1375 };
1376
1377 /**
1378  * hv_pci_read_config_compl() - Invoked when a response packet
1379  * for a read config block operation arrives.
1380  * @context:            Identifies the read config operation
1381  * @resp:               The response packet itself
1382  * @resp_packet_size:   Size in bytes of the response packet
1383  */
1384 static void hv_pci_read_config_compl(void *context, struct pci_response *resp,
1385                                      int resp_packet_size)
1386 {
1387         struct hv_read_config_compl *comp = context;
1388         struct pci_read_block_response *read_resp =
1389                 (struct pci_read_block_response *)resp;
1390         unsigned int data_len, hdr_len;
1391
1392         hdr_len = offsetof(struct pci_read_block_response, bytes);
1393         if (resp_packet_size < hdr_len) {
1394                 comp->comp_pkt.completion_status = -1;
1395                 goto out;
1396         }
1397
1398         data_len = resp_packet_size - hdr_len;
1399         if (data_len > 0 && read_resp->status == 0) {
1400                 comp->bytes_returned = min(comp->len, data_len);
1401                 memcpy(comp->buf, read_resp->bytes, comp->bytes_returned);
1402         } else {
1403                 comp->bytes_returned = 0;
1404         }
1405
1406         comp->comp_pkt.completion_status = read_resp->status;
1407 out:
1408         complete(&comp->comp_pkt.host_event);
1409 }
1410
1411 /**
1412  * hv_read_config_block() - Sends a read config block request to
1413  * the back-end driver running in the Hyper-V parent partition.
1414  * @pdev:               The PCI driver's representation for this device.
1415  * @buf:                Buffer into which the config block will be copied.
1416  * @len:                Size in bytes of buf.
1417  * @block_id:           Identifies the config block which has been requested.
1418  * @bytes_returned:     Size which came back from the back-end driver.
1419  *
1420  * Return: 0 on success, -errno on failure
1421  */
1422 static int hv_read_config_block(struct pci_dev *pdev, void *buf,
1423                                 unsigned int len, unsigned int block_id,
1424                                 unsigned int *bytes_returned)
1425 {
1426         struct hv_pcibus_device *hbus =
1427                 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1428                              sysdata);
1429         struct {
1430                 struct pci_packet pkt;
1431                 char buf[sizeof(struct pci_read_block)];
1432         } pkt;
1433         struct hv_read_config_compl comp_pkt;
1434         struct pci_read_block *read_blk;
1435         int ret;
1436
1437         if (len == 0 || len > HV_CONFIG_BLOCK_SIZE_MAX)
1438                 return -EINVAL;
1439
1440         init_completion(&comp_pkt.comp_pkt.host_event);
1441         comp_pkt.buf = buf;
1442         comp_pkt.len = len;
1443
1444         memset(&pkt, 0, sizeof(pkt));
1445         pkt.pkt.completion_func = hv_pci_read_config_compl;
1446         pkt.pkt.compl_ctxt = &comp_pkt;
1447         read_blk = (struct pci_read_block *)&pkt.pkt.message;
1448         read_blk->message_type.type = PCI_READ_BLOCK;
1449         read_blk->wslot.slot = devfn_to_wslot(pdev->devfn);
1450         read_blk->block_id = block_id;
1451         read_blk->bytes_requested = len;
1452
1453         ret = vmbus_sendpacket(hbus->hdev->channel, read_blk,
1454                                sizeof(*read_blk), (unsigned long)&pkt.pkt,
1455                                VM_PKT_DATA_INBAND,
1456                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1457         if (ret)
1458                 return ret;
1459
1460         ret = wait_for_response(hbus->hdev, &comp_pkt.comp_pkt.host_event);
1461         if (ret)
1462                 return ret;
1463
1464         if (comp_pkt.comp_pkt.completion_status != 0 ||
1465             comp_pkt.bytes_returned == 0) {
1466                 dev_err(&hbus->hdev->device,
1467                         "Read Config Block failed: 0x%x, bytes_returned=%d\n",
1468                         comp_pkt.comp_pkt.completion_status,
1469                         comp_pkt.bytes_returned);
1470                 return -EIO;
1471         }
1472
1473         *bytes_returned = comp_pkt.bytes_returned;
1474         return 0;
1475 }
1476
1477 /**
1478  * hv_pci_write_config_compl() - Invoked when a response packet for a write
1479  * config block operation arrives.
1480  * @context:            Identifies the write config operation
1481  * @resp:               The response packet itself
1482  * @resp_packet_size:   Size in bytes of the response packet
1483  */
1484 static void hv_pci_write_config_compl(void *context, struct pci_response *resp,
1485                                       int resp_packet_size)
1486 {
1487         struct hv_pci_compl *comp_pkt = context;
1488
1489         comp_pkt->completion_status = resp->status;
1490         complete(&comp_pkt->host_event);
1491 }
1492
1493 /**
1494  * hv_write_config_block() - Sends a write config block request to the
1495  * back-end driver running in the Hyper-V parent partition.
1496  * @pdev:               The PCI driver's representation for this device.
1497  * @buf:                Buffer from which the config block will be copied.
1498  * @len:                Size in bytes of buf.
1499  * @block_id:           Identifies the config block which is being written.
1500  *
1501  * Return: 0 on success, -errno on failure
1502  */
1503 static int hv_write_config_block(struct pci_dev *pdev, void *buf,
1504                                 unsigned int len, unsigned int block_id)
1505 {
1506         struct hv_pcibus_device *hbus =
1507                 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1508                              sysdata);
1509         struct {
1510                 struct pci_packet pkt;
1511                 char buf[sizeof(struct pci_write_block)];
1512                 u32 reserved;
1513         } pkt;
1514         struct hv_pci_compl comp_pkt;
1515         struct pci_write_block *write_blk;
1516         u32 pkt_size;
1517         int ret;
1518
1519         if (len == 0 || len > HV_CONFIG_BLOCK_SIZE_MAX)
1520                 return -EINVAL;
1521
1522         init_completion(&comp_pkt.host_event);
1523
1524         memset(&pkt, 0, sizeof(pkt));
1525         pkt.pkt.completion_func = hv_pci_write_config_compl;
1526         pkt.pkt.compl_ctxt = &comp_pkt;
1527         write_blk = (struct pci_write_block *)&pkt.pkt.message;
1528         write_blk->message_type.type = PCI_WRITE_BLOCK;
1529         write_blk->wslot.slot = devfn_to_wslot(pdev->devfn);
1530         write_blk->block_id = block_id;
1531         write_blk->byte_count = len;
1532         memcpy(write_blk->bytes, buf, len);
1533         pkt_size = offsetof(struct pci_write_block, bytes) + len;
1534         /*
1535          * This quirk is required on some hosts shipped around 2018, because
1536          * these hosts don't check the pkt_size correctly (new hosts have been
1537          * fixed since early 2019). The quirk is also safe on very old hosts
1538          * and new hosts, because, on them, what really matters is the length
1539          * specified in write_blk->byte_count.
1540          */
1541         pkt_size += sizeof(pkt.reserved);
1542
1543         ret = vmbus_sendpacket(hbus->hdev->channel, write_blk, pkt_size,
1544                                (unsigned long)&pkt.pkt, VM_PKT_DATA_INBAND,
1545                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1546         if (ret)
1547                 return ret;
1548
1549         ret = wait_for_response(hbus->hdev, &comp_pkt.host_event);
1550         if (ret)
1551                 return ret;
1552
1553         if (comp_pkt.completion_status != 0) {
1554                 dev_err(&hbus->hdev->device,
1555                         "Write Config Block failed: 0x%x\n",
1556                         comp_pkt.completion_status);
1557                 return -EIO;
1558         }
1559
1560         return 0;
1561 }
1562
1563 /**
1564  * hv_register_block_invalidate() - Invoked when a config block invalidation
1565  * arrives from the back-end driver.
1566  * @pdev:               The PCI driver's representation for this device.
1567  * @context:            Identifies the device.
1568  * @block_invalidate:   Identifies all of the blocks being invalidated.
1569  *
1570  * Return: 0 on success, -errno on failure
1571  */
1572 static int hv_register_block_invalidate(struct pci_dev *pdev, void *context,
1573                                         void (*block_invalidate)(void *context,
1574                                                                  u64 block_mask))
1575 {
1576         struct hv_pcibus_device *hbus =
1577                 container_of(pdev->bus->sysdata, struct hv_pcibus_device,
1578                              sysdata);
1579         struct hv_pci_dev *hpdev;
1580
1581         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1582         if (!hpdev)
1583                 return -ENODEV;
1584
1585         hpdev->block_invalidate = block_invalidate;
1586         hpdev->invalidate_context = context;
1587
1588         put_pcichild(hpdev);
1589         return 0;
1590
1591 }
1592
1593 /* Interrupt management hooks */
1594 static void hv_int_desc_free(struct hv_pci_dev *hpdev,
1595                              struct tran_int_desc *int_desc)
1596 {
1597         struct pci_delete_interrupt *int_pkt;
1598         struct {
1599                 struct pci_packet pkt;
1600                 u8 buffer[sizeof(struct pci_delete_interrupt)];
1601         } ctxt;
1602
1603         if (!int_desc->vector_count) {
1604                 kfree(int_desc);
1605                 return;
1606         }
1607         memset(&ctxt, 0, sizeof(ctxt));
1608         int_pkt = (struct pci_delete_interrupt *)&ctxt.pkt.message;
1609         int_pkt->message_type.type =
1610                 PCI_DELETE_INTERRUPT_MESSAGE;
1611         int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
1612         int_pkt->int_desc = *int_desc;
1613         vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt, sizeof(*int_pkt),
1614                          0, VM_PKT_DATA_INBAND, 0);
1615         kfree(int_desc);
1616 }
1617
1618 /**
1619  * hv_msi_free() - Free the MSI.
1620  * @domain:     The interrupt domain pointer
1621  * @info:       Extra MSI-related context
1622  * @irq:        Identifies the IRQ.
1623  *
1624  * The Hyper-V parent partition and hypervisor are tracking the
1625  * messages that are in use, keeping the interrupt redirection
1626  * table up to date.  This callback sends a message that frees
1627  * the IRT entry and related tracking nonsense.
1628  */
1629 static void hv_msi_free(struct irq_domain *domain, struct msi_domain_info *info,
1630                         unsigned int irq)
1631 {
1632         struct hv_pcibus_device *hbus;
1633         struct hv_pci_dev *hpdev;
1634         struct pci_dev *pdev;
1635         struct tran_int_desc *int_desc;
1636         struct irq_data *irq_data = irq_domain_get_irq_data(domain, irq);
1637         struct msi_desc *msi = irq_data_get_msi_desc(irq_data);
1638
1639         pdev = msi_desc_to_pci_dev(msi);
1640         hbus = info->data;
1641         int_desc = irq_data_get_irq_chip_data(irq_data);
1642         if (!int_desc)
1643                 return;
1644
1645         irq_data->chip_data = NULL;
1646         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1647         if (!hpdev) {
1648                 kfree(int_desc);
1649                 return;
1650         }
1651
1652         hv_int_desc_free(hpdev, int_desc);
1653         put_pcichild(hpdev);
1654 }
1655
1656 static void hv_irq_mask(struct irq_data *data)
1657 {
1658         pci_msi_mask_irq(data);
1659         if (data->parent_data->chip->irq_mask)
1660                 irq_chip_mask_parent(data);
1661 }
1662
1663 static void hv_irq_unmask(struct irq_data *data)
1664 {
1665         hv_arch_irq_unmask(data);
1666
1667         if (data->parent_data->chip->irq_unmask)
1668                 irq_chip_unmask_parent(data);
1669         pci_msi_unmask_irq(data);
1670 }
1671
1672 struct compose_comp_ctxt {
1673         struct hv_pci_compl comp_pkt;
1674         struct tran_int_desc int_desc;
1675 };
1676
1677 static void hv_pci_compose_compl(void *context, struct pci_response *resp,
1678                                  int resp_packet_size)
1679 {
1680         struct compose_comp_ctxt *comp_pkt = context;
1681         struct pci_create_int_response *int_resp =
1682                 (struct pci_create_int_response *)resp;
1683
1684         if (resp_packet_size < sizeof(*int_resp)) {
1685                 comp_pkt->comp_pkt.completion_status = -1;
1686                 goto out;
1687         }
1688         comp_pkt->comp_pkt.completion_status = resp->status;
1689         comp_pkt->int_desc = int_resp->int_desc;
1690 out:
1691         complete(&comp_pkt->comp_pkt.host_event);
1692 }
1693
1694 static u32 hv_compose_msi_req_v1(
1695         struct pci_create_interrupt *int_pkt,
1696         u32 slot, u8 vector, u16 vector_count)
1697 {
1698         int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE;
1699         int_pkt->wslot.slot = slot;
1700         int_pkt->int_desc.vector = vector;
1701         int_pkt->int_desc.vector_count = vector_count;
1702         int_pkt->int_desc.delivery_mode = DELIVERY_MODE;
1703
1704         /*
1705          * Create MSI w/ dummy vCPU set, overwritten by subsequent retarget in
1706          * hv_irq_unmask().
1707          */
1708         int_pkt->int_desc.cpu_mask = CPU_AFFINITY_ALL;
1709
1710         return sizeof(*int_pkt);
1711 }
1712
1713 /*
1714  * The vCPU selected by hv_compose_multi_msi_req_get_cpu() and
1715  * hv_compose_msi_req_get_cpu() is a "dummy" vCPU because the final vCPU to be
1716  * interrupted is specified later in hv_irq_unmask() and communicated to Hyper-V
1717  * via the HVCALL_RETARGET_INTERRUPT hypercall. But the choice of dummy vCPU is
1718  * not irrelevant because Hyper-V chooses the physical CPU to handle the
1719  * interrupts based on the vCPU specified in message sent to the vPCI VSP in
1720  * hv_compose_msi_msg(). Hyper-V's choice of pCPU is not visible to the guest,
1721  * but assigning too many vPCI device interrupts to the same pCPU can cause a
1722  * performance bottleneck. So we spread out the dummy vCPUs to influence Hyper-V
1723  * to spread out the pCPUs that it selects.
1724  *
1725  * For the single-MSI and MSI-X cases, it's OK for hv_compose_msi_req_get_cpu()
1726  * to always return the same dummy vCPU, because a second call to
1727  * hv_compose_msi_msg() contains the "real" vCPU, causing Hyper-V to choose a
1728  * new pCPU for the interrupt. But for the multi-MSI case, the second call to
1729  * hv_compose_msi_msg() exits without sending a message to the vPCI VSP, so the
1730  * original dummy vCPU is used. This dummy vCPU must be round-robin'ed so that
1731  * the pCPUs are spread out. All interrupts for a multi-MSI device end up using
1732  * the same pCPU, even though the vCPUs will be spread out by later calls
1733  * to hv_irq_unmask(), but that is the best we can do now.
1734  *
1735  * With Hyper-V in Nov 2022, the HVCALL_RETARGET_INTERRUPT hypercall does *not*
1736  * cause Hyper-V to reselect the pCPU based on the specified vCPU. Such an
1737  * enhancement is planned for a future version. With that enhancement, the
1738  * dummy vCPU selection won't matter, and interrupts for the same multi-MSI
1739  * device will be spread across multiple pCPUs.
1740  */
1741
1742 /*
1743  * Create MSI w/ dummy vCPU set targeting just one vCPU, overwritten
1744  * by subsequent retarget in hv_irq_unmask().
1745  */
1746 static int hv_compose_msi_req_get_cpu(const struct cpumask *affinity)
1747 {
1748         return cpumask_first_and(affinity, cpu_online_mask);
1749 }
1750
1751 /*
1752  * Make sure the dummy vCPU values for multi-MSI don't all point to vCPU0.
1753  */
1754 static int hv_compose_multi_msi_req_get_cpu(void)
1755 {
1756         static DEFINE_SPINLOCK(multi_msi_cpu_lock);
1757
1758         /* -1 means starting with CPU 0 */
1759         static int cpu_next = -1;
1760
1761         unsigned long flags;
1762         int cpu;
1763
1764         spin_lock_irqsave(&multi_msi_cpu_lock, flags);
1765
1766         cpu_next = cpumask_next_wrap(cpu_next, cpu_online_mask, nr_cpu_ids,
1767                                      false);
1768         cpu = cpu_next;
1769
1770         spin_unlock_irqrestore(&multi_msi_cpu_lock, flags);
1771
1772         return cpu;
1773 }
1774
1775 static u32 hv_compose_msi_req_v2(
1776         struct pci_create_interrupt2 *int_pkt, int cpu,
1777         u32 slot, u8 vector, u16 vector_count)
1778 {
1779         int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE2;
1780         int_pkt->wslot.slot = slot;
1781         int_pkt->int_desc.vector = vector;
1782         int_pkt->int_desc.vector_count = vector_count;
1783         int_pkt->int_desc.delivery_mode = DELIVERY_MODE;
1784         int_pkt->int_desc.processor_array[0] =
1785                 hv_cpu_number_to_vp_number(cpu);
1786         int_pkt->int_desc.processor_count = 1;
1787
1788         return sizeof(*int_pkt);
1789 }
1790
1791 static u32 hv_compose_msi_req_v3(
1792         struct pci_create_interrupt3 *int_pkt, int cpu,
1793         u32 slot, u32 vector, u16 vector_count)
1794 {
1795         int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE3;
1796         int_pkt->wslot.slot = slot;
1797         int_pkt->int_desc.vector = vector;
1798         int_pkt->int_desc.reserved = 0;
1799         int_pkt->int_desc.vector_count = vector_count;
1800         int_pkt->int_desc.delivery_mode = DELIVERY_MODE;
1801         int_pkt->int_desc.processor_array[0] =
1802                 hv_cpu_number_to_vp_number(cpu);
1803         int_pkt->int_desc.processor_count = 1;
1804
1805         return sizeof(*int_pkt);
1806 }
1807
1808 /**
1809  * hv_compose_msi_msg() - Supplies a valid MSI address/data
1810  * @data:       Everything about this MSI
1811  * @msg:        Buffer that is filled in by this function
1812  *
1813  * This function unpacks the IRQ looking for target CPU set, IDT
1814  * vector and mode and sends a message to the parent partition
1815  * asking for a mapping for that tuple in this partition.  The
1816  * response supplies a data value and address to which that data
1817  * should be written to trigger that interrupt.
1818  */
1819 static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
1820 {
1821         struct hv_pcibus_device *hbus;
1822         struct vmbus_channel *channel;
1823         struct hv_pci_dev *hpdev;
1824         struct pci_bus *pbus;
1825         struct pci_dev *pdev;
1826         const struct cpumask *dest;
1827         struct compose_comp_ctxt comp;
1828         struct tran_int_desc *int_desc;
1829         struct msi_desc *msi_desc;
1830         /*
1831          * vector_count should be u16: see hv_msi_desc, hv_msi_desc2
1832          * and hv_msi_desc3. vector must be u32: see hv_msi_desc3.
1833          */
1834         u16 vector_count;
1835         u32 vector;
1836         struct {
1837                 struct pci_packet pci_pkt;
1838                 union {
1839                         struct pci_create_interrupt v1;
1840                         struct pci_create_interrupt2 v2;
1841                         struct pci_create_interrupt3 v3;
1842                 } int_pkts;
1843         } __packed ctxt;
1844         bool multi_msi;
1845         u64 trans_id;
1846         u32 size;
1847         int ret;
1848         int cpu;
1849
1850         msi_desc  = irq_data_get_msi_desc(data);
1851         multi_msi = !msi_desc->pci.msi_attrib.is_msix &&
1852                     msi_desc->nvec_used > 1;
1853
1854         /* Reuse the previous allocation */
1855         if (data->chip_data && multi_msi) {
1856                 int_desc = data->chip_data;
1857                 msg->address_hi = int_desc->address >> 32;
1858                 msg->address_lo = int_desc->address & 0xffffffff;
1859                 msg->data = int_desc->data;
1860                 return;
1861         }
1862
1863         pdev = msi_desc_to_pci_dev(msi_desc);
1864         dest = irq_data_get_effective_affinity_mask(data);
1865         pbus = pdev->bus;
1866         hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
1867         channel = hbus->hdev->channel;
1868         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1869         if (!hpdev)
1870                 goto return_null_message;
1871
1872         /* Free any previous message that might have already been composed. */
1873         if (data->chip_data && !multi_msi) {
1874                 int_desc = data->chip_data;
1875                 data->chip_data = NULL;
1876                 hv_int_desc_free(hpdev, int_desc);
1877         }
1878
1879         int_desc = kzalloc(sizeof(*int_desc), GFP_ATOMIC);
1880         if (!int_desc)
1881                 goto drop_reference;
1882
1883         if (multi_msi) {
1884                 /*
1885                  * If this is not the first MSI of Multi MSI, we already have
1886                  * a mapping.  Can exit early.
1887                  */
1888                 if (msi_desc->irq != data->irq) {
1889                         data->chip_data = int_desc;
1890                         int_desc->address = msi_desc->msg.address_lo |
1891                                             (u64)msi_desc->msg.address_hi << 32;
1892                         int_desc->data = msi_desc->msg.data +
1893                                          (data->irq - msi_desc->irq);
1894                         msg->address_hi = msi_desc->msg.address_hi;
1895                         msg->address_lo = msi_desc->msg.address_lo;
1896                         msg->data = int_desc->data;
1897                         put_pcichild(hpdev);
1898                         return;
1899                 }
1900                 /*
1901                  * The vector we select here is a dummy value.  The correct
1902                  * value gets sent to the hypervisor in unmask().  This needs
1903                  * to be aligned with the count, and also not zero.  Multi-msi
1904                  * is powers of 2 up to 32, so 32 will always work here.
1905                  */
1906                 vector = 32;
1907                 vector_count = msi_desc->nvec_used;
1908                 cpu = hv_compose_multi_msi_req_get_cpu();
1909         } else {
1910                 vector = hv_msi_get_int_vector(data);
1911                 vector_count = 1;
1912                 cpu = hv_compose_msi_req_get_cpu(dest);
1913         }
1914
1915         /*
1916          * hv_compose_msi_req_v1 and v2 are for x86 only, meaning 'vector'
1917          * can't exceed u8. Cast 'vector' down to u8 for v1/v2 explicitly
1918          * for better readability.
1919          */
1920         memset(&ctxt, 0, sizeof(ctxt));
1921         init_completion(&comp.comp_pkt.host_event);
1922         ctxt.pci_pkt.completion_func = hv_pci_compose_compl;
1923         ctxt.pci_pkt.compl_ctxt = &comp;
1924
1925         switch (hbus->protocol_version) {
1926         case PCI_PROTOCOL_VERSION_1_1:
1927                 size = hv_compose_msi_req_v1(&ctxt.int_pkts.v1,
1928                                         hpdev->desc.win_slot.slot,
1929                                         (u8)vector,
1930                                         vector_count);
1931                 break;
1932
1933         case PCI_PROTOCOL_VERSION_1_2:
1934         case PCI_PROTOCOL_VERSION_1_3:
1935                 size = hv_compose_msi_req_v2(&ctxt.int_pkts.v2,
1936                                         cpu,
1937                                         hpdev->desc.win_slot.slot,
1938                                         (u8)vector,
1939                                         vector_count);
1940                 break;
1941
1942         case PCI_PROTOCOL_VERSION_1_4:
1943                 size = hv_compose_msi_req_v3(&ctxt.int_pkts.v3,
1944                                         cpu,
1945                                         hpdev->desc.win_slot.slot,
1946                                         vector,
1947                                         vector_count);
1948                 break;
1949
1950         default:
1951                 /* As we only negotiate protocol versions known to this driver,
1952                  * this path should never hit. However, this is it not a hot
1953                  * path so we print a message to aid future updates.
1954                  */
1955                 dev_err(&hbus->hdev->device,
1956                         "Unexpected vPCI protocol, update driver.");
1957                 goto free_int_desc;
1958         }
1959
1960         ret = vmbus_sendpacket_getid(hpdev->hbus->hdev->channel, &ctxt.int_pkts,
1961                                      size, (unsigned long)&ctxt.pci_pkt,
1962                                      &trans_id, VM_PKT_DATA_INBAND,
1963                                      VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1964         if (ret) {
1965                 dev_err(&hbus->hdev->device,
1966                         "Sending request for interrupt failed: 0x%x",
1967                         comp.comp_pkt.completion_status);
1968                 goto free_int_desc;
1969         }
1970
1971         /*
1972          * Prevents hv_pci_onchannelcallback() from running concurrently
1973          * in the tasklet.
1974          */
1975         tasklet_disable_in_atomic(&channel->callback_event);
1976
1977         /*
1978          * Since this function is called with IRQ locks held, can't
1979          * do normal wait for completion; instead poll.
1980          */
1981         while (!try_wait_for_completion(&comp.comp_pkt.host_event)) {
1982                 unsigned long flags;
1983
1984                 /* 0xFFFF means an invalid PCI VENDOR ID. */
1985                 if (hv_pcifront_get_vendor_id(hpdev) == 0xFFFF) {
1986                         dev_err_once(&hbus->hdev->device,
1987                                      "the device has gone\n");
1988                         goto enable_tasklet;
1989                 }
1990
1991                 /*
1992                  * Make sure that the ring buffer data structure doesn't get
1993                  * freed while we dereference the ring buffer pointer.  Test
1994                  * for the channel's onchannel_callback being NULL within a
1995                  * sched_lock critical section.  See also the inline comments
1996                  * in vmbus_reset_channel_cb().
1997                  */
1998                 spin_lock_irqsave(&channel->sched_lock, flags);
1999                 if (unlikely(channel->onchannel_callback == NULL)) {
2000                         spin_unlock_irqrestore(&channel->sched_lock, flags);
2001                         goto enable_tasklet;
2002                 }
2003                 hv_pci_onchannelcallback(hbus);
2004                 spin_unlock_irqrestore(&channel->sched_lock, flags);
2005
2006                 udelay(100);
2007         }
2008
2009         tasklet_enable(&channel->callback_event);
2010
2011         if (comp.comp_pkt.completion_status < 0) {
2012                 dev_err(&hbus->hdev->device,
2013                         "Request for interrupt failed: 0x%x",
2014                         comp.comp_pkt.completion_status);
2015                 goto free_int_desc;
2016         }
2017
2018         /*
2019          * Record the assignment so that this can be unwound later. Using
2020          * irq_set_chip_data() here would be appropriate, but the lock it takes
2021          * is already held.
2022          */
2023         *int_desc = comp.int_desc;
2024         data->chip_data = int_desc;
2025
2026         /* Pass up the result. */
2027         msg->address_hi = comp.int_desc.address >> 32;
2028         msg->address_lo = comp.int_desc.address & 0xffffffff;
2029         msg->data = comp.int_desc.data;
2030
2031         put_pcichild(hpdev);
2032         return;
2033
2034 enable_tasklet:
2035         tasklet_enable(&channel->callback_event);
2036         /*
2037          * The completion packet on the stack becomes invalid after 'return';
2038          * remove the ID from the VMbus requestor if the identifier is still
2039          * mapped to/associated with the packet.  (The identifier could have
2040          * been 're-used', i.e., already removed and (re-)mapped.)
2041          *
2042          * Cf. hv_pci_onchannelcallback().
2043          */
2044         vmbus_request_addr_match(channel, trans_id, (unsigned long)&ctxt.pci_pkt);
2045 free_int_desc:
2046         kfree(int_desc);
2047 drop_reference:
2048         put_pcichild(hpdev);
2049 return_null_message:
2050         msg->address_hi = 0;
2051         msg->address_lo = 0;
2052         msg->data = 0;
2053 }
2054
2055 /* HW Interrupt Chip Descriptor */
2056 static struct irq_chip hv_msi_irq_chip = {
2057         .name                   = "Hyper-V PCIe MSI",
2058         .irq_compose_msi_msg    = hv_compose_msi_msg,
2059         .irq_set_affinity       = irq_chip_set_affinity_parent,
2060 #ifdef CONFIG_X86
2061         .irq_ack                = irq_chip_ack_parent,
2062 #elif defined(CONFIG_ARM64)
2063         .irq_eoi                = irq_chip_eoi_parent,
2064 #endif
2065         .irq_mask               = hv_irq_mask,
2066         .irq_unmask             = hv_irq_unmask,
2067 };
2068
2069 static struct msi_domain_ops hv_msi_ops = {
2070         .msi_prepare    = hv_msi_prepare,
2071         .msi_free       = hv_msi_free,
2072 };
2073
2074 /**
2075  * hv_pcie_init_irq_domain() - Initialize IRQ domain
2076  * @hbus:       The root PCI bus
2077  *
2078  * This function creates an IRQ domain which will be used for
2079  * interrupts from devices that have been passed through.  These
2080  * devices only support MSI and MSI-X, not line-based interrupts
2081  * or simulations of line-based interrupts through PCIe's
2082  * fabric-layer messages.  Because interrupts are remapped, we
2083  * can support multi-message MSI here.
2084  *
2085  * Return: '0' on success and error value on failure
2086  */
2087 static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus)
2088 {
2089         hbus->msi_info.chip = &hv_msi_irq_chip;
2090         hbus->msi_info.ops = &hv_msi_ops;
2091         hbus->msi_info.flags = (MSI_FLAG_USE_DEF_DOM_OPS |
2092                 MSI_FLAG_USE_DEF_CHIP_OPS | MSI_FLAG_MULTI_PCI_MSI |
2093                 MSI_FLAG_PCI_MSIX);
2094         hbus->msi_info.handler = FLOW_HANDLER;
2095         hbus->msi_info.handler_name = FLOW_NAME;
2096         hbus->msi_info.data = hbus;
2097         hbus->irq_domain = pci_msi_create_irq_domain(hbus->fwnode,
2098                                                      &hbus->msi_info,
2099                                                      hv_pci_get_root_domain());
2100         if (!hbus->irq_domain) {
2101                 dev_err(&hbus->hdev->device,
2102                         "Failed to build an MSI IRQ domain\n");
2103                 return -ENODEV;
2104         }
2105
2106         dev_set_msi_domain(&hbus->bridge->dev, hbus->irq_domain);
2107
2108         return 0;
2109 }
2110
2111 /**
2112  * get_bar_size() - Get the address space consumed by a BAR
2113  * @bar_val:    Value that a BAR returned after -1 was written
2114  *              to it.
2115  *
2116  * This function returns the size of the BAR, rounded up to 1
2117  * page.  It has to be rounded up because the hypervisor's page
2118  * table entry that maps the BAR into the VM can't specify an
2119  * offset within a page.  The invariant is that the hypervisor
2120  * must place any BARs of smaller than page length at the
2121  * beginning of a page.
2122  *
2123  * Return:      Size in bytes of the consumed MMIO space.
2124  */
2125 static u64 get_bar_size(u64 bar_val)
2126 {
2127         return round_up((1 + ~(bar_val & PCI_BASE_ADDRESS_MEM_MASK)),
2128                         PAGE_SIZE);
2129 }
2130
2131 /**
2132  * survey_child_resources() - Total all MMIO requirements
2133  * @hbus:       Root PCI bus, as understood by this driver
2134  */
2135 static void survey_child_resources(struct hv_pcibus_device *hbus)
2136 {
2137         struct hv_pci_dev *hpdev;
2138         resource_size_t bar_size = 0;
2139         unsigned long flags;
2140         struct completion *event;
2141         u64 bar_val;
2142         int i;
2143
2144         /* If nobody is waiting on the answer, don't compute it. */
2145         event = xchg(&hbus->survey_event, NULL);
2146         if (!event)
2147                 return;
2148
2149         /* If the answer has already been computed, go with it. */
2150         if (hbus->low_mmio_space || hbus->high_mmio_space) {
2151                 complete(event);
2152                 return;
2153         }
2154
2155         spin_lock_irqsave(&hbus->device_list_lock, flags);
2156
2157         /*
2158          * Due to an interesting quirk of the PCI spec, all memory regions
2159          * for a child device are a power of 2 in size and aligned in memory,
2160          * so it's sufficient to just add them up without tracking alignment.
2161          */
2162         list_for_each_entry(hpdev, &hbus->children, list_entry) {
2163                 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
2164                         if (hpdev->probed_bar[i] & PCI_BASE_ADDRESS_SPACE_IO)
2165                                 dev_err(&hbus->hdev->device,
2166                                         "There's an I/O BAR in this list!\n");
2167
2168                         if (hpdev->probed_bar[i] != 0) {
2169                                 /*
2170                                  * A probed BAR has all the upper bits set that
2171                                  * can be changed.
2172                                  */
2173
2174                                 bar_val = hpdev->probed_bar[i];
2175                                 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
2176                                         bar_val |=
2177                                         ((u64)hpdev->probed_bar[++i] << 32);
2178                                 else
2179                                         bar_val |= 0xffffffff00000000ULL;
2180
2181                                 bar_size = get_bar_size(bar_val);
2182
2183                                 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
2184                                         hbus->high_mmio_space += bar_size;
2185                                 else
2186                                         hbus->low_mmio_space += bar_size;
2187                         }
2188                 }
2189         }
2190
2191         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2192         complete(event);
2193 }
2194
2195 /**
2196  * prepopulate_bars() - Fill in BARs with defaults
2197  * @hbus:       Root PCI bus, as understood by this driver
2198  *
2199  * The core PCI driver code seems much, much happier if the BARs
2200  * for a device have values upon first scan. So fill them in.
2201  * The algorithm below works down from large sizes to small,
2202  * attempting to pack the assignments optimally. The assumption,
2203  * enforced in other parts of the code, is that the beginning of
2204  * the memory-mapped I/O space will be aligned on the largest
2205  * BAR size.
2206  */
2207 static void prepopulate_bars(struct hv_pcibus_device *hbus)
2208 {
2209         resource_size_t high_size = 0;
2210         resource_size_t low_size = 0;
2211         resource_size_t high_base = 0;
2212         resource_size_t low_base = 0;
2213         resource_size_t bar_size;
2214         struct hv_pci_dev *hpdev;
2215         unsigned long flags;
2216         u64 bar_val;
2217         u32 command;
2218         bool high;
2219         int i;
2220
2221         if (hbus->low_mmio_space) {
2222                 low_size = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
2223                 low_base = hbus->low_mmio_res->start;
2224         }
2225
2226         if (hbus->high_mmio_space) {
2227                 high_size = 1ULL <<
2228                         (63 - __builtin_clzll(hbus->high_mmio_space));
2229                 high_base = hbus->high_mmio_res->start;
2230         }
2231
2232         spin_lock_irqsave(&hbus->device_list_lock, flags);
2233
2234         /*
2235          * Clear the memory enable bit, in case it's already set. This occurs
2236          * in the suspend path of hibernation, where the device is suspended,
2237          * resumed and suspended again: see hibernation_snapshot() and
2238          * hibernation_platform_enter().
2239          *
2240          * If the memory enable bit is already set, Hyper-V silently ignores
2241          * the below BAR updates, and the related PCI device driver can not
2242          * work, because reading from the device register(s) always returns
2243          * 0xFFFFFFFF (PCI_ERROR_RESPONSE).
2244          */
2245         list_for_each_entry(hpdev, &hbus->children, list_entry) {
2246                 _hv_pcifront_read_config(hpdev, PCI_COMMAND, 2, &command);
2247                 command &= ~PCI_COMMAND_MEMORY;
2248                 _hv_pcifront_write_config(hpdev, PCI_COMMAND, 2, command);
2249         }
2250
2251         /* Pick addresses for the BARs. */
2252         do {
2253                 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2254                         for (i = 0; i < PCI_STD_NUM_BARS; i++) {
2255                                 bar_val = hpdev->probed_bar[i];
2256                                 if (bar_val == 0)
2257                                         continue;
2258                                 high = bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64;
2259                                 if (high) {
2260                                         bar_val |=
2261                                                 ((u64)hpdev->probed_bar[i + 1]
2262                                                  << 32);
2263                                 } else {
2264                                         bar_val |= 0xffffffffULL << 32;
2265                                 }
2266                                 bar_size = get_bar_size(bar_val);
2267                                 if (high) {
2268                                         if (high_size != bar_size) {
2269                                                 i++;
2270                                                 continue;
2271                                         }
2272                                         _hv_pcifront_write_config(hpdev,
2273                                                 PCI_BASE_ADDRESS_0 + (4 * i),
2274                                                 4,
2275                                                 (u32)(high_base & 0xffffff00));
2276                                         i++;
2277                                         _hv_pcifront_write_config(hpdev,
2278                                                 PCI_BASE_ADDRESS_0 + (4 * i),
2279                                                 4, (u32)(high_base >> 32));
2280                                         high_base += bar_size;
2281                                 } else {
2282                                         if (low_size != bar_size)
2283                                                 continue;
2284                                         _hv_pcifront_write_config(hpdev,
2285                                                 PCI_BASE_ADDRESS_0 + (4 * i),
2286                                                 4,
2287                                                 (u32)(low_base & 0xffffff00));
2288                                         low_base += bar_size;
2289                                 }
2290                         }
2291                         if (high_size <= 1 && low_size <= 1) {
2292                                 /*
2293                                  * No need to set the PCI_COMMAND_MEMORY bit as
2294                                  * the core PCI driver doesn't require the bit
2295                                  * to be pre-set. Actually here we intentionally
2296                                  * keep the bit off so that the PCI BAR probing
2297                                  * in the core PCI driver doesn't cause Hyper-V
2298                                  * to unnecessarily unmap/map the virtual BARs
2299                                  * from/to the physical BARs multiple times.
2300                                  * This reduces the VM boot time significantly
2301                                  * if the BAR sizes are huge.
2302                                  */
2303                                 break;
2304                         }
2305                 }
2306
2307                 high_size >>= 1;
2308                 low_size >>= 1;
2309         }  while (high_size || low_size);
2310
2311         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2312 }
2313
2314 /*
2315  * Assign entries in sysfs pci slot directory.
2316  *
2317  * Note that this function does not need to lock the children list
2318  * because it is called from pci_devices_present_work which
2319  * is serialized with hv_eject_device_work because they are on the
2320  * same ordered workqueue. Therefore hbus->children list will not change
2321  * even when pci_create_slot sleeps.
2322  */
2323 static void hv_pci_assign_slots(struct hv_pcibus_device *hbus)
2324 {
2325         struct hv_pci_dev *hpdev;
2326         char name[SLOT_NAME_SIZE];
2327         int slot_nr;
2328
2329         list_for_each_entry(hpdev, &hbus->children, list_entry) {
2330                 if (hpdev->pci_slot)
2331                         continue;
2332
2333                 slot_nr = PCI_SLOT(wslot_to_devfn(hpdev->desc.win_slot.slot));
2334                 snprintf(name, SLOT_NAME_SIZE, "%u", hpdev->desc.ser);
2335                 hpdev->pci_slot = pci_create_slot(hbus->bridge->bus, slot_nr,
2336                                           name, NULL);
2337                 if (IS_ERR(hpdev->pci_slot)) {
2338                         pr_warn("pci_create slot %s failed\n", name);
2339                         hpdev->pci_slot = NULL;
2340                 }
2341         }
2342 }
2343
2344 /*
2345  * Remove entries in sysfs pci slot directory.
2346  */
2347 static void hv_pci_remove_slots(struct hv_pcibus_device *hbus)
2348 {
2349         struct hv_pci_dev *hpdev;
2350
2351         list_for_each_entry(hpdev, &hbus->children, list_entry) {
2352                 if (!hpdev->pci_slot)
2353                         continue;
2354                 pci_destroy_slot(hpdev->pci_slot);
2355                 hpdev->pci_slot = NULL;
2356         }
2357 }
2358
2359 /*
2360  * Set NUMA node for the devices on the bus
2361  */
2362 static void hv_pci_assign_numa_node(struct hv_pcibus_device *hbus)
2363 {
2364         struct pci_dev *dev;
2365         struct pci_bus *bus = hbus->bridge->bus;
2366         struct hv_pci_dev *hv_dev;
2367
2368         list_for_each_entry(dev, &bus->devices, bus_list) {
2369                 hv_dev = get_pcichild_wslot(hbus, devfn_to_wslot(dev->devfn));
2370                 if (!hv_dev)
2371                         continue;
2372
2373                 if (hv_dev->desc.flags & HV_PCI_DEVICE_FLAG_NUMA_AFFINITY &&
2374                     hv_dev->desc.virtual_numa_node < num_possible_nodes())
2375                         /*
2376                          * The kernel may boot with some NUMA nodes offline
2377                          * (e.g. in a KDUMP kernel) or with NUMA disabled via
2378                          * "numa=off". In those cases, adjust the host provided
2379                          * NUMA node to a valid NUMA node used by the kernel.
2380                          */
2381                         set_dev_node(&dev->dev,
2382                                      numa_map_to_online_node(
2383                                              hv_dev->desc.virtual_numa_node));
2384
2385                 put_pcichild(hv_dev);
2386         }
2387 }
2388
2389 /**
2390  * create_root_hv_pci_bus() - Expose a new root PCI bus
2391  * @hbus:       Root PCI bus, as understood by this driver
2392  *
2393  * Return: 0 on success, -errno on failure
2394  */
2395 static int create_root_hv_pci_bus(struct hv_pcibus_device *hbus)
2396 {
2397         int error;
2398         struct pci_host_bridge *bridge = hbus->bridge;
2399
2400         bridge->dev.parent = &hbus->hdev->device;
2401         bridge->sysdata = &hbus->sysdata;
2402         bridge->ops = &hv_pcifront_ops;
2403
2404         error = pci_scan_root_bus_bridge(bridge);
2405         if (error)
2406                 return error;
2407
2408         pci_lock_rescan_remove();
2409         hv_pci_assign_numa_node(hbus);
2410         pci_bus_assign_resources(bridge->bus);
2411         hv_pci_assign_slots(hbus);
2412         pci_bus_add_devices(bridge->bus);
2413         pci_unlock_rescan_remove();
2414         hbus->state = hv_pcibus_installed;
2415         return 0;
2416 }
2417
2418 struct q_res_req_compl {
2419         struct completion host_event;
2420         struct hv_pci_dev *hpdev;
2421 };
2422
2423 /**
2424  * q_resource_requirements() - Query Resource Requirements
2425  * @context:            The completion context.
2426  * @resp:               The response that came from the host.
2427  * @resp_packet_size:   The size in bytes of resp.
2428  *
2429  * This function is invoked on completion of a Query Resource
2430  * Requirements packet.
2431  */
2432 static void q_resource_requirements(void *context, struct pci_response *resp,
2433                                     int resp_packet_size)
2434 {
2435         struct q_res_req_compl *completion = context;
2436         struct pci_q_res_req_response *q_res_req =
2437                 (struct pci_q_res_req_response *)resp;
2438         s32 status;
2439         int i;
2440
2441         status = (resp_packet_size < sizeof(*q_res_req)) ? -1 : resp->status;
2442         if (status < 0) {
2443                 dev_err(&completion->hpdev->hbus->hdev->device,
2444                         "query resource requirements failed: %x\n",
2445                         status);
2446         } else {
2447                 for (i = 0; i < PCI_STD_NUM_BARS; i++) {
2448                         completion->hpdev->probed_bar[i] =
2449                                 q_res_req->probed_bar[i];
2450                 }
2451         }
2452
2453         complete(&completion->host_event);
2454 }
2455
2456 /**
2457  * new_pcichild_device() - Create a new child device
2458  * @hbus:       The internal struct tracking this root PCI bus.
2459  * @desc:       The information supplied so far from the host
2460  *              about the device.
2461  *
2462  * This function creates the tracking structure for a new child
2463  * device and kicks off the process of figuring out what it is.
2464  *
2465  * Return: Pointer to the new tracking struct
2466  */
2467 static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
2468                 struct hv_pcidev_description *desc)
2469 {
2470         struct hv_pci_dev *hpdev;
2471         struct pci_child_message *res_req;
2472         struct q_res_req_compl comp_pkt;
2473         struct {
2474                 struct pci_packet init_packet;
2475                 u8 buffer[sizeof(struct pci_child_message)];
2476         } pkt;
2477         unsigned long flags;
2478         int ret;
2479
2480         hpdev = kzalloc(sizeof(*hpdev), GFP_KERNEL);
2481         if (!hpdev)
2482                 return NULL;
2483
2484         hpdev->hbus = hbus;
2485
2486         memset(&pkt, 0, sizeof(pkt));
2487         init_completion(&comp_pkt.host_event);
2488         comp_pkt.hpdev = hpdev;
2489         pkt.init_packet.compl_ctxt = &comp_pkt;
2490         pkt.init_packet.completion_func = q_resource_requirements;
2491         res_req = (struct pci_child_message *)&pkt.init_packet.message;
2492         res_req->message_type.type = PCI_QUERY_RESOURCE_REQUIREMENTS;
2493         res_req->wslot.slot = desc->win_slot.slot;
2494
2495         ret = vmbus_sendpacket(hbus->hdev->channel, res_req,
2496                                sizeof(struct pci_child_message),
2497                                (unsigned long)&pkt.init_packet,
2498                                VM_PKT_DATA_INBAND,
2499                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2500         if (ret)
2501                 goto error;
2502
2503         if (wait_for_response(hbus->hdev, &comp_pkt.host_event))
2504                 goto error;
2505
2506         hpdev->desc = *desc;
2507         refcount_set(&hpdev->refs, 1);
2508         get_pcichild(hpdev);
2509         spin_lock_irqsave(&hbus->device_list_lock, flags);
2510
2511         list_add_tail(&hpdev->list_entry, &hbus->children);
2512         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2513         return hpdev;
2514
2515 error:
2516         kfree(hpdev);
2517         return NULL;
2518 }
2519
2520 /**
2521  * get_pcichild_wslot() - Find device from slot
2522  * @hbus:       Root PCI bus, as understood by this driver
2523  * @wslot:      Location on the bus
2524  *
2525  * This function looks up a PCI device and returns the internal
2526  * representation of it.  It acquires a reference on it, so that
2527  * the device won't be deleted while somebody is using it.  The
2528  * caller is responsible for calling put_pcichild() to release
2529  * this reference.
2530  *
2531  * Return:      Internal representation of a PCI device
2532  */
2533 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
2534                                              u32 wslot)
2535 {
2536         unsigned long flags;
2537         struct hv_pci_dev *iter, *hpdev = NULL;
2538
2539         spin_lock_irqsave(&hbus->device_list_lock, flags);
2540         list_for_each_entry(iter, &hbus->children, list_entry) {
2541                 if (iter->desc.win_slot.slot == wslot) {
2542                         hpdev = iter;
2543                         get_pcichild(hpdev);
2544                         break;
2545                 }
2546         }
2547         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2548
2549         return hpdev;
2550 }
2551
2552 /**
2553  * pci_devices_present_work() - Handle new list of child devices
2554  * @work:       Work struct embedded in struct hv_dr_work
2555  *
2556  * "Bus Relations" is the Windows term for "children of this
2557  * bus."  The terminology is preserved here for people trying to
2558  * debug the interaction between Hyper-V and Linux.  This
2559  * function is called when the parent partition reports a list
2560  * of functions that should be observed under this PCI Express
2561  * port (bus).
2562  *
2563  * This function updates the list, and must tolerate being
2564  * called multiple times with the same information.  The typical
2565  * number of child devices is one, with very atypical cases
2566  * involving three or four, so the algorithms used here can be
2567  * simple and inefficient.
2568  *
2569  * It must also treat the omission of a previously observed device as
2570  * notification that the device no longer exists.
2571  *
2572  * Note that this function is serialized with hv_eject_device_work(),
2573  * because both are pushed to the ordered workqueue hbus->wq.
2574  */
2575 static void pci_devices_present_work(struct work_struct *work)
2576 {
2577         u32 child_no;
2578         bool found;
2579         struct hv_pcidev_description *new_desc;
2580         struct hv_pci_dev *hpdev;
2581         struct hv_pcibus_device *hbus;
2582         struct list_head removed;
2583         struct hv_dr_work *dr_wrk;
2584         struct hv_dr_state *dr = NULL;
2585         unsigned long flags;
2586
2587         dr_wrk = container_of(work, struct hv_dr_work, wrk);
2588         hbus = dr_wrk->bus;
2589         kfree(dr_wrk);
2590
2591         INIT_LIST_HEAD(&removed);
2592
2593         /* Pull this off the queue and process it if it was the last one. */
2594         spin_lock_irqsave(&hbus->device_list_lock, flags);
2595         while (!list_empty(&hbus->dr_list)) {
2596                 dr = list_first_entry(&hbus->dr_list, struct hv_dr_state,
2597                                       list_entry);
2598                 list_del(&dr->list_entry);
2599
2600                 /* Throw this away if the list still has stuff in it. */
2601                 if (!list_empty(&hbus->dr_list)) {
2602                         kfree(dr);
2603                         continue;
2604                 }
2605         }
2606         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2607
2608         if (!dr)
2609                 return;
2610
2611         mutex_lock(&hbus->state_lock);
2612
2613         /* First, mark all existing children as reported missing. */
2614         spin_lock_irqsave(&hbus->device_list_lock, flags);
2615         list_for_each_entry(hpdev, &hbus->children, list_entry) {
2616                 hpdev->reported_missing = true;
2617         }
2618         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2619
2620         /* Next, add back any reported devices. */
2621         for (child_no = 0; child_no < dr->device_count; child_no++) {
2622                 found = false;
2623                 new_desc = &dr->func[child_no];
2624
2625                 spin_lock_irqsave(&hbus->device_list_lock, flags);
2626                 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2627                         if ((hpdev->desc.win_slot.slot == new_desc->win_slot.slot) &&
2628                             (hpdev->desc.v_id == new_desc->v_id) &&
2629                             (hpdev->desc.d_id == new_desc->d_id) &&
2630                             (hpdev->desc.ser == new_desc->ser)) {
2631                                 hpdev->reported_missing = false;
2632                                 found = true;
2633                         }
2634                 }
2635                 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2636
2637                 if (!found) {
2638                         hpdev = new_pcichild_device(hbus, new_desc);
2639                         if (!hpdev)
2640                                 dev_err(&hbus->hdev->device,
2641                                         "couldn't record a child device.\n");
2642                 }
2643         }
2644
2645         /* Move missing children to a list on the stack. */
2646         spin_lock_irqsave(&hbus->device_list_lock, flags);
2647         do {
2648                 found = false;
2649                 list_for_each_entry(hpdev, &hbus->children, list_entry) {
2650                         if (hpdev->reported_missing) {
2651                                 found = true;
2652                                 put_pcichild(hpdev);
2653                                 list_move_tail(&hpdev->list_entry, &removed);
2654                                 break;
2655                         }
2656                 }
2657         } while (found);
2658         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2659
2660         /* Delete everything that should no longer exist. */
2661         while (!list_empty(&removed)) {
2662                 hpdev = list_first_entry(&removed, struct hv_pci_dev,
2663                                          list_entry);
2664                 list_del(&hpdev->list_entry);
2665
2666                 if (hpdev->pci_slot)
2667                         pci_destroy_slot(hpdev->pci_slot);
2668
2669                 put_pcichild(hpdev);
2670         }
2671
2672         switch (hbus->state) {
2673         case hv_pcibus_installed:
2674                 /*
2675                  * Tell the core to rescan bus
2676                  * because there may have been changes.
2677                  */
2678                 pci_lock_rescan_remove();
2679                 pci_scan_child_bus(hbus->bridge->bus);
2680                 hv_pci_assign_numa_node(hbus);
2681                 hv_pci_assign_slots(hbus);
2682                 pci_unlock_rescan_remove();
2683                 break;
2684
2685         case hv_pcibus_init:
2686         case hv_pcibus_probed:
2687                 survey_child_resources(hbus);
2688                 break;
2689
2690         default:
2691                 break;
2692         }
2693
2694         mutex_unlock(&hbus->state_lock);
2695
2696         kfree(dr);
2697 }
2698
2699 /**
2700  * hv_pci_start_relations_work() - Queue work to start device discovery
2701  * @hbus:       Root PCI bus, as understood by this driver
2702  * @dr:         The list of children returned from host
2703  *
2704  * Return:  0 on success, -errno on failure
2705  */
2706 static int hv_pci_start_relations_work(struct hv_pcibus_device *hbus,
2707                                        struct hv_dr_state *dr)
2708 {
2709         struct hv_dr_work *dr_wrk;
2710         unsigned long flags;
2711         bool pending_dr;
2712
2713         if (hbus->state == hv_pcibus_removing) {
2714                 dev_info(&hbus->hdev->device,
2715                          "PCI VMBus BUS_RELATIONS: ignored\n");
2716                 return -ENOENT;
2717         }
2718
2719         dr_wrk = kzalloc(sizeof(*dr_wrk), GFP_NOWAIT);
2720         if (!dr_wrk)
2721                 return -ENOMEM;
2722
2723         INIT_WORK(&dr_wrk->wrk, pci_devices_present_work);
2724         dr_wrk->bus = hbus;
2725
2726         spin_lock_irqsave(&hbus->device_list_lock, flags);
2727         /*
2728          * If pending_dr is true, we have already queued a work,
2729          * which will see the new dr. Otherwise, we need to
2730          * queue a new work.
2731          */
2732         pending_dr = !list_empty(&hbus->dr_list);
2733         list_add_tail(&dr->list_entry, &hbus->dr_list);
2734         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2735
2736         if (pending_dr)
2737                 kfree(dr_wrk);
2738         else
2739                 queue_work(hbus->wq, &dr_wrk->wrk);
2740
2741         return 0;
2742 }
2743
2744 /**
2745  * hv_pci_devices_present() - Handle list of new children
2746  * @hbus:      Root PCI bus, as understood by this driver
2747  * @relations: Packet from host listing children
2748  *
2749  * Process a new list of devices on the bus. The list of devices is
2750  * discovered by VSP and sent to us via VSP message PCI_BUS_RELATIONS,
2751  * whenever a new list of devices for this bus appears.
2752  */
2753 static void hv_pci_devices_present(struct hv_pcibus_device *hbus,
2754                                    struct pci_bus_relations *relations)
2755 {
2756         struct hv_dr_state *dr;
2757         int i;
2758
2759         dr = kzalloc(struct_size(dr, func, relations->device_count),
2760                      GFP_NOWAIT);
2761         if (!dr)
2762                 return;
2763
2764         dr->device_count = relations->device_count;
2765         for (i = 0; i < dr->device_count; i++) {
2766                 dr->func[i].v_id = relations->func[i].v_id;
2767                 dr->func[i].d_id = relations->func[i].d_id;
2768                 dr->func[i].rev = relations->func[i].rev;
2769                 dr->func[i].prog_intf = relations->func[i].prog_intf;
2770                 dr->func[i].subclass = relations->func[i].subclass;
2771                 dr->func[i].base_class = relations->func[i].base_class;
2772                 dr->func[i].subsystem_id = relations->func[i].subsystem_id;
2773                 dr->func[i].win_slot = relations->func[i].win_slot;
2774                 dr->func[i].ser = relations->func[i].ser;
2775         }
2776
2777         if (hv_pci_start_relations_work(hbus, dr))
2778                 kfree(dr);
2779 }
2780
2781 /**
2782  * hv_pci_devices_present2() - Handle list of new children
2783  * @hbus:       Root PCI bus, as understood by this driver
2784  * @relations:  Packet from host listing children
2785  *
2786  * This function is the v2 version of hv_pci_devices_present()
2787  */
2788 static void hv_pci_devices_present2(struct hv_pcibus_device *hbus,
2789                                     struct pci_bus_relations2 *relations)
2790 {
2791         struct hv_dr_state *dr;
2792         int i;
2793
2794         dr = kzalloc(struct_size(dr, func, relations->device_count),
2795                      GFP_NOWAIT);
2796         if (!dr)
2797                 return;
2798
2799         dr->device_count = relations->device_count;
2800         for (i = 0; i < dr->device_count; i++) {
2801                 dr->func[i].v_id = relations->func[i].v_id;
2802                 dr->func[i].d_id = relations->func[i].d_id;
2803                 dr->func[i].rev = relations->func[i].rev;
2804                 dr->func[i].prog_intf = relations->func[i].prog_intf;
2805                 dr->func[i].subclass = relations->func[i].subclass;
2806                 dr->func[i].base_class = relations->func[i].base_class;
2807                 dr->func[i].subsystem_id = relations->func[i].subsystem_id;
2808                 dr->func[i].win_slot = relations->func[i].win_slot;
2809                 dr->func[i].ser = relations->func[i].ser;
2810                 dr->func[i].flags = relations->func[i].flags;
2811                 dr->func[i].virtual_numa_node =
2812                         relations->func[i].virtual_numa_node;
2813         }
2814
2815         if (hv_pci_start_relations_work(hbus, dr))
2816                 kfree(dr);
2817 }
2818
2819 /**
2820  * hv_eject_device_work() - Asynchronously handles ejection
2821  * @work:       Work struct embedded in internal device struct
2822  *
2823  * This function handles ejecting a device.  Windows will
2824  * attempt to gracefully eject a device, waiting 60 seconds to
2825  * hear back from the guest OS that this completed successfully.
2826  * If this timer expires, the device will be forcibly removed.
2827  */
2828 static void hv_eject_device_work(struct work_struct *work)
2829 {
2830         struct pci_eject_response *ejct_pkt;
2831         struct hv_pcibus_device *hbus;
2832         struct hv_pci_dev *hpdev;
2833         struct pci_dev *pdev;
2834         unsigned long flags;
2835         int wslot;
2836         struct {
2837                 struct pci_packet pkt;
2838                 u8 buffer[sizeof(struct pci_eject_response)];
2839         } ctxt;
2840
2841         hpdev = container_of(work, struct hv_pci_dev, wrk);
2842         hbus = hpdev->hbus;
2843
2844         mutex_lock(&hbus->state_lock);
2845
2846         /*
2847          * Ejection can come before or after the PCI bus has been set up, so
2848          * attempt to find it and tear down the bus state, if it exists.  This
2849          * must be done without constructs like pci_domain_nr(hbus->bridge->bus)
2850          * because hbus->bridge->bus may not exist yet.
2851          */
2852         wslot = wslot_to_devfn(hpdev->desc.win_slot.slot);
2853         pdev = pci_get_domain_bus_and_slot(hbus->bridge->domain_nr, 0, wslot);
2854         if (pdev) {
2855                 pci_lock_rescan_remove();
2856                 pci_stop_and_remove_bus_device(pdev);
2857                 pci_dev_put(pdev);
2858                 pci_unlock_rescan_remove();
2859         }
2860
2861         spin_lock_irqsave(&hbus->device_list_lock, flags);
2862         list_del(&hpdev->list_entry);
2863         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
2864
2865         if (hpdev->pci_slot)
2866                 pci_destroy_slot(hpdev->pci_slot);
2867
2868         memset(&ctxt, 0, sizeof(ctxt));
2869         ejct_pkt = (struct pci_eject_response *)&ctxt.pkt.message;
2870         ejct_pkt->message_type.type = PCI_EJECTION_COMPLETE;
2871         ejct_pkt->wslot.slot = hpdev->desc.win_slot.slot;
2872         vmbus_sendpacket(hbus->hdev->channel, ejct_pkt,
2873                          sizeof(*ejct_pkt), 0,
2874                          VM_PKT_DATA_INBAND, 0);
2875
2876         /* For the get_pcichild() in hv_pci_eject_device() */
2877         put_pcichild(hpdev);
2878         /* For the two refs got in new_pcichild_device() */
2879         put_pcichild(hpdev);
2880         put_pcichild(hpdev);
2881         /* hpdev has been freed. Do not use it any more. */
2882
2883         mutex_unlock(&hbus->state_lock);
2884 }
2885
2886 /**
2887  * hv_pci_eject_device() - Handles device ejection
2888  * @hpdev:      Internal device tracking struct
2889  *
2890  * This function is invoked when an ejection packet arrives.  It
2891  * just schedules work so that we don't re-enter the packet
2892  * delivery code handling the ejection.
2893  */
2894 static void hv_pci_eject_device(struct hv_pci_dev *hpdev)
2895 {
2896         struct hv_pcibus_device *hbus = hpdev->hbus;
2897         struct hv_device *hdev = hbus->hdev;
2898
2899         if (hbus->state == hv_pcibus_removing) {
2900                 dev_info(&hdev->device, "PCI VMBus EJECT: ignored\n");
2901                 return;
2902         }
2903
2904         get_pcichild(hpdev);
2905         INIT_WORK(&hpdev->wrk, hv_eject_device_work);
2906         queue_work(hbus->wq, &hpdev->wrk);
2907 }
2908
2909 /**
2910  * hv_pci_onchannelcallback() - Handles incoming packets
2911  * @context:    Internal bus tracking struct
2912  *
2913  * This function is invoked whenever the host sends a packet to
2914  * this channel (which is private to this root PCI bus).
2915  */
2916 static void hv_pci_onchannelcallback(void *context)
2917 {
2918         const int packet_size = 0x100;
2919         int ret;
2920         struct hv_pcibus_device *hbus = context;
2921         struct vmbus_channel *chan = hbus->hdev->channel;
2922         u32 bytes_recvd;
2923         u64 req_id, req_addr;
2924         struct vmpacket_descriptor *desc;
2925         unsigned char *buffer;
2926         int bufferlen = packet_size;
2927         struct pci_packet *comp_packet;
2928         struct pci_response *response;
2929         struct pci_incoming_message *new_message;
2930         struct pci_bus_relations *bus_rel;
2931         struct pci_bus_relations2 *bus_rel2;
2932         struct pci_dev_inval_block *inval;
2933         struct pci_dev_incoming *dev_message;
2934         struct hv_pci_dev *hpdev;
2935         unsigned long flags;
2936
2937         buffer = kmalloc(bufferlen, GFP_ATOMIC);
2938         if (!buffer)
2939                 return;
2940
2941         while (1) {
2942                 ret = vmbus_recvpacket_raw(chan, buffer, bufferlen,
2943                                            &bytes_recvd, &req_id);
2944
2945                 if (ret == -ENOBUFS) {
2946                         kfree(buffer);
2947                         /* Handle large packet */
2948                         bufferlen = bytes_recvd;
2949                         buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
2950                         if (!buffer)
2951                                 return;
2952                         continue;
2953                 }
2954
2955                 /* Zero length indicates there are no more packets. */
2956                 if (ret || !bytes_recvd)
2957                         break;
2958
2959                 /*
2960                  * All incoming packets must be at least as large as a
2961                  * response.
2962                  */
2963                 if (bytes_recvd <= sizeof(struct pci_response))
2964                         continue;
2965                 desc = (struct vmpacket_descriptor *)buffer;
2966
2967                 switch (desc->type) {
2968                 case VM_PKT_COMP:
2969
2970                         lock_requestor(chan, flags);
2971                         req_addr = __vmbus_request_addr_match(chan, req_id,
2972                                                               VMBUS_RQST_ADDR_ANY);
2973                         if (req_addr == VMBUS_RQST_ERROR) {
2974                                 unlock_requestor(chan, flags);
2975                                 dev_err(&hbus->hdev->device,
2976                                         "Invalid transaction ID %llx\n",
2977                                         req_id);
2978                                 break;
2979                         }
2980                         comp_packet = (struct pci_packet *)req_addr;
2981                         response = (struct pci_response *)buffer;
2982                         /*
2983                          * Call ->completion_func() within the critical section to make
2984                          * sure that the packet pointer is still valid during the call:
2985                          * here 'valid' means that there's a task still waiting for the
2986                          * completion, and that the packet data is still on the waiting
2987                          * task's stack.  Cf. hv_compose_msi_msg().
2988                          */
2989                         comp_packet->completion_func(comp_packet->compl_ctxt,
2990                                                      response,
2991                                                      bytes_recvd);
2992                         unlock_requestor(chan, flags);
2993                         break;
2994
2995                 case VM_PKT_DATA_INBAND:
2996
2997                         new_message = (struct pci_incoming_message *)buffer;
2998                         switch (new_message->message_type.type) {
2999                         case PCI_BUS_RELATIONS:
3000
3001                                 bus_rel = (struct pci_bus_relations *)buffer;
3002                                 if (bytes_recvd < sizeof(*bus_rel) ||
3003                                     bytes_recvd <
3004                                         struct_size(bus_rel, func,
3005                                                     bus_rel->device_count)) {
3006                                         dev_err(&hbus->hdev->device,
3007                                                 "bus relations too small\n");
3008                                         break;
3009                                 }
3010
3011                                 hv_pci_devices_present(hbus, bus_rel);
3012                                 break;
3013
3014                         case PCI_BUS_RELATIONS2:
3015
3016                                 bus_rel2 = (struct pci_bus_relations2 *)buffer;
3017                                 if (bytes_recvd < sizeof(*bus_rel2) ||
3018                                     bytes_recvd <
3019                                         struct_size(bus_rel2, func,
3020                                                     bus_rel2->device_count)) {
3021                                         dev_err(&hbus->hdev->device,
3022                                                 "bus relations v2 too small\n");
3023                                         break;
3024                                 }
3025
3026                                 hv_pci_devices_present2(hbus, bus_rel2);
3027                                 break;
3028
3029                         case PCI_EJECT:
3030
3031                                 dev_message = (struct pci_dev_incoming *)buffer;
3032                                 if (bytes_recvd < sizeof(*dev_message)) {
3033                                         dev_err(&hbus->hdev->device,
3034                                                 "eject message too small\n");
3035                                         break;
3036                                 }
3037                                 hpdev = get_pcichild_wslot(hbus,
3038                                                       dev_message->wslot.slot);
3039                                 if (hpdev) {
3040                                         hv_pci_eject_device(hpdev);
3041                                         put_pcichild(hpdev);
3042                                 }
3043                                 break;
3044
3045                         case PCI_INVALIDATE_BLOCK:
3046
3047                                 inval = (struct pci_dev_inval_block *)buffer;
3048                                 if (bytes_recvd < sizeof(*inval)) {
3049                                         dev_err(&hbus->hdev->device,
3050                                                 "invalidate message too small\n");
3051                                         break;
3052                                 }
3053                                 hpdev = get_pcichild_wslot(hbus,
3054                                                            inval->wslot.slot);
3055                                 if (hpdev) {
3056                                         if (hpdev->block_invalidate) {
3057                                                 hpdev->block_invalidate(
3058                                                     hpdev->invalidate_context,
3059                                                     inval->block_mask);
3060                                         }
3061                                         put_pcichild(hpdev);
3062                                 }
3063                                 break;
3064
3065                         default:
3066                                 dev_warn(&hbus->hdev->device,
3067                                         "Unimplemented protocol message %x\n",
3068                                         new_message->message_type.type);
3069                                 break;
3070                         }
3071                         break;
3072
3073                 default:
3074                         dev_err(&hbus->hdev->device,
3075                                 "unhandled packet type %d, tid %llx len %d\n",
3076                                 desc->type, req_id, bytes_recvd);
3077                         break;
3078                 }
3079         }
3080
3081         kfree(buffer);
3082 }
3083
3084 /**
3085  * hv_pci_protocol_negotiation() - Set up protocol
3086  * @hdev:               VMBus's tracking struct for this root PCI bus.
3087  * @version:            Array of supported channel protocol versions in
3088  *                      the order of probing - highest go first.
3089  * @num_version:        Number of elements in the version array.
3090  *
3091  * This driver is intended to support running on Windows 10
3092  * (server) and later versions. It will not run on earlier
3093  * versions, as they assume that many of the operations which
3094  * Linux needs accomplished with a spinlock held were done via
3095  * asynchronous messaging via VMBus.  Windows 10 increases the
3096  * surface area of PCI emulation so that these actions can take
3097  * place by suspending a virtual processor for their duration.
3098  *
3099  * This function negotiates the channel protocol version,
3100  * failing if the host doesn't support the necessary protocol
3101  * level.
3102  */
3103 static int hv_pci_protocol_negotiation(struct hv_device *hdev,
3104                                        enum pci_protocol_version_t version[],
3105                                        int num_version)
3106 {
3107         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3108         struct pci_version_request *version_req;
3109         struct hv_pci_compl comp_pkt;
3110         struct pci_packet *pkt;
3111         int ret;
3112         int i;
3113
3114         /*
3115          * Initiate the handshake with the host and negotiate
3116          * a version that the host can support. We start with the
3117          * highest version number and go down if the host cannot
3118          * support it.
3119          */
3120         pkt = kzalloc(sizeof(*pkt) + sizeof(*version_req), GFP_KERNEL);
3121         if (!pkt)
3122                 return -ENOMEM;
3123
3124         init_completion(&comp_pkt.host_event);
3125         pkt->completion_func = hv_pci_generic_compl;
3126         pkt->compl_ctxt = &comp_pkt;
3127         version_req = (struct pci_version_request *)&pkt->message;
3128         version_req->message_type.type = PCI_QUERY_PROTOCOL_VERSION;
3129
3130         for (i = 0; i < num_version; i++) {
3131                 version_req->protocol_version = version[i];
3132                 ret = vmbus_sendpacket(hdev->channel, version_req,
3133                                 sizeof(struct pci_version_request),
3134                                 (unsigned long)pkt, VM_PKT_DATA_INBAND,
3135                                 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3136                 if (!ret)
3137                         ret = wait_for_response(hdev, &comp_pkt.host_event);
3138
3139                 if (ret) {
3140                         dev_err(&hdev->device,
3141                                 "PCI Pass-through VSP failed to request version: %d",
3142                                 ret);
3143                         goto exit;
3144                 }
3145
3146                 if (comp_pkt.completion_status >= 0) {
3147                         hbus->protocol_version = version[i];
3148                         dev_info(&hdev->device,
3149                                 "PCI VMBus probing: Using version %#x\n",
3150                                 hbus->protocol_version);
3151                         goto exit;
3152                 }
3153
3154                 if (comp_pkt.completion_status != STATUS_REVISION_MISMATCH) {
3155                         dev_err(&hdev->device,
3156                                 "PCI Pass-through VSP failed version request: %#x",
3157                                 comp_pkt.completion_status);
3158                         ret = -EPROTO;
3159                         goto exit;
3160                 }
3161
3162                 reinit_completion(&comp_pkt.host_event);
3163         }
3164
3165         dev_err(&hdev->device,
3166                 "PCI pass-through VSP failed to find supported version");
3167         ret = -EPROTO;
3168
3169 exit:
3170         kfree(pkt);
3171         return ret;
3172 }
3173
3174 /**
3175  * hv_pci_free_bridge_windows() - Release memory regions for the
3176  * bus
3177  * @hbus:       Root PCI bus, as understood by this driver
3178  */
3179 static void hv_pci_free_bridge_windows(struct hv_pcibus_device *hbus)
3180 {
3181         /*
3182          * Set the resources back to the way they looked when they
3183          * were allocated by setting IORESOURCE_BUSY again.
3184          */
3185
3186         if (hbus->low_mmio_space && hbus->low_mmio_res) {
3187                 hbus->low_mmio_res->flags |= IORESOURCE_BUSY;
3188                 vmbus_free_mmio(hbus->low_mmio_res->start,
3189                                 resource_size(hbus->low_mmio_res));
3190         }
3191
3192         if (hbus->high_mmio_space && hbus->high_mmio_res) {
3193                 hbus->high_mmio_res->flags |= IORESOURCE_BUSY;
3194                 vmbus_free_mmio(hbus->high_mmio_res->start,
3195                                 resource_size(hbus->high_mmio_res));
3196         }
3197 }
3198
3199 /**
3200  * hv_pci_allocate_bridge_windows() - Allocate memory regions
3201  * for the bus
3202  * @hbus:       Root PCI bus, as understood by this driver
3203  *
3204  * This function calls vmbus_allocate_mmio(), which is itself a
3205  * bit of a compromise.  Ideally, we might change the pnp layer
3206  * in the kernel such that it comprehends either PCI devices
3207  * which are "grandchildren of ACPI," with some intermediate bus
3208  * node (in this case, VMBus) or change it such that it
3209  * understands VMBus.  The pnp layer, however, has been declared
3210  * deprecated, and not subject to change.
3211  *
3212  * The workaround, implemented here, is to ask VMBus to allocate
3213  * MMIO space for this bus.  VMBus itself knows which ranges are
3214  * appropriate by looking at its own ACPI objects.  Then, after
3215  * these ranges are claimed, they're modified to look like they
3216  * would have looked if the ACPI and pnp code had allocated
3217  * bridge windows.  These descriptors have to exist in this form
3218  * in order to satisfy the code which will get invoked when the
3219  * endpoint PCI function driver calls request_mem_region() or
3220  * request_mem_region_exclusive().
3221  *
3222  * Return: 0 on success, -errno on failure
3223  */
3224 static int hv_pci_allocate_bridge_windows(struct hv_pcibus_device *hbus)
3225 {
3226         resource_size_t align;
3227         int ret;
3228
3229         if (hbus->low_mmio_space) {
3230                 align = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
3231                 ret = vmbus_allocate_mmio(&hbus->low_mmio_res, hbus->hdev, 0,
3232                                           (u64)(u32)0xffffffff,
3233                                           hbus->low_mmio_space,
3234                                           align, false);
3235                 if (ret) {
3236                         dev_err(&hbus->hdev->device,
3237                                 "Need %#llx of low MMIO space. Consider reconfiguring the VM.\n",
3238                                 hbus->low_mmio_space);
3239                         return ret;
3240                 }
3241
3242                 /* Modify this resource to become a bridge window. */
3243                 hbus->low_mmio_res->flags |= IORESOURCE_WINDOW;
3244                 hbus->low_mmio_res->flags &= ~IORESOURCE_BUSY;
3245                 pci_add_resource(&hbus->bridge->windows, hbus->low_mmio_res);
3246         }
3247
3248         if (hbus->high_mmio_space) {
3249                 align = 1ULL << (63 - __builtin_clzll(hbus->high_mmio_space));
3250                 ret = vmbus_allocate_mmio(&hbus->high_mmio_res, hbus->hdev,
3251                                           0x100000000, -1,
3252                                           hbus->high_mmio_space, align,
3253                                           false);
3254                 if (ret) {
3255                         dev_err(&hbus->hdev->device,
3256                                 "Need %#llx of high MMIO space. Consider reconfiguring the VM.\n",
3257                                 hbus->high_mmio_space);
3258                         goto release_low_mmio;
3259                 }
3260
3261                 /* Modify this resource to become a bridge window. */
3262                 hbus->high_mmio_res->flags |= IORESOURCE_WINDOW;
3263                 hbus->high_mmio_res->flags &= ~IORESOURCE_BUSY;
3264                 pci_add_resource(&hbus->bridge->windows, hbus->high_mmio_res);
3265         }
3266
3267         return 0;
3268
3269 release_low_mmio:
3270         if (hbus->low_mmio_res) {
3271                 vmbus_free_mmio(hbus->low_mmio_res->start,
3272                                 resource_size(hbus->low_mmio_res));
3273         }
3274
3275         return ret;
3276 }
3277
3278 /**
3279  * hv_allocate_config_window() - Find MMIO space for PCI Config
3280  * @hbus:       Root PCI bus, as understood by this driver
3281  *
3282  * This function claims memory-mapped I/O space for accessing
3283  * configuration space for the functions on this bus.
3284  *
3285  * Return: 0 on success, -errno on failure
3286  */
3287 static int hv_allocate_config_window(struct hv_pcibus_device *hbus)
3288 {
3289         int ret;
3290
3291         /*
3292          * Set up a region of MMIO space to use for accessing configuration
3293          * space.
3294          */
3295         ret = vmbus_allocate_mmio(&hbus->mem_config, hbus->hdev, 0, -1,
3296                                   PCI_CONFIG_MMIO_LENGTH, 0x1000, false);
3297         if (ret)
3298                 return ret;
3299
3300         /*
3301          * vmbus_allocate_mmio() gets used for allocating both device endpoint
3302          * resource claims (those which cannot be overlapped) and the ranges
3303          * which are valid for the children of this bus, which are intended
3304          * to be overlapped by those children.  Set the flag on this claim
3305          * meaning that this region can't be overlapped.
3306          */
3307
3308         hbus->mem_config->flags |= IORESOURCE_BUSY;
3309
3310         return 0;
3311 }
3312
3313 static void hv_free_config_window(struct hv_pcibus_device *hbus)
3314 {
3315         vmbus_free_mmio(hbus->mem_config->start, PCI_CONFIG_MMIO_LENGTH);
3316 }
3317
3318 static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs);
3319
3320 /**
3321  * hv_pci_enter_d0() - Bring the "bus" into the D0 power state
3322  * @hdev:       VMBus's tracking struct for this root PCI bus
3323  *
3324  * Return: 0 on success, -errno on failure
3325  */
3326 static int hv_pci_enter_d0(struct hv_device *hdev)
3327 {
3328         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3329         struct pci_bus_d0_entry *d0_entry;
3330         struct hv_pci_compl comp_pkt;
3331         struct pci_packet *pkt;
3332         bool retry = true;
3333         int ret;
3334
3335 enter_d0_retry:
3336         /*
3337          * Tell the host that the bus is ready to use, and moved into the
3338          * powered-on state.  This includes telling the host which region
3339          * of memory-mapped I/O space has been chosen for configuration space
3340          * access.
3341          */
3342         pkt = kzalloc(sizeof(*pkt) + sizeof(*d0_entry), GFP_KERNEL);
3343         if (!pkt)
3344                 return -ENOMEM;
3345
3346         init_completion(&comp_pkt.host_event);
3347         pkt->completion_func = hv_pci_generic_compl;
3348         pkt->compl_ctxt = &comp_pkt;
3349         d0_entry = (struct pci_bus_d0_entry *)&pkt->message;
3350         d0_entry->message_type.type = PCI_BUS_D0ENTRY;
3351         d0_entry->mmio_base = hbus->mem_config->start;
3352
3353         ret = vmbus_sendpacket(hdev->channel, d0_entry, sizeof(*d0_entry),
3354                                (unsigned long)pkt, VM_PKT_DATA_INBAND,
3355                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3356         if (!ret)
3357                 ret = wait_for_response(hdev, &comp_pkt.host_event);
3358
3359         if (ret)
3360                 goto exit;
3361
3362         /*
3363          * In certain case (Kdump) the pci device of interest was
3364          * not cleanly shut down and resource is still held on host
3365          * side, the host could return invalid device status.
3366          * We need to explicitly request host to release the resource
3367          * and try to enter D0 again.
3368          */
3369         if (comp_pkt.completion_status < 0 && retry) {
3370                 retry = false;
3371
3372                 dev_err(&hdev->device, "Retrying D0 Entry\n");
3373
3374                 /*
3375                  * Hv_pci_bus_exit() calls hv_send_resource_released()
3376                  * to free up resources of its child devices.
3377                  * In the kdump kernel we need to set the
3378                  * wslot_res_allocated to 255 so it scans all child
3379                  * devices to release resources allocated in the
3380                  * normal kernel before panic happened.
3381                  */
3382                 hbus->wslot_res_allocated = 255;
3383
3384                 ret = hv_pci_bus_exit(hdev, true);
3385
3386                 if (ret == 0) {
3387                         kfree(pkt);
3388                         goto enter_d0_retry;
3389                 }
3390                 dev_err(&hdev->device,
3391                         "Retrying D0 failed with ret %d\n", ret);
3392         }
3393
3394         if (comp_pkt.completion_status < 0) {
3395                 dev_err(&hdev->device,
3396                         "PCI Pass-through VSP failed D0 Entry with status %x\n",
3397                         comp_pkt.completion_status);
3398                 ret = -EPROTO;
3399                 goto exit;
3400         }
3401
3402         ret = 0;
3403
3404 exit:
3405         kfree(pkt);
3406         return ret;
3407 }
3408
3409 /**
3410  * hv_pci_query_relations() - Ask host to send list of child
3411  * devices
3412  * @hdev:       VMBus's tracking struct for this root PCI bus
3413  *
3414  * Return: 0 on success, -errno on failure
3415  */
3416 static int hv_pci_query_relations(struct hv_device *hdev)
3417 {
3418         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3419         struct pci_message message;
3420         struct completion comp;
3421         int ret;
3422
3423         /* Ask the host to send along the list of child devices */
3424         init_completion(&comp);
3425         if (cmpxchg(&hbus->survey_event, NULL, &comp))
3426                 return -ENOTEMPTY;
3427
3428         memset(&message, 0, sizeof(message));
3429         message.type = PCI_QUERY_BUS_RELATIONS;
3430
3431         ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
3432                                0, VM_PKT_DATA_INBAND, 0);
3433         if (!ret)
3434                 ret = wait_for_response(hdev, &comp);
3435
3436         /*
3437          * In the case of fast device addition/removal, it's possible that
3438          * vmbus_sendpacket() or wait_for_response() returns -ENODEV but we
3439          * already got a PCI_BUS_RELATIONS* message from the host and the
3440          * channel callback already scheduled a work to hbus->wq, which can be
3441          * running pci_devices_present_work() -> survey_child_resources() ->
3442          * complete(&hbus->survey_event), even after hv_pci_query_relations()
3443          * exits and the stack variable 'comp' is no longer valid; as a result,
3444          * a hang or a page fault may happen when the complete() calls
3445          * raw_spin_lock_irqsave(). Flush hbus->wq before we exit from
3446          * hv_pci_query_relations() to avoid the issues. Note: if 'ret' is
3447          * -ENODEV, there can't be any more work item scheduled to hbus->wq
3448          * after the flush_workqueue(): see vmbus_onoffer_rescind() ->
3449          * vmbus_reset_channel_cb(), vmbus_rescind_cleanup() ->
3450          * channel->rescind = true.
3451          */
3452         flush_workqueue(hbus->wq);
3453
3454         return ret;
3455 }
3456
3457 /**
3458  * hv_send_resources_allocated() - Report local resource choices
3459  * @hdev:       VMBus's tracking struct for this root PCI bus
3460  *
3461  * The host OS is expecting to be sent a request as a message
3462  * which contains all the resources that the device will use.
3463  * The response contains those same resources, "translated"
3464  * which is to say, the values which should be used by the
3465  * hardware, when it delivers an interrupt.  (MMIO resources are
3466  * used in local terms.)  This is nice for Windows, and lines up
3467  * with the FDO/PDO split, which doesn't exist in Linux.  Linux
3468  * is deeply expecting to scan an emulated PCI configuration
3469  * space.  So this message is sent here only to drive the state
3470  * machine on the host forward.
3471  *
3472  * Return: 0 on success, -errno on failure
3473  */
3474 static int hv_send_resources_allocated(struct hv_device *hdev)
3475 {
3476         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3477         struct pci_resources_assigned *res_assigned;
3478         struct pci_resources_assigned2 *res_assigned2;
3479         struct hv_pci_compl comp_pkt;
3480         struct hv_pci_dev *hpdev;
3481         struct pci_packet *pkt;
3482         size_t size_res;
3483         int wslot;
3484         int ret;
3485
3486         size_res = (hbus->protocol_version < PCI_PROTOCOL_VERSION_1_2)
3487                         ? sizeof(*res_assigned) : sizeof(*res_assigned2);
3488
3489         pkt = kmalloc(sizeof(*pkt) + size_res, GFP_KERNEL);
3490         if (!pkt)
3491                 return -ENOMEM;
3492
3493         ret = 0;
3494
3495         for (wslot = 0; wslot < 256; wslot++) {
3496                 hpdev = get_pcichild_wslot(hbus, wslot);
3497                 if (!hpdev)
3498                         continue;
3499
3500                 memset(pkt, 0, sizeof(*pkt) + size_res);
3501                 init_completion(&comp_pkt.host_event);
3502                 pkt->completion_func = hv_pci_generic_compl;
3503                 pkt->compl_ctxt = &comp_pkt;
3504
3505                 if (hbus->protocol_version < PCI_PROTOCOL_VERSION_1_2) {
3506                         res_assigned =
3507                                 (struct pci_resources_assigned *)&pkt->message;
3508                         res_assigned->message_type.type =
3509                                 PCI_RESOURCES_ASSIGNED;
3510                         res_assigned->wslot.slot = hpdev->desc.win_slot.slot;
3511                 } else {
3512                         res_assigned2 =
3513                                 (struct pci_resources_assigned2 *)&pkt->message;
3514                         res_assigned2->message_type.type =
3515                                 PCI_RESOURCES_ASSIGNED2;
3516                         res_assigned2->wslot.slot = hpdev->desc.win_slot.slot;
3517                 }
3518                 put_pcichild(hpdev);
3519
3520                 ret = vmbus_sendpacket(hdev->channel, &pkt->message,
3521                                 size_res, (unsigned long)pkt,
3522                                 VM_PKT_DATA_INBAND,
3523                                 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3524                 if (!ret)
3525                         ret = wait_for_response(hdev, &comp_pkt.host_event);
3526                 if (ret)
3527                         break;
3528
3529                 if (comp_pkt.completion_status < 0) {
3530                         ret = -EPROTO;
3531                         dev_err(&hdev->device,
3532                                 "resource allocated returned 0x%x",
3533                                 comp_pkt.completion_status);
3534                         break;
3535                 }
3536
3537                 hbus->wslot_res_allocated = wslot;
3538         }
3539
3540         kfree(pkt);
3541         return ret;
3542 }
3543
3544 /**
3545  * hv_send_resources_released() - Report local resources
3546  * released
3547  * @hdev:       VMBus's tracking struct for this root PCI bus
3548  *
3549  * Return: 0 on success, -errno on failure
3550  */
3551 static int hv_send_resources_released(struct hv_device *hdev)
3552 {
3553         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3554         struct pci_child_message pkt;
3555         struct hv_pci_dev *hpdev;
3556         int wslot;
3557         int ret;
3558
3559         for (wslot = hbus->wslot_res_allocated; wslot >= 0; wslot--) {
3560                 hpdev = get_pcichild_wslot(hbus, wslot);
3561                 if (!hpdev)
3562                         continue;
3563
3564                 memset(&pkt, 0, sizeof(pkt));
3565                 pkt.message_type.type = PCI_RESOURCES_RELEASED;
3566                 pkt.wslot.slot = hpdev->desc.win_slot.slot;
3567
3568                 put_pcichild(hpdev);
3569
3570                 ret = vmbus_sendpacket(hdev->channel, &pkt, sizeof(pkt), 0,
3571                                        VM_PKT_DATA_INBAND, 0);
3572                 if (ret)
3573                         return ret;
3574
3575                 hbus->wslot_res_allocated = wslot - 1;
3576         }
3577
3578         hbus->wslot_res_allocated = -1;
3579
3580         return 0;
3581 }
3582
3583 #define HVPCI_DOM_MAP_SIZE (64 * 1024)
3584 static DECLARE_BITMAP(hvpci_dom_map, HVPCI_DOM_MAP_SIZE);
3585
3586 /*
3587  * PCI domain number 0 is used by emulated devices on Gen1 VMs, so define 0
3588  * as invalid for passthrough PCI devices of this driver.
3589  */
3590 #define HVPCI_DOM_INVALID 0
3591
3592 /**
3593  * hv_get_dom_num() - Get a valid PCI domain number
3594  * Check if the PCI domain number is in use, and return another number if
3595  * it is in use.
3596  *
3597  * @dom: Requested domain number
3598  *
3599  * return: domain number on success, HVPCI_DOM_INVALID on failure
3600  */
3601 static u16 hv_get_dom_num(u16 dom)
3602 {
3603         unsigned int i;
3604
3605         if (test_and_set_bit(dom, hvpci_dom_map) == 0)
3606                 return dom;
3607
3608         for_each_clear_bit(i, hvpci_dom_map, HVPCI_DOM_MAP_SIZE) {
3609                 if (test_and_set_bit(i, hvpci_dom_map) == 0)
3610                         return i;
3611         }
3612
3613         return HVPCI_DOM_INVALID;
3614 }
3615
3616 /**
3617  * hv_put_dom_num() - Mark the PCI domain number as free
3618  * @dom: Domain number to be freed
3619  */
3620 static void hv_put_dom_num(u16 dom)
3621 {
3622         clear_bit(dom, hvpci_dom_map);
3623 }
3624
3625 /**
3626  * hv_pci_probe() - New VMBus channel probe, for a root PCI bus
3627  * @hdev:       VMBus's tracking struct for this root PCI bus
3628  * @dev_id:     Identifies the device itself
3629  *
3630  * Return: 0 on success, -errno on failure
3631  */
3632 static int hv_pci_probe(struct hv_device *hdev,
3633                         const struct hv_vmbus_device_id *dev_id)
3634 {
3635         struct pci_host_bridge *bridge;
3636         struct hv_pcibus_device *hbus;
3637         u16 dom_req, dom;
3638         char *name;
3639         int ret;
3640
3641         bridge = devm_pci_alloc_host_bridge(&hdev->device, 0);
3642         if (!bridge)
3643                 return -ENOMEM;
3644
3645         hbus = kzalloc(sizeof(*hbus), GFP_KERNEL);
3646         if (!hbus)
3647                 return -ENOMEM;
3648
3649         hbus->bridge = bridge;
3650         mutex_init(&hbus->state_lock);
3651         hbus->state = hv_pcibus_init;
3652         hbus->wslot_res_allocated = -1;
3653
3654         /*
3655          * The PCI bus "domain" is what is called "segment" in ACPI and other
3656          * specs. Pull it from the instance ID, to get something usually
3657          * unique. In rare cases of collision, we will find out another number
3658          * not in use.
3659          *
3660          * Note that, since this code only runs in a Hyper-V VM, Hyper-V
3661          * together with this guest driver can guarantee that (1) The only
3662          * domain used by Gen1 VMs for something that looks like a physical
3663          * PCI bus (which is actually emulated by the hypervisor) is domain 0.
3664          * (2) There will be no overlap between domains (after fixing possible
3665          * collisions) in the same VM.
3666          */
3667         dom_req = hdev->dev_instance.b[5] << 8 | hdev->dev_instance.b[4];
3668         dom = hv_get_dom_num(dom_req);
3669
3670         if (dom == HVPCI_DOM_INVALID) {
3671                 dev_err(&hdev->device,
3672                         "Unable to use dom# 0x%x or other numbers", dom_req);
3673                 ret = -EINVAL;
3674                 goto free_bus;
3675         }
3676
3677         if (dom != dom_req)
3678                 dev_info(&hdev->device,
3679                          "PCI dom# 0x%x has collision, using 0x%x",
3680                          dom_req, dom);
3681
3682         hbus->bridge->domain_nr = dom;
3683 #ifdef CONFIG_X86
3684         hbus->sysdata.domain = dom;
3685         hbus->use_calls = !!(ms_hyperv.hints & HV_X64_USE_MMIO_HYPERCALLS);
3686 #elif defined(CONFIG_ARM64)
3687         /*
3688          * Set the PCI bus parent to be the corresponding VMbus
3689          * device. Then the VMbus device will be assigned as the
3690          * ACPI companion in pcibios_root_bridge_prepare() and
3691          * pci_dma_configure() will propagate device coherence
3692          * information to devices created on the bus.
3693          */
3694         hbus->sysdata.parent = hdev->device.parent;
3695         hbus->use_calls = false;
3696 #endif
3697
3698         hbus->hdev = hdev;
3699         INIT_LIST_HEAD(&hbus->children);
3700         INIT_LIST_HEAD(&hbus->dr_list);
3701         spin_lock_init(&hbus->config_lock);
3702         spin_lock_init(&hbus->device_list_lock);
3703         hbus->wq = alloc_ordered_workqueue("hv_pci_%x", 0,
3704                                            hbus->bridge->domain_nr);
3705         if (!hbus->wq) {
3706                 ret = -ENOMEM;
3707                 goto free_dom;
3708         }
3709
3710         hdev->channel->next_request_id_callback = vmbus_next_request_id;
3711         hdev->channel->request_addr_callback = vmbus_request_addr;
3712         hdev->channel->rqstor_size = HV_PCI_RQSTOR_SIZE;
3713
3714         ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
3715                          hv_pci_onchannelcallback, hbus);
3716         if (ret)
3717                 goto destroy_wq;
3718
3719         hv_set_drvdata(hdev, hbus);
3720
3721         ret = hv_pci_protocol_negotiation(hdev, pci_protocol_versions,
3722                                           ARRAY_SIZE(pci_protocol_versions));
3723         if (ret)
3724                 goto close;
3725
3726         ret = hv_allocate_config_window(hbus);
3727         if (ret)
3728                 goto close;
3729
3730         hbus->cfg_addr = ioremap(hbus->mem_config->start,
3731                                  PCI_CONFIG_MMIO_LENGTH);
3732         if (!hbus->cfg_addr) {
3733                 dev_err(&hdev->device,
3734                         "Unable to map a virtual address for config space\n");
3735                 ret = -ENOMEM;
3736                 goto free_config;
3737         }
3738
3739         name = kasprintf(GFP_KERNEL, "%pUL", &hdev->dev_instance);
3740         if (!name) {
3741                 ret = -ENOMEM;
3742                 goto unmap;
3743         }
3744
3745         hbus->fwnode = irq_domain_alloc_named_fwnode(name);
3746         kfree(name);
3747         if (!hbus->fwnode) {
3748                 ret = -ENOMEM;
3749                 goto unmap;
3750         }
3751
3752         ret = hv_pcie_init_irq_domain(hbus);
3753         if (ret)
3754                 goto free_fwnode;
3755
3756         ret = hv_pci_query_relations(hdev);
3757         if (ret)
3758                 goto free_irq_domain;
3759
3760         mutex_lock(&hbus->state_lock);
3761
3762         ret = hv_pci_enter_d0(hdev);
3763         if (ret)
3764                 goto release_state_lock;
3765
3766         ret = hv_pci_allocate_bridge_windows(hbus);
3767         if (ret)
3768                 goto exit_d0;
3769
3770         ret = hv_send_resources_allocated(hdev);
3771         if (ret)
3772                 goto free_windows;
3773
3774         prepopulate_bars(hbus);
3775
3776         hbus->state = hv_pcibus_probed;
3777
3778         ret = create_root_hv_pci_bus(hbus);
3779         if (ret)
3780                 goto free_windows;
3781
3782         mutex_unlock(&hbus->state_lock);
3783         return 0;
3784
3785 free_windows:
3786         hv_pci_free_bridge_windows(hbus);
3787 exit_d0:
3788         (void) hv_pci_bus_exit(hdev, true);
3789 release_state_lock:
3790         mutex_unlock(&hbus->state_lock);
3791 free_irq_domain:
3792         irq_domain_remove(hbus->irq_domain);
3793 free_fwnode:
3794         irq_domain_free_fwnode(hbus->fwnode);
3795 unmap:
3796         iounmap(hbus->cfg_addr);
3797 free_config:
3798         hv_free_config_window(hbus);
3799 close:
3800         vmbus_close(hdev->channel);
3801 destroy_wq:
3802         destroy_workqueue(hbus->wq);
3803 free_dom:
3804         hv_put_dom_num(hbus->bridge->domain_nr);
3805 free_bus:
3806         kfree(hbus);
3807         return ret;
3808 }
3809
3810 static int hv_pci_bus_exit(struct hv_device *hdev, bool keep_devs)
3811 {
3812         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3813         struct vmbus_channel *chan = hdev->channel;
3814         struct {
3815                 struct pci_packet teardown_packet;
3816                 u8 buffer[sizeof(struct pci_message)];
3817         } pkt;
3818         struct hv_pci_compl comp_pkt;
3819         struct hv_pci_dev *hpdev, *tmp;
3820         unsigned long flags;
3821         u64 trans_id;
3822         int ret;
3823
3824         /*
3825          * After the host sends the RESCIND_CHANNEL message, it doesn't
3826          * access the per-channel ringbuffer any longer.
3827          */
3828         if (chan->rescind)
3829                 return 0;
3830
3831         if (!keep_devs) {
3832                 struct list_head removed;
3833
3834                 /* Move all present children to the list on stack */
3835                 INIT_LIST_HEAD(&removed);
3836                 spin_lock_irqsave(&hbus->device_list_lock, flags);
3837                 list_for_each_entry_safe(hpdev, tmp, &hbus->children, list_entry)
3838                         list_move_tail(&hpdev->list_entry, &removed);
3839                 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
3840
3841                 /* Remove all children in the list */
3842                 list_for_each_entry_safe(hpdev, tmp, &removed, list_entry) {
3843                         list_del(&hpdev->list_entry);
3844                         if (hpdev->pci_slot)
3845                                 pci_destroy_slot(hpdev->pci_slot);
3846                         /* For the two refs got in new_pcichild_device() */
3847                         put_pcichild(hpdev);
3848                         put_pcichild(hpdev);
3849                 }
3850         }
3851
3852         ret = hv_send_resources_released(hdev);
3853         if (ret) {
3854                 dev_err(&hdev->device,
3855                         "Couldn't send resources released packet(s)\n");
3856                 return ret;
3857         }
3858
3859         memset(&pkt.teardown_packet, 0, sizeof(pkt.teardown_packet));
3860         init_completion(&comp_pkt.host_event);
3861         pkt.teardown_packet.completion_func = hv_pci_generic_compl;
3862         pkt.teardown_packet.compl_ctxt = &comp_pkt;
3863         pkt.teardown_packet.message[0].type = PCI_BUS_D0EXIT;
3864
3865         ret = vmbus_sendpacket_getid(chan, &pkt.teardown_packet.message,
3866                                      sizeof(struct pci_message),
3867                                      (unsigned long)&pkt.teardown_packet,
3868                                      &trans_id, VM_PKT_DATA_INBAND,
3869                                      VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3870         if (ret)
3871                 return ret;
3872
3873         if (wait_for_completion_timeout(&comp_pkt.host_event, 10 * HZ) == 0) {
3874                 /*
3875                  * The completion packet on the stack becomes invalid after
3876                  * 'return'; remove the ID from the VMbus requestor if the
3877                  * identifier is still mapped to/associated with the packet.
3878                  *
3879                  * Cf. hv_pci_onchannelcallback().
3880                  */
3881                 vmbus_request_addr_match(chan, trans_id,
3882                                          (unsigned long)&pkt.teardown_packet);
3883                 return -ETIMEDOUT;
3884         }
3885
3886         return 0;
3887 }
3888
3889 /**
3890  * hv_pci_remove() - Remove routine for this VMBus channel
3891  * @hdev:       VMBus's tracking struct for this root PCI bus
3892  */
3893 static void hv_pci_remove(struct hv_device *hdev)
3894 {
3895         struct hv_pcibus_device *hbus;
3896
3897         hbus = hv_get_drvdata(hdev);
3898         if (hbus->state == hv_pcibus_installed) {
3899                 tasklet_disable(&hdev->channel->callback_event);
3900                 hbus->state = hv_pcibus_removing;
3901                 tasklet_enable(&hdev->channel->callback_event);
3902                 destroy_workqueue(hbus->wq);
3903                 hbus->wq = NULL;
3904                 /*
3905                  * At this point, no work is running or can be scheduled
3906                  * on hbus-wq. We can't race with hv_pci_devices_present()
3907                  * or hv_pci_eject_device(), it's safe to proceed.
3908                  */
3909
3910                 /* Remove the bus from PCI's point of view. */
3911                 pci_lock_rescan_remove();
3912                 pci_stop_root_bus(hbus->bridge->bus);
3913                 hv_pci_remove_slots(hbus);
3914                 pci_remove_root_bus(hbus->bridge->bus);
3915                 pci_unlock_rescan_remove();
3916         }
3917
3918         hv_pci_bus_exit(hdev, false);
3919
3920         vmbus_close(hdev->channel);
3921
3922         iounmap(hbus->cfg_addr);
3923         hv_free_config_window(hbus);
3924         hv_pci_free_bridge_windows(hbus);
3925         irq_domain_remove(hbus->irq_domain);
3926         irq_domain_free_fwnode(hbus->fwnode);
3927
3928         hv_put_dom_num(hbus->bridge->domain_nr);
3929
3930         kfree(hbus);
3931 }
3932
3933 static int hv_pci_suspend(struct hv_device *hdev)
3934 {
3935         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
3936         enum hv_pcibus_state old_state;
3937         int ret;
3938
3939         /*
3940          * hv_pci_suspend() must make sure there are no pending work items
3941          * before calling vmbus_close(), since it runs in a process context
3942          * as a callback in dpm_suspend().  When it starts to run, the channel
3943          * callback hv_pci_onchannelcallback(), which runs in a tasklet
3944          * context, can be still running concurrently and scheduling new work
3945          * items onto hbus->wq in hv_pci_devices_present() and
3946          * hv_pci_eject_device(), and the work item handlers can access the
3947          * vmbus channel, which can be being closed by hv_pci_suspend(), e.g.
3948          * the work item handler pci_devices_present_work() ->
3949          * new_pcichild_device() writes to the vmbus channel.
3950          *
3951          * To eliminate the race, hv_pci_suspend() disables the channel
3952          * callback tasklet, sets hbus->state to hv_pcibus_removing, and
3953          * re-enables the tasklet. This way, when hv_pci_suspend() proceeds,
3954          * it knows that no new work item can be scheduled, and then it flushes
3955          * hbus->wq and safely closes the vmbus channel.
3956          */
3957         tasklet_disable(&hdev->channel->callback_event);
3958
3959         /* Change the hbus state to prevent new work items. */
3960         old_state = hbus->state;
3961         if (hbus->state == hv_pcibus_installed)
3962                 hbus->state = hv_pcibus_removing;
3963
3964         tasklet_enable(&hdev->channel->callback_event);
3965
3966         if (old_state != hv_pcibus_installed)
3967                 return -EINVAL;
3968
3969         flush_workqueue(hbus->wq);
3970
3971         ret = hv_pci_bus_exit(hdev, true);
3972         if (ret)
3973                 return ret;
3974
3975         vmbus_close(hdev->channel);
3976
3977         return 0;
3978 }
3979
3980 static int hv_pci_restore_msi_msg(struct pci_dev *pdev, void *arg)
3981 {
3982         struct irq_data *irq_data;
3983         struct msi_desc *entry;
3984         int ret = 0;
3985
3986         if (!pdev->msi_enabled && !pdev->msix_enabled)
3987                 return 0;
3988
3989         msi_lock_descs(&pdev->dev);
3990         msi_for_each_desc(entry, &pdev->dev, MSI_DESC_ASSOCIATED) {
3991                 irq_data = irq_get_irq_data(entry->irq);
3992                 if (WARN_ON_ONCE(!irq_data)) {
3993                         ret = -EINVAL;
3994                         break;
3995                 }
3996
3997                 hv_compose_msi_msg(irq_data, &entry->msg);
3998         }
3999         msi_unlock_descs(&pdev->dev);
4000
4001         return ret;
4002 }
4003
4004 /*
4005  * Upon resume, pci_restore_msi_state() -> ... ->  __pci_write_msi_msg()
4006  * directly writes the MSI/MSI-X registers via MMIO, but since Hyper-V
4007  * doesn't trap and emulate the MMIO accesses, here hv_compose_msi_msg()
4008  * must be used to ask Hyper-V to re-create the IOMMU Interrupt Remapping
4009  * Table entries.
4010  */
4011 static void hv_pci_restore_msi_state(struct hv_pcibus_device *hbus)
4012 {
4013         pci_walk_bus(hbus->bridge->bus, hv_pci_restore_msi_msg, NULL);
4014 }
4015
4016 static int hv_pci_resume(struct hv_device *hdev)
4017 {
4018         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
4019         enum pci_protocol_version_t version[1];
4020         int ret;
4021
4022         hbus->state = hv_pcibus_init;
4023
4024         hdev->channel->next_request_id_callback = vmbus_next_request_id;
4025         hdev->channel->request_addr_callback = vmbus_request_addr;
4026         hdev->channel->rqstor_size = HV_PCI_RQSTOR_SIZE;
4027
4028         ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
4029                          hv_pci_onchannelcallback, hbus);
4030         if (ret)
4031                 return ret;
4032
4033         /* Only use the version that was in use before hibernation. */
4034         version[0] = hbus->protocol_version;
4035         ret = hv_pci_protocol_negotiation(hdev, version, 1);
4036         if (ret)
4037                 goto out;
4038
4039         ret = hv_pci_query_relations(hdev);
4040         if (ret)
4041                 goto out;
4042
4043         mutex_lock(&hbus->state_lock);
4044
4045         ret = hv_pci_enter_d0(hdev);
4046         if (ret)
4047                 goto release_state_lock;
4048
4049         ret = hv_send_resources_allocated(hdev);
4050         if (ret)
4051                 goto release_state_lock;
4052
4053         prepopulate_bars(hbus);
4054
4055         hv_pci_restore_msi_state(hbus);
4056
4057         hbus->state = hv_pcibus_installed;
4058         mutex_unlock(&hbus->state_lock);
4059         return 0;
4060
4061 release_state_lock:
4062         mutex_unlock(&hbus->state_lock);
4063 out:
4064         vmbus_close(hdev->channel);
4065         return ret;
4066 }
4067
4068 static const struct hv_vmbus_device_id hv_pci_id_table[] = {
4069         /* PCI Pass-through Class ID */
4070         /* 44C4F61D-4444-4400-9D52-802E27EDE19F */
4071         { HV_PCIE_GUID, },
4072         { },
4073 };
4074
4075 MODULE_DEVICE_TABLE(vmbus, hv_pci_id_table);
4076
4077 static struct hv_driver hv_pci_drv = {
4078         .name           = "hv_pci",
4079         .id_table       = hv_pci_id_table,
4080         .probe          = hv_pci_probe,
4081         .remove         = hv_pci_remove,
4082         .suspend        = hv_pci_suspend,
4083         .resume         = hv_pci_resume,
4084 };
4085
4086 static void __exit exit_hv_pci_drv(void)
4087 {
4088         vmbus_driver_unregister(&hv_pci_drv);
4089
4090         hvpci_block_ops.read_block = NULL;
4091         hvpci_block_ops.write_block = NULL;
4092         hvpci_block_ops.reg_blk_invalidate = NULL;
4093 }
4094
4095 static int __init init_hv_pci_drv(void)
4096 {
4097         int ret;
4098
4099         if (!hv_is_hyperv_initialized())
4100                 return -ENODEV;
4101
4102         ret = hv_pci_irqchip_init();
4103         if (ret)
4104                 return ret;
4105
4106         /* Set the invalid domain number's bit, so it will not be used */
4107         set_bit(HVPCI_DOM_INVALID, hvpci_dom_map);
4108
4109         /* Initialize PCI block r/w interface */
4110         hvpci_block_ops.read_block = hv_read_config_block;
4111         hvpci_block_ops.write_block = hv_write_config_block;
4112         hvpci_block_ops.reg_blk_invalidate = hv_register_block_invalidate;
4113
4114         return vmbus_driver_register(&hv_pci_drv);
4115 }
4116
4117 module_init(init_hv_pci_drv);
4118 module_exit(exit_hv_pci_drv);
4119
4120 MODULE_DESCRIPTION("Hyper-V PCI");
4121 MODULE_LICENSE("GPL v2");