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