Merge tag 'pci-v4.16-changes' of git://git.kernel.org/pub/scm/linux/kernel/git/helgaa...
[linux.git] / drivers / pci / host / 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/msi.h>
49 #include <linux/hyperv.h>
50 #include <linux/refcount.h>
51 #include <asm/mshyperv.h>
52
53 /*
54  * Protocol versions. The low word is the minor version, the high word the
55  * major version.
56  */
57
58 #define PCI_MAKE_VERSION(major, minor) ((u32)(((major) << 16) | (minor)))
59 #define PCI_MAJOR_VERSION(version) ((u32)(version) >> 16)
60 #define PCI_MINOR_VERSION(version) ((u32)(version) & 0xff)
61
62 enum pci_protocol_version_t {
63         PCI_PROTOCOL_VERSION_1_1 = PCI_MAKE_VERSION(1, 1),      /* Win10 */
64         PCI_PROTOCOL_VERSION_1_2 = PCI_MAKE_VERSION(1, 2),      /* RS1 */
65 };
66
67 #define CPU_AFFINITY_ALL        -1ULL
68
69 /*
70  * Supported protocol versions in the order of probing - highest go
71  * first.
72  */
73 static enum pci_protocol_version_t pci_protocol_versions[] = {
74         PCI_PROTOCOL_VERSION_1_2,
75         PCI_PROTOCOL_VERSION_1_1,
76 };
77
78 /*
79  * Protocol version negotiated by hv_pci_protocol_negotiation().
80  */
81 static enum pci_protocol_version_t pci_protocol_version;
82
83 #define PCI_CONFIG_MMIO_LENGTH  0x2000
84 #define CFG_PAGE_OFFSET 0x1000
85 #define CFG_PAGE_SIZE (PCI_CONFIG_MMIO_LENGTH - CFG_PAGE_OFFSET)
86
87 #define MAX_SUPPORTED_MSI_MESSAGES 0x400
88
89 #define STATUS_REVISION_MISMATCH 0xC0000059
90
91 /*
92  * Message Types
93  */
94
95 enum pci_message_type {
96         /*
97          * Version 1.1
98          */
99         PCI_MESSAGE_BASE                = 0x42490000,
100         PCI_BUS_RELATIONS               = PCI_MESSAGE_BASE + 0,
101         PCI_QUERY_BUS_RELATIONS         = PCI_MESSAGE_BASE + 1,
102         PCI_POWER_STATE_CHANGE          = PCI_MESSAGE_BASE + 4,
103         PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5,
104         PCI_QUERY_RESOURCE_RESOURCES    = PCI_MESSAGE_BASE + 6,
105         PCI_BUS_D0ENTRY                 = PCI_MESSAGE_BASE + 7,
106         PCI_BUS_D0EXIT                  = PCI_MESSAGE_BASE + 8,
107         PCI_READ_BLOCK                  = PCI_MESSAGE_BASE + 9,
108         PCI_WRITE_BLOCK                 = PCI_MESSAGE_BASE + 0xA,
109         PCI_EJECT                       = PCI_MESSAGE_BASE + 0xB,
110         PCI_QUERY_STOP                  = PCI_MESSAGE_BASE + 0xC,
111         PCI_REENABLE                    = PCI_MESSAGE_BASE + 0xD,
112         PCI_QUERY_STOP_FAILED           = PCI_MESSAGE_BASE + 0xE,
113         PCI_EJECTION_COMPLETE           = PCI_MESSAGE_BASE + 0xF,
114         PCI_RESOURCES_ASSIGNED          = PCI_MESSAGE_BASE + 0x10,
115         PCI_RESOURCES_RELEASED          = PCI_MESSAGE_BASE + 0x11,
116         PCI_INVALIDATE_BLOCK            = PCI_MESSAGE_BASE + 0x12,
117         PCI_QUERY_PROTOCOL_VERSION      = PCI_MESSAGE_BASE + 0x13,
118         PCI_CREATE_INTERRUPT_MESSAGE    = PCI_MESSAGE_BASE + 0x14,
119         PCI_DELETE_INTERRUPT_MESSAGE    = PCI_MESSAGE_BASE + 0x15,
120         PCI_RESOURCES_ASSIGNED2         = PCI_MESSAGE_BASE + 0x16,
121         PCI_CREATE_INTERRUPT_MESSAGE2   = PCI_MESSAGE_BASE + 0x17,
122         PCI_DELETE_INTERRUPT_MESSAGE2   = PCI_MESSAGE_BASE + 0x18, /* unused */
123         PCI_MESSAGE_MAXIMUM
124 };
125
126 /*
127  * Structures defining the virtual PCI Express protocol.
128  */
129
130 union pci_version {
131         struct {
132                 u16 minor_version;
133                 u16 major_version;
134         } parts;
135         u32 version;
136 } __packed;
137
138 /*
139  * Function numbers are 8-bits wide on Express, as interpreted through ARI,
140  * which is all this driver does.  This representation is the one used in
141  * Windows, which is what is expected when sending this back and forth with
142  * the Hyper-V parent partition.
143  */
144 union win_slot_encoding {
145         struct {
146                 u32     dev:5;
147                 u32     func:3;
148                 u32     reserved:24;
149         } bits;
150         u32 slot;
151 } __packed;
152
153 /*
154  * Pretty much as defined in the PCI Specifications.
155  */
156 struct pci_function_description {
157         u16     v_id;   /* vendor ID */
158         u16     d_id;   /* device ID */
159         u8      rev;
160         u8      prog_intf;
161         u8      subclass;
162         u8      base_class;
163         u32     subsystem_id;
164         union win_slot_encoding win_slot;
165         u32     ser;    /* serial number */
166 } __packed;
167
168 /**
169  * struct hv_msi_desc
170  * @vector:             IDT entry
171  * @delivery_mode:      As defined in Intel's Programmer's
172  *                      Reference Manual, Volume 3, Chapter 8.
173  * @vector_count:       Number of contiguous entries in the
174  *                      Interrupt Descriptor Table that are
175  *                      occupied by this Message-Signaled
176  *                      Interrupt. For "MSI", as first defined
177  *                      in PCI 2.2, this can be between 1 and
178  *                      32. For "MSI-X," as first defined in PCI
179  *                      3.0, this must be 1, as each MSI-X table
180  *                      entry would have its own descriptor.
181  * @reserved:           Empty space
182  * @cpu_mask:           All the target virtual processors.
183  */
184 struct hv_msi_desc {
185         u8      vector;
186         u8      delivery_mode;
187         u16     vector_count;
188         u32     reserved;
189         u64     cpu_mask;
190 } __packed;
191
192 /**
193  * struct hv_msi_desc2 - 1.2 version of hv_msi_desc
194  * @vector:             IDT entry
195  * @delivery_mode:      As defined in Intel's Programmer's
196  *                      Reference Manual, Volume 3, Chapter 8.
197  * @vector_count:       Number of contiguous entries in the
198  *                      Interrupt Descriptor Table that are
199  *                      occupied by this Message-Signaled
200  *                      Interrupt. For "MSI", as first defined
201  *                      in PCI 2.2, this can be between 1 and
202  *                      32. For "MSI-X," as first defined in PCI
203  *                      3.0, this must be 1, as each MSI-X table
204  *                      entry would have its own descriptor.
205  * @processor_count:    number of bits enabled in array.
206  * @processor_array:    All the target virtual processors.
207  */
208 struct hv_msi_desc2 {
209         u8      vector;
210         u8      delivery_mode;
211         u16     vector_count;
212         u16     processor_count;
213         u16     processor_array[32];
214 } __packed;
215
216 /**
217  * struct tran_int_desc
218  * @reserved:           unused, padding
219  * @vector_count:       same as in hv_msi_desc
220  * @data:               This is the "data payload" value that is
221  *                      written by the device when it generates
222  *                      a message-signaled interrupt, either MSI
223  *                      or MSI-X.
224  * @address:            This is the address to which the data
225  *                      payload is written on interrupt
226  *                      generation.
227  */
228 struct tran_int_desc {
229         u16     reserved;
230         u16     vector_count;
231         u32     data;
232         u64     address;
233 } __packed;
234
235 /*
236  * A generic message format for virtual PCI.
237  * Specific message formats are defined later in the file.
238  */
239
240 struct pci_message {
241         u32 type;
242 } __packed;
243
244 struct pci_child_message {
245         struct pci_message message_type;
246         union win_slot_encoding wslot;
247 } __packed;
248
249 struct pci_incoming_message {
250         struct vmpacket_descriptor hdr;
251         struct pci_message message_type;
252 } __packed;
253
254 struct pci_response {
255         struct vmpacket_descriptor hdr;
256         s32 status;                     /* negative values are failures */
257 } __packed;
258
259 struct pci_packet {
260         void (*completion_func)(void *context, struct pci_response *resp,
261                                 int resp_packet_size);
262         void *compl_ctxt;
263
264         struct pci_message message[0];
265 };
266
267 /*
268  * Specific message types supporting the PCI protocol.
269  */
270
271 /*
272  * Version negotiation message. Sent from the guest to the host.
273  * The guest is free to try different versions until the host
274  * accepts the version.
275  *
276  * pci_version: The protocol version requested.
277  * is_last_attempt: If TRUE, this is the last version guest will request.
278  * reservedz: Reserved field, set to zero.
279  */
280
281 struct pci_version_request {
282         struct pci_message message_type;
283         u32 protocol_version;
284 } __packed;
285
286 /*
287  * Bus D0 Entry.  This is sent from the guest to the host when the virtual
288  * bus (PCI Express port) is ready for action.
289  */
290
291 struct pci_bus_d0_entry {
292         struct pci_message message_type;
293         u32 reserved;
294         u64 mmio_base;
295 } __packed;
296
297 struct pci_bus_relations {
298         struct pci_incoming_message incoming;
299         u32 device_count;
300         struct pci_function_description func[0];
301 } __packed;
302
303 struct pci_q_res_req_response {
304         struct vmpacket_descriptor hdr;
305         s32 status;                     /* negative values are failures */
306         u32 probed_bar[6];
307 } __packed;
308
309 struct pci_set_power {
310         struct pci_message message_type;
311         union win_slot_encoding wslot;
312         u32 power_state;                /* In Windows terms */
313         u32 reserved;
314 } __packed;
315
316 struct pci_set_power_response {
317         struct vmpacket_descriptor hdr;
318         s32 status;                     /* negative values are failures */
319         union win_slot_encoding wslot;
320         u32 resultant_state;            /* In Windows terms */
321         u32 reserved;
322 } __packed;
323
324 struct pci_resources_assigned {
325         struct pci_message message_type;
326         union win_slot_encoding wslot;
327         u8 memory_range[0x14][6];       /* not used here */
328         u32 msi_descriptors;
329         u32 reserved[4];
330 } __packed;
331
332 struct pci_resources_assigned2 {
333         struct pci_message message_type;
334         union win_slot_encoding wslot;
335         u8 memory_range[0x14][6];       /* not used here */
336         u32 msi_descriptor_count;
337         u8 reserved[70];
338 } __packed;
339
340 struct pci_create_interrupt {
341         struct pci_message message_type;
342         union win_slot_encoding wslot;
343         struct hv_msi_desc int_desc;
344 } __packed;
345
346 struct pci_create_int_response {
347         struct pci_response response;
348         u32 reserved;
349         struct tran_int_desc int_desc;
350 } __packed;
351
352 struct pci_create_interrupt2 {
353         struct pci_message message_type;
354         union win_slot_encoding wslot;
355         struct hv_msi_desc2 int_desc;
356 } __packed;
357
358 struct pci_delete_interrupt {
359         struct pci_message message_type;
360         union win_slot_encoding wslot;
361         struct tran_int_desc int_desc;
362 } __packed;
363
364 struct pci_dev_incoming {
365         struct pci_incoming_message incoming;
366         union win_slot_encoding wslot;
367 } __packed;
368
369 struct pci_eject_response {
370         struct pci_message message_type;
371         union win_slot_encoding wslot;
372         u32 status;
373 } __packed;
374
375 static int pci_ring_size = (4 * PAGE_SIZE);
376
377 /*
378  * Definitions or interrupt steering hypercall.
379  */
380 #define HV_PARTITION_ID_SELF            ((u64)-1)
381 #define HVCALL_RETARGET_INTERRUPT       0x7e
382
383 struct hv_interrupt_entry {
384         u32     source;                 /* 1 for MSI(-X) */
385         u32     reserved1;
386         u32     address;
387         u32     data;
388 };
389
390 #define HV_VP_SET_BANK_COUNT_MAX        5 /* current implementation limit */
391
392 struct hv_vp_set {
393         u64     format;                 /* 0 (HvGenericSetSparse4k) */
394         u64     valid_banks;
395         u64     masks[HV_VP_SET_BANK_COUNT_MAX];
396 };
397
398 /*
399  * flags for hv_device_interrupt_target.flags
400  */
401 #define HV_DEVICE_INTERRUPT_TARGET_MULTICAST            1
402 #define HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET        2
403
404 struct hv_device_interrupt_target {
405         u32     vector;
406         u32     flags;
407         union {
408                 u64              vp_mask;
409                 struct hv_vp_set vp_set;
410         };
411 };
412
413 struct retarget_msi_interrupt {
414         u64     partition_id;           /* use "self" */
415         u64     device_id;
416         struct hv_interrupt_entry int_entry;
417         u64     reserved2;
418         struct hv_device_interrupt_target int_target;
419 } __packed;
420
421 /*
422  * Driver specific state.
423  */
424
425 enum hv_pcibus_state {
426         hv_pcibus_init = 0,
427         hv_pcibus_probed,
428         hv_pcibus_installed,
429         hv_pcibus_removed,
430         hv_pcibus_maximum
431 };
432
433 struct hv_pcibus_device {
434         struct pci_sysdata sysdata;
435         enum hv_pcibus_state state;
436         atomic_t remove_lock;
437         struct hv_device *hdev;
438         resource_size_t low_mmio_space;
439         resource_size_t high_mmio_space;
440         struct resource *mem_config;
441         struct resource *low_mmio_res;
442         struct resource *high_mmio_res;
443         struct completion *survey_event;
444         struct completion remove_event;
445         struct pci_bus *pci_bus;
446         spinlock_t config_lock; /* Avoid two threads writing index page */
447         spinlock_t device_list_lock;    /* Protect lists below */
448         void __iomem *cfg_addr;
449
450         struct semaphore enum_sem;
451         struct list_head resources_for_children;
452
453         struct list_head children;
454         struct list_head dr_list;
455
456         struct msi_domain_info msi_info;
457         struct msi_controller msi_chip;
458         struct irq_domain *irq_domain;
459
460         /* hypercall arg, must not cross page boundary */
461         struct retarget_msi_interrupt retarget_msi_interrupt_params;
462
463         spinlock_t retarget_msi_interrupt_lock;
464 };
465
466 /*
467  * Tracks "Device Relations" messages from the host, which must be both
468  * processed in order and deferred so that they don't run in the context
469  * of the incoming packet callback.
470  */
471 struct hv_dr_work {
472         struct work_struct wrk;
473         struct hv_pcibus_device *bus;
474 };
475
476 struct hv_dr_state {
477         struct list_head list_entry;
478         u32 device_count;
479         struct pci_function_description func[0];
480 };
481
482 enum hv_pcichild_state {
483         hv_pcichild_init = 0,
484         hv_pcichild_requirements,
485         hv_pcichild_resourced,
486         hv_pcichild_ejecting,
487         hv_pcichild_maximum
488 };
489
490 enum hv_pcidev_ref_reason {
491         hv_pcidev_ref_invalid = 0,
492         hv_pcidev_ref_initial,
493         hv_pcidev_ref_by_slot,
494         hv_pcidev_ref_packet,
495         hv_pcidev_ref_pnp,
496         hv_pcidev_ref_childlist,
497         hv_pcidev_irqdata,
498         hv_pcidev_ref_max
499 };
500
501 struct hv_pci_dev {
502         /* List protected by pci_rescan_remove_lock */
503         struct list_head list_entry;
504         refcount_t refs;
505         enum hv_pcichild_state state;
506         struct pci_function_description desc;
507         bool reported_missing;
508         struct hv_pcibus_device *hbus;
509         struct work_struct wrk;
510
511         /*
512          * What would be observed if one wrote 0xFFFFFFFF to a BAR and then
513          * read it back, for each of the BAR offsets within config space.
514          */
515         u32 probed_bar[6];
516 };
517
518 struct hv_pci_compl {
519         struct completion host_event;
520         s32 completion_status;
521 };
522
523 /**
524  * hv_pci_generic_compl() - Invoked for a completion packet
525  * @context:            Set up by the sender of the packet.
526  * @resp:               The response packet
527  * @resp_packet_size:   Size in bytes of the packet
528  *
529  * This function is used to trigger an event and report status
530  * for any message for which the completion packet contains a
531  * status and nothing else.
532  */
533 static void hv_pci_generic_compl(void *context, struct pci_response *resp,
534                                  int resp_packet_size)
535 {
536         struct hv_pci_compl *comp_pkt = context;
537
538         if (resp_packet_size >= offsetofend(struct pci_response, status))
539                 comp_pkt->completion_status = resp->status;
540         else
541                 comp_pkt->completion_status = -1;
542
543         complete(&comp_pkt->host_event);
544 }
545
546 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
547                                                 u32 wslot);
548 static void get_pcichild(struct hv_pci_dev *hv_pcidev,
549                          enum hv_pcidev_ref_reason reason);
550 static void put_pcichild(struct hv_pci_dev *hv_pcidev,
551                          enum hv_pcidev_ref_reason reason);
552
553 static void get_hvpcibus(struct hv_pcibus_device *hv_pcibus);
554 static void put_hvpcibus(struct hv_pcibus_device *hv_pcibus);
555
556 /**
557  * devfn_to_wslot() - Convert from Linux PCI slot to Windows
558  * @devfn:      The Linux representation of PCI slot
559  *
560  * Windows uses a slightly different representation of PCI slot.
561  *
562  * Return: The Windows representation
563  */
564 static u32 devfn_to_wslot(int devfn)
565 {
566         union win_slot_encoding wslot;
567
568         wslot.slot = 0;
569         wslot.bits.dev = PCI_SLOT(devfn);
570         wslot.bits.func = PCI_FUNC(devfn);
571
572         return wslot.slot;
573 }
574
575 /**
576  * wslot_to_devfn() - Convert from Windows PCI slot to Linux
577  * @wslot:      The Windows representation of PCI slot
578  *
579  * Windows uses a slightly different representation of PCI slot.
580  *
581  * Return: The Linux representation
582  */
583 static int wslot_to_devfn(u32 wslot)
584 {
585         union win_slot_encoding slot_no;
586
587         slot_no.slot = wslot;
588         return PCI_DEVFN(slot_no.bits.dev, slot_no.bits.func);
589 }
590
591 /*
592  * PCI Configuration Space for these root PCI buses is implemented as a pair
593  * of pages in memory-mapped I/O space.  Writing to the first page chooses
594  * the PCI function being written or read.  Once the first page has been
595  * written to, the following page maps in the entire configuration space of
596  * the function.
597  */
598
599 /**
600  * _hv_pcifront_read_config() - Internal PCI config read
601  * @hpdev:      The PCI driver's representation of the device
602  * @where:      Offset within config space
603  * @size:       Size of the transfer
604  * @val:        Pointer to the buffer receiving the data
605  */
606 static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where,
607                                      int size, u32 *val)
608 {
609         unsigned long flags;
610         void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
611
612         /*
613          * If the attempt is to read the IDs or the ROM BAR, simulate that.
614          */
615         if (where + size <= PCI_COMMAND) {
616                 memcpy(val, ((u8 *)&hpdev->desc.v_id) + where, size);
617         } else if (where >= PCI_CLASS_REVISION && where + size <=
618                    PCI_CACHE_LINE_SIZE) {
619                 memcpy(val, ((u8 *)&hpdev->desc.rev) + where -
620                        PCI_CLASS_REVISION, size);
621         } else if (where >= PCI_SUBSYSTEM_VENDOR_ID && where + size <=
622                    PCI_ROM_ADDRESS) {
623                 memcpy(val, (u8 *)&hpdev->desc.subsystem_id + where -
624                        PCI_SUBSYSTEM_VENDOR_ID, size);
625         } else if (where >= PCI_ROM_ADDRESS && where + size <=
626                    PCI_CAPABILITY_LIST) {
627                 /* ROM BARs are unimplemented */
628                 *val = 0;
629         } else if (where >= PCI_INTERRUPT_LINE && where + size <=
630                    PCI_INTERRUPT_PIN) {
631                 /*
632                  * Interrupt Line and Interrupt PIN are hard-wired to zero
633                  * because this front-end only supports message-signaled
634                  * interrupts.
635                  */
636                 *val = 0;
637         } else if (where + size <= CFG_PAGE_SIZE) {
638                 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
639                 /* Choose the function to be read. (See comment above) */
640                 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
641                 /* Make sure the function was chosen before we start reading. */
642                 mb();
643                 /* Read from that function's config space. */
644                 switch (size) {
645                 case 1:
646                         *val = readb(addr);
647                         break;
648                 case 2:
649                         *val = readw(addr);
650                         break;
651                 default:
652                         *val = readl(addr);
653                         break;
654                 }
655                 /*
656                  * Make sure the write was done before we release the spinlock
657                  * allowing consecutive reads/writes.
658                  */
659                 mb();
660                 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
661         } else {
662                 dev_err(&hpdev->hbus->hdev->device,
663                         "Attempt to read beyond a function's config space.\n");
664         }
665 }
666
667 /**
668  * _hv_pcifront_write_config() - Internal PCI config write
669  * @hpdev:      The PCI driver's representation of the device
670  * @where:      Offset within config space
671  * @size:       Size of the transfer
672  * @val:        The data being transferred
673  */
674 static void _hv_pcifront_write_config(struct hv_pci_dev *hpdev, int where,
675                                       int size, u32 val)
676 {
677         unsigned long flags;
678         void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
679
680         if (where >= PCI_SUBSYSTEM_VENDOR_ID &&
681             where + size <= PCI_CAPABILITY_LIST) {
682                 /* SSIDs and ROM BARs are read-only */
683         } else if (where >= PCI_COMMAND && where + size <= CFG_PAGE_SIZE) {
684                 spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
685                 /* Choose the function to be written. (See comment above) */
686                 writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
687                 /* Make sure the function was chosen before we start writing. */
688                 wmb();
689                 /* Write to that function's config space. */
690                 switch (size) {
691                 case 1:
692                         writeb(val, addr);
693                         break;
694                 case 2:
695                         writew(val, addr);
696                         break;
697                 default:
698                         writel(val, addr);
699                         break;
700                 }
701                 /*
702                  * Make sure the write was done before we release the spinlock
703                  * allowing consecutive reads/writes.
704                  */
705                 mb();
706                 spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
707         } else {
708                 dev_err(&hpdev->hbus->hdev->device,
709                         "Attempt to write beyond a function's config space.\n");
710         }
711 }
712
713 /**
714  * hv_pcifront_read_config() - Read configuration space
715  * @bus: PCI Bus structure
716  * @devfn: Device/function
717  * @where: Offset from base
718  * @size: Byte/word/dword
719  * @val: Value to be read
720  *
721  * Return: PCIBIOS_SUCCESSFUL on success
722  *         PCIBIOS_DEVICE_NOT_FOUND on failure
723  */
724 static int hv_pcifront_read_config(struct pci_bus *bus, unsigned int devfn,
725                                    int where, int size, u32 *val)
726 {
727         struct hv_pcibus_device *hbus =
728                 container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
729         struct hv_pci_dev *hpdev;
730
731         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
732         if (!hpdev)
733                 return PCIBIOS_DEVICE_NOT_FOUND;
734
735         _hv_pcifront_read_config(hpdev, where, size, val);
736
737         put_pcichild(hpdev, hv_pcidev_ref_by_slot);
738         return PCIBIOS_SUCCESSFUL;
739 }
740
741 /**
742  * hv_pcifront_write_config() - Write configuration space
743  * @bus: PCI Bus structure
744  * @devfn: Device/function
745  * @where: Offset from base
746  * @size: Byte/word/dword
747  * @val: Value to be written to device
748  *
749  * Return: PCIBIOS_SUCCESSFUL on success
750  *         PCIBIOS_DEVICE_NOT_FOUND on failure
751  */
752 static int hv_pcifront_write_config(struct pci_bus *bus, unsigned int devfn,
753                                     int where, int size, u32 val)
754 {
755         struct hv_pcibus_device *hbus =
756             container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
757         struct hv_pci_dev *hpdev;
758
759         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
760         if (!hpdev)
761                 return PCIBIOS_DEVICE_NOT_FOUND;
762
763         _hv_pcifront_write_config(hpdev, where, size, val);
764
765         put_pcichild(hpdev, hv_pcidev_ref_by_slot);
766         return PCIBIOS_SUCCESSFUL;
767 }
768
769 /* PCIe operations */
770 static struct pci_ops hv_pcifront_ops = {
771         .read  = hv_pcifront_read_config,
772         .write = hv_pcifront_write_config,
773 };
774
775 /* Interrupt management hooks */
776 static void hv_int_desc_free(struct hv_pci_dev *hpdev,
777                              struct tran_int_desc *int_desc)
778 {
779         struct pci_delete_interrupt *int_pkt;
780         struct {
781                 struct pci_packet pkt;
782                 u8 buffer[sizeof(struct pci_delete_interrupt)];
783         } ctxt;
784
785         memset(&ctxt, 0, sizeof(ctxt));
786         int_pkt = (struct pci_delete_interrupt *)&ctxt.pkt.message;
787         int_pkt->message_type.type =
788                 PCI_DELETE_INTERRUPT_MESSAGE;
789         int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
790         int_pkt->int_desc = *int_desc;
791         vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt, sizeof(*int_pkt),
792                          (unsigned long)&ctxt.pkt, VM_PKT_DATA_INBAND, 0);
793         kfree(int_desc);
794 }
795
796 /**
797  * hv_msi_free() - Free the MSI.
798  * @domain:     The interrupt domain pointer
799  * @info:       Extra MSI-related context
800  * @irq:        Identifies the IRQ.
801  *
802  * The Hyper-V parent partition and hypervisor are tracking the
803  * messages that are in use, keeping the interrupt redirection
804  * table up to date.  This callback sends a message that frees
805  * the IRT entry and related tracking nonsense.
806  */
807 static void hv_msi_free(struct irq_domain *domain, struct msi_domain_info *info,
808                         unsigned int irq)
809 {
810         struct hv_pcibus_device *hbus;
811         struct hv_pci_dev *hpdev;
812         struct pci_dev *pdev;
813         struct tran_int_desc *int_desc;
814         struct irq_data *irq_data = irq_domain_get_irq_data(domain, irq);
815         struct msi_desc *msi = irq_data_get_msi_desc(irq_data);
816
817         pdev = msi_desc_to_pci_dev(msi);
818         hbus = info->data;
819         int_desc = irq_data_get_irq_chip_data(irq_data);
820         if (!int_desc)
821                 return;
822
823         irq_data->chip_data = NULL;
824         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
825         if (!hpdev) {
826                 kfree(int_desc);
827                 return;
828         }
829
830         hv_int_desc_free(hpdev, int_desc);
831         put_pcichild(hpdev, hv_pcidev_ref_by_slot);
832 }
833
834 static int hv_set_affinity(struct irq_data *data, const struct cpumask *dest,
835                            bool force)
836 {
837         struct irq_data *parent = data->parent_data;
838
839         return parent->chip->irq_set_affinity(parent, dest, force);
840 }
841
842 static void hv_irq_mask(struct irq_data *data)
843 {
844         pci_msi_mask_irq(data);
845 }
846
847 /**
848  * hv_irq_unmask() - "Unmask" the IRQ by setting its current
849  * affinity.
850  * @data:       Describes the IRQ
851  *
852  * Build new a destination for the MSI and make a hypercall to
853  * update the Interrupt Redirection Table. "Device Logical ID"
854  * is built out of this PCI bus's instance GUID and the function
855  * number of the device.
856  */
857 static void hv_irq_unmask(struct irq_data *data)
858 {
859         struct msi_desc *msi_desc = irq_data_get_msi_desc(data);
860         struct irq_cfg *cfg = irqd_cfg(data);
861         struct retarget_msi_interrupt *params;
862         struct hv_pcibus_device *hbus;
863         struct cpumask *dest;
864         struct pci_bus *pbus;
865         struct pci_dev *pdev;
866         unsigned long flags;
867         u32 var_size = 0;
868         int cpu_vmbus;
869         int cpu;
870         u64 res;
871
872         dest = irq_data_get_effective_affinity_mask(data);
873         pdev = msi_desc_to_pci_dev(msi_desc);
874         pbus = pdev->bus;
875         hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
876
877         spin_lock_irqsave(&hbus->retarget_msi_interrupt_lock, flags);
878
879         params = &hbus->retarget_msi_interrupt_params;
880         memset(params, 0, sizeof(*params));
881         params->partition_id = HV_PARTITION_ID_SELF;
882         params->int_entry.source = 1; /* MSI(-X) */
883         params->int_entry.address = msi_desc->msg.address_lo;
884         params->int_entry.data = msi_desc->msg.data;
885         params->device_id = (hbus->hdev->dev_instance.b[5] << 24) |
886                            (hbus->hdev->dev_instance.b[4] << 16) |
887                            (hbus->hdev->dev_instance.b[7] << 8) |
888                            (hbus->hdev->dev_instance.b[6] & 0xf8) |
889                            PCI_FUNC(pdev->devfn);
890         params->int_target.vector = cfg->vector;
891
892         /*
893          * Honoring apic->irq_delivery_mode set to dest_Fixed by
894          * setting the HV_DEVICE_INTERRUPT_TARGET_MULTICAST flag results in a
895          * spurious interrupt storm. Not doing so does not seem to have a
896          * negative effect (yet?).
897          */
898
899         if (pci_protocol_version >= PCI_PROTOCOL_VERSION_1_2) {
900                 /*
901                  * PCI_PROTOCOL_VERSION_1_2 supports the VP_SET version of the
902                  * HVCALL_RETARGET_INTERRUPT hypercall, which also coincides
903                  * with >64 VP support.
904                  * ms_hyperv.hints & HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED
905                  * is not sufficient for this hypercall.
906                  */
907                 params->int_target.flags |=
908                         HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET;
909                 params->int_target.vp_set.valid_banks =
910                         (1ull << HV_VP_SET_BANK_COUNT_MAX) - 1;
911
912                 /*
913                  * var-sized hypercall, var-size starts after vp_mask (thus
914                  * vp_set.format does not count, but vp_set.valid_banks does).
915                  */
916                 var_size = 1 + HV_VP_SET_BANK_COUNT_MAX;
917
918                 for_each_cpu_and(cpu, dest, cpu_online_mask) {
919                         cpu_vmbus = hv_cpu_number_to_vp_number(cpu);
920
921                         if (cpu_vmbus >= HV_VP_SET_BANK_COUNT_MAX * 64) {
922                                 dev_err(&hbus->hdev->device,
923                                         "too high CPU %d", cpu_vmbus);
924                                 res = 1;
925                                 goto exit_unlock;
926                         }
927
928                         params->int_target.vp_set.masks[cpu_vmbus / 64] |=
929                                 (1ULL << (cpu_vmbus & 63));
930                 }
931         } else {
932                 for_each_cpu_and(cpu, dest, cpu_online_mask) {
933                         params->int_target.vp_mask |=
934                                 (1ULL << hv_cpu_number_to_vp_number(cpu));
935                 }
936         }
937
938         res = hv_do_hypercall(HVCALL_RETARGET_INTERRUPT | (var_size << 17),
939                               params, NULL);
940
941 exit_unlock:
942         spin_unlock_irqrestore(&hbus->retarget_msi_interrupt_lock, flags);
943
944         if (res) {
945                 dev_err(&hbus->hdev->device,
946                         "%s() failed: %#llx", __func__, res);
947                 return;
948         }
949
950         pci_msi_unmask_irq(data);
951 }
952
953 struct compose_comp_ctxt {
954         struct hv_pci_compl comp_pkt;
955         struct tran_int_desc int_desc;
956 };
957
958 static void hv_pci_compose_compl(void *context, struct pci_response *resp,
959                                  int resp_packet_size)
960 {
961         struct compose_comp_ctxt *comp_pkt = context;
962         struct pci_create_int_response *int_resp =
963                 (struct pci_create_int_response *)resp;
964
965         comp_pkt->comp_pkt.completion_status = resp->status;
966         comp_pkt->int_desc = int_resp->int_desc;
967         complete(&comp_pkt->comp_pkt.host_event);
968 }
969
970 static u32 hv_compose_msi_req_v1(
971         struct pci_create_interrupt *int_pkt, struct cpumask *affinity,
972         u32 slot, u8 vector)
973 {
974         int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE;
975         int_pkt->wslot.slot = slot;
976         int_pkt->int_desc.vector = vector;
977         int_pkt->int_desc.vector_count = 1;
978         int_pkt->int_desc.delivery_mode = dest_Fixed;
979
980         /*
981          * Create MSI w/ dummy vCPU set, overwritten by subsequent retarget in
982          * hv_irq_unmask().
983          */
984         int_pkt->int_desc.cpu_mask = CPU_AFFINITY_ALL;
985
986         return sizeof(*int_pkt);
987 }
988
989 static u32 hv_compose_msi_req_v2(
990         struct pci_create_interrupt2 *int_pkt, struct cpumask *affinity,
991         u32 slot, u8 vector)
992 {
993         int cpu;
994
995         int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE2;
996         int_pkt->wslot.slot = slot;
997         int_pkt->int_desc.vector = vector;
998         int_pkt->int_desc.vector_count = 1;
999         int_pkt->int_desc.delivery_mode = dest_Fixed;
1000
1001         /*
1002          * Create MSI w/ dummy vCPU set targeting just one vCPU, overwritten
1003          * by subsequent retarget in hv_irq_unmask().
1004          */
1005         cpu = cpumask_first_and(affinity, cpu_online_mask);
1006         int_pkt->int_desc.processor_array[0] =
1007                 hv_cpu_number_to_vp_number(cpu);
1008         int_pkt->int_desc.processor_count = 1;
1009
1010         return sizeof(*int_pkt);
1011 }
1012
1013 /**
1014  * hv_compose_msi_msg() - Supplies a valid MSI address/data
1015  * @data:       Everything about this MSI
1016  * @msg:        Buffer that is filled in by this function
1017  *
1018  * This function unpacks the IRQ looking for target CPU set, IDT
1019  * vector and mode and sends a message to the parent partition
1020  * asking for a mapping for that tuple in this partition.  The
1021  * response supplies a data value and address to which that data
1022  * should be written to trigger that interrupt.
1023  */
1024 static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
1025 {
1026         struct irq_cfg *cfg = irqd_cfg(data);
1027         struct hv_pcibus_device *hbus;
1028         struct hv_pci_dev *hpdev;
1029         struct pci_bus *pbus;
1030         struct pci_dev *pdev;
1031         struct cpumask *dest;
1032         struct compose_comp_ctxt comp;
1033         struct tran_int_desc *int_desc;
1034         struct {
1035                 struct pci_packet pci_pkt;
1036                 union {
1037                         struct pci_create_interrupt v1;
1038                         struct pci_create_interrupt2 v2;
1039                 } int_pkts;
1040         } __packed ctxt;
1041
1042         u32 size;
1043         int ret;
1044
1045         pdev = msi_desc_to_pci_dev(irq_data_get_msi_desc(data));
1046         dest = irq_data_get_effective_affinity_mask(data);
1047         pbus = pdev->bus;
1048         hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
1049         hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1050         if (!hpdev)
1051                 goto return_null_message;
1052
1053         /* Free any previous message that might have already been composed. */
1054         if (data->chip_data) {
1055                 int_desc = data->chip_data;
1056                 data->chip_data = NULL;
1057                 hv_int_desc_free(hpdev, int_desc);
1058         }
1059
1060         int_desc = kzalloc(sizeof(*int_desc), GFP_ATOMIC);
1061         if (!int_desc)
1062                 goto drop_reference;
1063
1064         memset(&ctxt, 0, sizeof(ctxt));
1065         init_completion(&comp.comp_pkt.host_event);
1066         ctxt.pci_pkt.completion_func = hv_pci_compose_compl;
1067         ctxt.pci_pkt.compl_ctxt = &comp;
1068
1069         switch (pci_protocol_version) {
1070         case PCI_PROTOCOL_VERSION_1_1:
1071                 size = hv_compose_msi_req_v1(&ctxt.int_pkts.v1,
1072                                         dest,
1073                                         hpdev->desc.win_slot.slot,
1074                                         cfg->vector);
1075                 break;
1076
1077         case PCI_PROTOCOL_VERSION_1_2:
1078                 size = hv_compose_msi_req_v2(&ctxt.int_pkts.v2,
1079                                         dest,
1080                                         hpdev->desc.win_slot.slot,
1081                                         cfg->vector);
1082                 break;
1083
1084         default:
1085                 /* As we only negotiate protocol versions known to this driver,
1086                  * this path should never hit. However, this is it not a hot
1087                  * path so we print a message to aid future updates.
1088                  */
1089                 dev_err(&hbus->hdev->device,
1090                         "Unexpected vPCI protocol, update driver.");
1091                 goto free_int_desc;
1092         }
1093
1094         ret = vmbus_sendpacket(hpdev->hbus->hdev->channel, &ctxt.int_pkts,
1095                                size, (unsigned long)&ctxt.pci_pkt,
1096                                VM_PKT_DATA_INBAND,
1097                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1098         if (ret) {
1099                 dev_err(&hbus->hdev->device,
1100                         "Sending request for interrupt failed: 0x%x",
1101                         comp.comp_pkt.completion_status);
1102                 goto free_int_desc;
1103         }
1104
1105         /*
1106          * Since this function is called with IRQ locks held, can't
1107          * do normal wait for completion; instead poll.
1108          */
1109         while (!try_wait_for_completion(&comp.comp_pkt.host_event))
1110                 udelay(100);
1111
1112         if (comp.comp_pkt.completion_status < 0) {
1113                 dev_err(&hbus->hdev->device,
1114                         "Request for interrupt failed: 0x%x",
1115                         comp.comp_pkt.completion_status);
1116                 goto free_int_desc;
1117         }
1118
1119         /*
1120          * Record the assignment so that this can be unwound later. Using
1121          * irq_set_chip_data() here would be appropriate, but the lock it takes
1122          * is already held.
1123          */
1124         *int_desc = comp.int_desc;
1125         data->chip_data = int_desc;
1126
1127         /* Pass up the result. */
1128         msg->address_hi = comp.int_desc.address >> 32;
1129         msg->address_lo = comp.int_desc.address & 0xffffffff;
1130         msg->data = comp.int_desc.data;
1131
1132         put_pcichild(hpdev, hv_pcidev_ref_by_slot);
1133         return;
1134
1135 free_int_desc:
1136         kfree(int_desc);
1137 drop_reference:
1138         put_pcichild(hpdev, hv_pcidev_ref_by_slot);
1139 return_null_message:
1140         msg->address_hi = 0;
1141         msg->address_lo = 0;
1142         msg->data = 0;
1143 }
1144
1145 /* HW Interrupt Chip Descriptor */
1146 static struct irq_chip hv_msi_irq_chip = {
1147         .name                   = "Hyper-V PCIe MSI",
1148         .irq_compose_msi_msg    = hv_compose_msi_msg,
1149         .irq_set_affinity       = hv_set_affinity,
1150         .irq_ack                = irq_chip_ack_parent,
1151         .irq_mask               = hv_irq_mask,
1152         .irq_unmask             = hv_irq_unmask,
1153 };
1154
1155 static irq_hw_number_t hv_msi_domain_ops_get_hwirq(struct msi_domain_info *info,
1156                                                    msi_alloc_info_t *arg)
1157 {
1158         return arg->msi_hwirq;
1159 }
1160
1161 static struct msi_domain_ops hv_msi_ops = {
1162         .get_hwirq      = hv_msi_domain_ops_get_hwirq,
1163         .msi_prepare    = pci_msi_prepare,
1164         .set_desc       = pci_msi_set_desc,
1165         .msi_free       = hv_msi_free,
1166 };
1167
1168 /**
1169  * hv_pcie_init_irq_domain() - Initialize IRQ domain
1170  * @hbus:       The root PCI bus
1171  *
1172  * This function creates an IRQ domain which will be used for
1173  * interrupts from devices that have been passed through.  These
1174  * devices only support MSI and MSI-X, not line-based interrupts
1175  * or simulations of line-based interrupts through PCIe's
1176  * fabric-layer messages.  Because interrupts are remapped, we
1177  * can support multi-message MSI here.
1178  *
1179  * Return: '0' on success and error value on failure
1180  */
1181 static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus)
1182 {
1183         hbus->msi_info.chip = &hv_msi_irq_chip;
1184         hbus->msi_info.ops = &hv_msi_ops;
1185         hbus->msi_info.flags = (MSI_FLAG_USE_DEF_DOM_OPS |
1186                 MSI_FLAG_USE_DEF_CHIP_OPS | MSI_FLAG_MULTI_PCI_MSI |
1187                 MSI_FLAG_PCI_MSIX);
1188         hbus->msi_info.handler = handle_edge_irq;
1189         hbus->msi_info.handler_name = "edge";
1190         hbus->msi_info.data = hbus;
1191         hbus->irq_domain = pci_msi_create_irq_domain(hbus->sysdata.fwnode,
1192                                                      &hbus->msi_info,
1193                                                      x86_vector_domain);
1194         if (!hbus->irq_domain) {
1195                 dev_err(&hbus->hdev->device,
1196                         "Failed to build an MSI IRQ domain\n");
1197                 return -ENODEV;
1198         }
1199
1200         return 0;
1201 }
1202
1203 /**
1204  * get_bar_size() - Get the address space consumed by a BAR
1205  * @bar_val:    Value that a BAR returned after -1 was written
1206  *              to it.
1207  *
1208  * This function returns the size of the BAR, rounded up to 1
1209  * page.  It has to be rounded up because the hypervisor's page
1210  * table entry that maps the BAR into the VM can't specify an
1211  * offset within a page.  The invariant is that the hypervisor
1212  * must place any BARs of smaller than page length at the
1213  * beginning of a page.
1214  *
1215  * Return:      Size in bytes of the consumed MMIO space.
1216  */
1217 static u64 get_bar_size(u64 bar_val)
1218 {
1219         return round_up((1 + ~(bar_val & PCI_BASE_ADDRESS_MEM_MASK)),
1220                         PAGE_SIZE);
1221 }
1222
1223 /**
1224  * survey_child_resources() - Total all MMIO requirements
1225  * @hbus:       Root PCI bus, as understood by this driver
1226  */
1227 static void survey_child_resources(struct hv_pcibus_device *hbus)
1228 {
1229         struct list_head *iter;
1230         struct hv_pci_dev *hpdev;
1231         resource_size_t bar_size = 0;
1232         unsigned long flags;
1233         struct completion *event;
1234         u64 bar_val;
1235         int i;
1236
1237         /* If nobody is waiting on the answer, don't compute it. */
1238         event = xchg(&hbus->survey_event, NULL);
1239         if (!event)
1240                 return;
1241
1242         /* If the answer has already been computed, go with it. */
1243         if (hbus->low_mmio_space || hbus->high_mmio_space) {
1244                 complete(event);
1245                 return;
1246         }
1247
1248         spin_lock_irqsave(&hbus->device_list_lock, flags);
1249
1250         /*
1251          * Due to an interesting quirk of the PCI spec, all memory regions
1252          * for a child device are a power of 2 in size and aligned in memory,
1253          * so it's sufficient to just add them up without tracking alignment.
1254          */
1255         list_for_each(iter, &hbus->children) {
1256                 hpdev = container_of(iter, struct hv_pci_dev, list_entry);
1257                 for (i = 0; i < 6; i++) {
1258                         if (hpdev->probed_bar[i] & PCI_BASE_ADDRESS_SPACE_IO)
1259                                 dev_err(&hbus->hdev->device,
1260                                         "There's an I/O BAR in this list!\n");
1261
1262                         if (hpdev->probed_bar[i] != 0) {
1263                                 /*
1264                                  * A probed BAR has all the upper bits set that
1265                                  * can be changed.
1266                                  */
1267
1268                                 bar_val = hpdev->probed_bar[i];
1269                                 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1270                                         bar_val |=
1271                                         ((u64)hpdev->probed_bar[++i] << 32);
1272                                 else
1273                                         bar_val |= 0xffffffff00000000ULL;
1274
1275                                 bar_size = get_bar_size(bar_val);
1276
1277                                 if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1278                                         hbus->high_mmio_space += bar_size;
1279                                 else
1280                                         hbus->low_mmio_space += bar_size;
1281                         }
1282                 }
1283         }
1284
1285         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1286         complete(event);
1287 }
1288
1289 /**
1290  * prepopulate_bars() - Fill in BARs with defaults
1291  * @hbus:       Root PCI bus, as understood by this driver
1292  *
1293  * The core PCI driver code seems much, much happier if the BARs
1294  * for a device have values upon first scan. So fill them in.
1295  * The algorithm below works down from large sizes to small,
1296  * attempting to pack the assignments optimally. The assumption,
1297  * enforced in other parts of the code, is that the beginning of
1298  * the memory-mapped I/O space will be aligned on the largest
1299  * BAR size.
1300  */
1301 static void prepopulate_bars(struct hv_pcibus_device *hbus)
1302 {
1303         resource_size_t high_size = 0;
1304         resource_size_t low_size = 0;
1305         resource_size_t high_base = 0;
1306         resource_size_t low_base = 0;
1307         resource_size_t bar_size;
1308         struct hv_pci_dev *hpdev;
1309         struct list_head *iter;
1310         unsigned long flags;
1311         u64 bar_val;
1312         u32 command;
1313         bool high;
1314         int i;
1315
1316         if (hbus->low_mmio_space) {
1317                 low_size = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
1318                 low_base = hbus->low_mmio_res->start;
1319         }
1320
1321         if (hbus->high_mmio_space) {
1322                 high_size = 1ULL <<
1323                         (63 - __builtin_clzll(hbus->high_mmio_space));
1324                 high_base = hbus->high_mmio_res->start;
1325         }
1326
1327         spin_lock_irqsave(&hbus->device_list_lock, flags);
1328
1329         /* Pick addresses for the BARs. */
1330         do {
1331                 list_for_each(iter, &hbus->children) {
1332                         hpdev = container_of(iter, struct hv_pci_dev,
1333                                              list_entry);
1334                         for (i = 0; i < 6; i++) {
1335                                 bar_val = hpdev->probed_bar[i];
1336                                 if (bar_val == 0)
1337                                         continue;
1338                                 high = bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64;
1339                                 if (high) {
1340                                         bar_val |=
1341                                                 ((u64)hpdev->probed_bar[i + 1]
1342                                                  << 32);
1343                                 } else {
1344                                         bar_val |= 0xffffffffULL << 32;
1345                                 }
1346                                 bar_size = get_bar_size(bar_val);
1347                                 if (high) {
1348                                         if (high_size != bar_size) {
1349                                                 i++;
1350                                                 continue;
1351                                         }
1352                                         _hv_pcifront_write_config(hpdev,
1353                                                 PCI_BASE_ADDRESS_0 + (4 * i),
1354                                                 4,
1355                                                 (u32)(high_base & 0xffffff00));
1356                                         i++;
1357                                         _hv_pcifront_write_config(hpdev,
1358                                                 PCI_BASE_ADDRESS_0 + (4 * i),
1359                                                 4, (u32)(high_base >> 32));
1360                                         high_base += bar_size;
1361                                 } else {
1362                                         if (low_size != bar_size)
1363                                                 continue;
1364                                         _hv_pcifront_write_config(hpdev,
1365                                                 PCI_BASE_ADDRESS_0 + (4 * i),
1366                                                 4,
1367                                                 (u32)(low_base & 0xffffff00));
1368                                         low_base += bar_size;
1369                                 }
1370                         }
1371                         if (high_size <= 1 && low_size <= 1) {
1372                                 /* Set the memory enable bit. */
1373                                 _hv_pcifront_read_config(hpdev, PCI_COMMAND, 2,
1374                                                          &command);
1375                                 command |= PCI_COMMAND_MEMORY;
1376                                 _hv_pcifront_write_config(hpdev, PCI_COMMAND, 2,
1377                                                           command);
1378                                 break;
1379                         }
1380                 }
1381
1382                 high_size >>= 1;
1383                 low_size >>= 1;
1384         }  while (high_size || low_size);
1385
1386         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1387 }
1388
1389 /**
1390  * create_root_hv_pci_bus() - Expose a new root PCI bus
1391  * @hbus:       Root PCI bus, as understood by this driver
1392  *
1393  * Return: 0 on success, -errno on failure
1394  */
1395 static int create_root_hv_pci_bus(struct hv_pcibus_device *hbus)
1396 {
1397         /* Register the device */
1398         hbus->pci_bus = pci_create_root_bus(&hbus->hdev->device,
1399                                             0, /* bus number is always zero */
1400                                             &hv_pcifront_ops,
1401                                             &hbus->sysdata,
1402                                             &hbus->resources_for_children);
1403         if (!hbus->pci_bus)
1404                 return -ENODEV;
1405
1406         hbus->pci_bus->msi = &hbus->msi_chip;
1407         hbus->pci_bus->msi->dev = &hbus->hdev->device;
1408
1409         pci_lock_rescan_remove();
1410         pci_scan_child_bus(hbus->pci_bus);
1411         pci_bus_assign_resources(hbus->pci_bus);
1412         pci_bus_add_devices(hbus->pci_bus);
1413         pci_unlock_rescan_remove();
1414         hbus->state = hv_pcibus_installed;
1415         return 0;
1416 }
1417
1418 struct q_res_req_compl {
1419         struct completion host_event;
1420         struct hv_pci_dev *hpdev;
1421 };
1422
1423 /**
1424  * q_resource_requirements() - Query Resource Requirements
1425  * @context:            The completion context.
1426  * @resp:               The response that came from the host.
1427  * @resp_packet_size:   The size in bytes of resp.
1428  *
1429  * This function is invoked on completion of a Query Resource
1430  * Requirements packet.
1431  */
1432 static void q_resource_requirements(void *context, struct pci_response *resp,
1433                                     int resp_packet_size)
1434 {
1435         struct q_res_req_compl *completion = context;
1436         struct pci_q_res_req_response *q_res_req =
1437                 (struct pci_q_res_req_response *)resp;
1438         int i;
1439
1440         if (resp->status < 0) {
1441                 dev_err(&completion->hpdev->hbus->hdev->device,
1442                         "query resource requirements failed: %x\n",
1443                         resp->status);
1444         } else {
1445                 for (i = 0; i < 6; i++) {
1446                         completion->hpdev->probed_bar[i] =
1447                                 q_res_req->probed_bar[i];
1448                 }
1449         }
1450
1451         complete(&completion->host_event);
1452 }
1453
1454 static void get_pcichild(struct hv_pci_dev *hpdev,
1455                             enum hv_pcidev_ref_reason reason)
1456 {
1457         refcount_inc(&hpdev->refs);
1458 }
1459
1460 static void put_pcichild(struct hv_pci_dev *hpdev,
1461                             enum hv_pcidev_ref_reason reason)
1462 {
1463         if (refcount_dec_and_test(&hpdev->refs))
1464                 kfree(hpdev);
1465 }
1466
1467 /**
1468  * new_pcichild_device() - Create a new child device
1469  * @hbus:       The internal struct tracking this root PCI bus.
1470  * @desc:       The information supplied so far from the host
1471  *              about the device.
1472  *
1473  * This function creates the tracking structure for a new child
1474  * device and kicks off the process of figuring out what it is.
1475  *
1476  * Return: Pointer to the new tracking struct
1477  */
1478 static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
1479                 struct pci_function_description *desc)
1480 {
1481         struct hv_pci_dev *hpdev;
1482         struct pci_child_message *res_req;
1483         struct q_res_req_compl comp_pkt;
1484         struct {
1485                 struct pci_packet init_packet;
1486                 u8 buffer[sizeof(struct pci_child_message)];
1487         } pkt;
1488         unsigned long flags;
1489         int ret;
1490
1491         hpdev = kzalloc(sizeof(*hpdev), GFP_ATOMIC);
1492         if (!hpdev)
1493                 return NULL;
1494
1495         hpdev->hbus = hbus;
1496
1497         memset(&pkt, 0, sizeof(pkt));
1498         init_completion(&comp_pkt.host_event);
1499         comp_pkt.hpdev = hpdev;
1500         pkt.init_packet.compl_ctxt = &comp_pkt;
1501         pkt.init_packet.completion_func = q_resource_requirements;
1502         res_req = (struct pci_child_message *)&pkt.init_packet.message;
1503         res_req->message_type.type = PCI_QUERY_RESOURCE_REQUIREMENTS;
1504         res_req->wslot.slot = desc->win_slot.slot;
1505
1506         ret = vmbus_sendpacket(hbus->hdev->channel, res_req,
1507                                sizeof(struct pci_child_message),
1508                                (unsigned long)&pkt.init_packet,
1509                                VM_PKT_DATA_INBAND,
1510                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1511         if (ret)
1512                 goto error;
1513
1514         wait_for_completion(&comp_pkt.host_event);
1515
1516         hpdev->desc = *desc;
1517         refcount_set(&hpdev->refs, 1);
1518         get_pcichild(hpdev, hv_pcidev_ref_childlist);
1519         spin_lock_irqsave(&hbus->device_list_lock, flags);
1520
1521         /*
1522          * When a device is being added to the bus, we set the PCI domain
1523          * number to be the device serial number, which is non-zero and
1524          * unique on the same VM.  The serial numbers start with 1, and
1525          * increase by 1 for each device.  So device names including this
1526          * can have shorter names than based on the bus instance UUID.
1527          * Only the first device serial number is used for domain, so the
1528          * domain number will not change after the first device is added.
1529          */
1530         if (list_empty(&hbus->children))
1531                 hbus->sysdata.domain = desc->ser;
1532         list_add_tail(&hpdev->list_entry, &hbus->children);
1533         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1534         return hpdev;
1535
1536 error:
1537         kfree(hpdev);
1538         return NULL;
1539 }
1540
1541 /**
1542  * get_pcichild_wslot() - Find device from slot
1543  * @hbus:       Root PCI bus, as understood by this driver
1544  * @wslot:      Location on the bus
1545  *
1546  * This function looks up a PCI device and returns the internal
1547  * representation of it.  It acquires a reference on it, so that
1548  * the device won't be deleted while somebody is using it.  The
1549  * caller is responsible for calling put_pcichild() to release
1550  * this reference.
1551  *
1552  * Return:      Internal representation of a PCI device
1553  */
1554 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
1555                                              u32 wslot)
1556 {
1557         unsigned long flags;
1558         struct hv_pci_dev *iter, *hpdev = NULL;
1559
1560         spin_lock_irqsave(&hbus->device_list_lock, flags);
1561         list_for_each_entry(iter, &hbus->children, list_entry) {
1562                 if (iter->desc.win_slot.slot == wslot) {
1563                         hpdev = iter;
1564                         get_pcichild(hpdev, hv_pcidev_ref_by_slot);
1565                         break;
1566                 }
1567         }
1568         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1569
1570         return hpdev;
1571 }
1572
1573 /**
1574  * pci_devices_present_work() - Handle new list of child devices
1575  * @work:       Work struct embedded in struct hv_dr_work
1576  *
1577  * "Bus Relations" is the Windows term for "children of this
1578  * bus."  The terminology is preserved here for people trying to
1579  * debug the interaction between Hyper-V and Linux.  This
1580  * function is called when the parent partition reports a list
1581  * of functions that should be observed under this PCI Express
1582  * port (bus).
1583  *
1584  * This function updates the list, and must tolerate being
1585  * called multiple times with the same information.  The typical
1586  * number of child devices is one, with very atypical cases
1587  * involving three or four, so the algorithms used here can be
1588  * simple and inefficient.
1589  *
1590  * It must also treat the omission of a previously observed device as
1591  * notification that the device no longer exists.
1592  *
1593  * Note that this function is a work item, and it may not be
1594  * invoked in the order that it was queued.  Back to back
1595  * updates of the list of present devices may involve queuing
1596  * multiple work items, and this one may run before ones that
1597  * were sent later. As such, this function only does something
1598  * if is the last one in the queue.
1599  */
1600 static void pci_devices_present_work(struct work_struct *work)
1601 {
1602         u32 child_no;
1603         bool found;
1604         struct list_head *iter;
1605         struct pci_function_description *new_desc;
1606         struct hv_pci_dev *hpdev;
1607         struct hv_pcibus_device *hbus;
1608         struct list_head removed;
1609         struct hv_dr_work *dr_wrk;
1610         struct hv_dr_state *dr = NULL;
1611         unsigned long flags;
1612
1613         dr_wrk = container_of(work, struct hv_dr_work, wrk);
1614         hbus = dr_wrk->bus;
1615         kfree(dr_wrk);
1616
1617         INIT_LIST_HEAD(&removed);
1618
1619         if (down_interruptible(&hbus->enum_sem)) {
1620                 put_hvpcibus(hbus);
1621                 return;
1622         }
1623
1624         /* Pull this off the queue and process it if it was the last one. */
1625         spin_lock_irqsave(&hbus->device_list_lock, flags);
1626         while (!list_empty(&hbus->dr_list)) {
1627                 dr = list_first_entry(&hbus->dr_list, struct hv_dr_state,
1628                                       list_entry);
1629                 list_del(&dr->list_entry);
1630
1631                 /* Throw this away if the list still has stuff in it. */
1632                 if (!list_empty(&hbus->dr_list)) {
1633                         kfree(dr);
1634                         continue;
1635                 }
1636         }
1637         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1638
1639         if (!dr) {
1640                 up(&hbus->enum_sem);
1641                 put_hvpcibus(hbus);
1642                 return;
1643         }
1644
1645         /* First, mark all existing children as reported missing. */
1646         spin_lock_irqsave(&hbus->device_list_lock, flags);
1647         list_for_each(iter, &hbus->children) {
1648                         hpdev = container_of(iter, struct hv_pci_dev,
1649                                              list_entry);
1650                         hpdev->reported_missing = true;
1651         }
1652         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1653
1654         /* Next, add back any reported devices. */
1655         for (child_no = 0; child_no < dr->device_count; child_no++) {
1656                 found = false;
1657                 new_desc = &dr->func[child_no];
1658
1659                 spin_lock_irqsave(&hbus->device_list_lock, flags);
1660                 list_for_each(iter, &hbus->children) {
1661                         hpdev = container_of(iter, struct hv_pci_dev,
1662                                              list_entry);
1663                         if ((hpdev->desc.win_slot.slot ==
1664                              new_desc->win_slot.slot) &&
1665                             (hpdev->desc.v_id == new_desc->v_id) &&
1666                             (hpdev->desc.d_id == new_desc->d_id) &&
1667                             (hpdev->desc.ser == new_desc->ser)) {
1668                                 hpdev->reported_missing = false;
1669                                 found = true;
1670                         }
1671                 }
1672                 spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1673
1674                 if (!found) {
1675                         hpdev = new_pcichild_device(hbus, new_desc);
1676                         if (!hpdev)
1677                                 dev_err(&hbus->hdev->device,
1678                                         "couldn't record a child device.\n");
1679                 }
1680         }
1681
1682         /* Move missing children to a list on the stack. */
1683         spin_lock_irqsave(&hbus->device_list_lock, flags);
1684         do {
1685                 found = false;
1686                 list_for_each(iter, &hbus->children) {
1687                         hpdev = container_of(iter, struct hv_pci_dev,
1688                                              list_entry);
1689                         if (hpdev->reported_missing) {
1690                                 found = true;
1691                                 put_pcichild(hpdev, hv_pcidev_ref_childlist);
1692                                 list_move_tail(&hpdev->list_entry, &removed);
1693                                 break;
1694                         }
1695                 }
1696         } while (found);
1697         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1698
1699         /* Delete everything that should no longer exist. */
1700         while (!list_empty(&removed)) {
1701                 hpdev = list_first_entry(&removed, struct hv_pci_dev,
1702                                          list_entry);
1703                 list_del(&hpdev->list_entry);
1704                 put_pcichild(hpdev, hv_pcidev_ref_initial);
1705         }
1706
1707         switch (hbus->state) {
1708         case hv_pcibus_installed:
1709                 /*
1710                  * Tell the core to rescan bus
1711                  * because there may have been changes.
1712                  */
1713                 pci_lock_rescan_remove();
1714                 pci_scan_child_bus(hbus->pci_bus);
1715                 pci_unlock_rescan_remove();
1716                 break;
1717
1718         case hv_pcibus_init:
1719         case hv_pcibus_probed:
1720                 survey_child_resources(hbus);
1721                 break;
1722
1723         default:
1724                 break;
1725         }
1726
1727         up(&hbus->enum_sem);
1728         put_hvpcibus(hbus);
1729         kfree(dr);
1730 }
1731
1732 /**
1733  * hv_pci_devices_present() - Handles list of new children
1734  * @hbus:       Root PCI bus, as understood by this driver
1735  * @relations:  Packet from host listing children
1736  *
1737  * This function is invoked whenever a new list of devices for
1738  * this bus appears.
1739  */
1740 static void hv_pci_devices_present(struct hv_pcibus_device *hbus,
1741                                    struct pci_bus_relations *relations)
1742 {
1743         struct hv_dr_state *dr;
1744         struct hv_dr_work *dr_wrk;
1745         unsigned long flags;
1746
1747         dr_wrk = kzalloc(sizeof(*dr_wrk), GFP_NOWAIT);
1748         if (!dr_wrk)
1749                 return;
1750
1751         dr = kzalloc(offsetof(struct hv_dr_state, func) +
1752                      (sizeof(struct pci_function_description) *
1753                       (relations->device_count)), GFP_NOWAIT);
1754         if (!dr)  {
1755                 kfree(dr_wrk);
1756                 return;
1757         }
1758
1759         INIT_WORK(&dr_wrk->wrk, pci_devices_present_work);
1760         dr_wrk->bus = hbus;
1761         dr->device_count = relations->device_count;
1762         if (dr->device_count != 0) {
1763                 memcpy(dr->func, relations->func,
1764                        sizeof(struct pci_function_description) *
1765                        dr->device_count);
1766         }
1767
1768         spin_lock_irqsave(&hbus->device_list_lock, flags);
1769         list_add_tail(&dr->list_entry, &hbus->dr_list);
1770         spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1771
1772         get_hvpcibus(hbus);
1773         schedule_work(&dr_wrk->wrk);
1774 }
1775
1776 /**
1777  * hv_eject_device_work() - Asynchronously handles ejection
1778  * @work:       Work struct embedded in internal device struct
1779  *
1780  * This function handles ejecting a device.  Windows will
1781  * attempt to gracefully eject a device, waiting 60 seconds to
1782  * hear back from the guest OS that this completed successfully.
1783  * If this timer expires, the device will be forcibly removed.
1784  */
1785 static void hv_eject_device_work(struct work_struct *work)
1786 {
1787         struct pci_eject_response *ejct_pkt;
1788         struct hv_pci_dev *hpdev;
1789         struct pci_dev *pdev;
1790         unsigned long flags;
1791         int wslot;
1792         struct {
1793                 struct pci_packet pkt;
1794                 u8 buffer[sizeof(struct pci_eject_response)];
1795         } ctxt;
1796
1797         hpdev = container_of(work, struct hv_pci_dev, wrk);
1798
1799         if (hpdev->state != hv_pcichild_ejecting) {
1800                 put_pcichild(hpdev, hv_pcidev_ref_pnp);
1801                 return;
1802         }
1803
1804         /*
1805          * Ejection can come before or after the PCI bus has been set up, so
1806          * attempt to find it and tear down the bus state, if it exists.  This
1807          * must be done without constructs like pci_domain_nr(hbus->pci_bus)
1808          * because hbus->pci_bus may not exist yet.
1809          */
1810         wslot = wslot_to_devfn(hpdev->desc.win_slot.slot);
1811         pdev = pci_get_domain_bus_and_slot(hpdev->hbus->sysdata.domain, 0,
1812                                            wslot);
1813         if (pdev) {
1814                 pci_lock_rescan_remove();
1815                 pci_stop_and_remove_bus_device(pdev);
1816                 pci_dev_put(pdev);
1817                 pci_unlock_rescan_remove();
1818         }
1819
1820         spin_lock_irqsave(&hpdev->hbus->device_list_lock, flags);
1821         list_del(&hpdev->list_entry);
1822         spin_unlock_irqrestore(&hpdev->hbus->device_list_lock, flags);
1823
1824         memset(&ctxt, 0, sizeof(ctxt));
1825         ejct_pkt = (struct pci_eject_response *)&ctxt.pkt.message;
1826         ejct_pkt->message_type.type = PCI_EJECTION_COMPLETE;
1827         ejct_pkt->wslot.slot = hpdev->desc.win_slot.slot;
1828         vmbus_sendpacket(hpdev->hbus->hdev->channel, ejct_pkt,
1829                          sizeof(*ejct_pkt), (unsigned long)&ctxt.pkt,
1830                          VM_PKT_DATA_INBAND, 0);
1831
1832         put_pcichild(hpdev, hv_pcidev_ref_childlist);
1833         put_pcichild(hpdev, hv_pcidev_ref_pnp);
1834         put_hvpcibus(hpdev->hbus);
1835 }
1836
1837 /**
1838  * hv_pci_eject_device() - Handles device ejection
1839  * @hpdev:      Internal device tracking struct
1840  *
1841  * This function is invoked when an ejection packet arrives.  It
1842  * just schedules work so that we don't re-enter the packet
1843  * delivery code handling the ejection.
1844  */
1845 static void hv_pci_eject_device(struct hv_pci_dev *hpdev)
1846 {
1847         hpdev->state = hv_pcichild_ejecting;
1848         get_pcichild(hpdev, hv_pcidev_ref_pnp);
1849         INIT_WORK(&hpdev->wrk, hv_eject_device_work);
1850         get_hvpcibus(hpdev->hbus);
1851         schedule_work(&hpdev->wrk);
1852 }
1853
1854 /**
1855  * hv_pci_onchannelcallback() - Handles incoming packets
1856  * @context:    Internal bus tracking struct
1857  *
1858  * This function is invoked whenever the host sends a packet to
1859  * this channel (which is private to this root PCI bus).
1860  */
1861 static void hv_pci_onchannelcallback(void *context)
1862 {
1863         const int packet_size = 0x100;
1864         int ret;
1865         struct hv_pcibus_device *hbus = context;
1866         u32 bytes_recvd;
1867         u64 req_id;
1868         struct vmpacket_descriptor *desc;
1869         unsigned char *buffer;
1870         int bufferlen = packet_size;
1871         struct pci_packet *comp_packet;
1872         struct pci_response *response;
1873         struct pci_incoming_message *new_message;
1874         struct pci_bus_relations *bus_rel;
1875         struct pci_dev_incoming *dev_message;
1876         struct hv_pci_dev *hpdev;
1877
1878         buffer = kmalloc(bufferlen, GFP_ATOMIC);
1879         if (!buffer)
1880                 return;
1881
1882         while (1) {
1883                 ret = vmbus_recvpacket_raw(hbus->hdev->channel, buffer,
1884                                            bufferlen, &bytes_recvd, &req_id);
1885
1886                 if (ret == -ENOBUFS) {
1887                         kfree(buffer);
1888                         /* Handle large packet */
1889                         bufferlen = bytes_recvd;
1890                         buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
1891                         if (!buffer)
1892                                 return;
1893                         continue;
1894                 }
1895
1896                 /* Zero length indicates there are no more packets. */
1897                 if (ret || !bytes_recvd)
1898                         break;
1899
1900                 /*
1901                  * All incoming packets must be at least as large as a
1902                  * response.
1903                  */
1904                 if (bytes_recvd <= sizeof(struct pci_response))
1905                         continue;
1906                 desc = (struct vmpacket_descriptor *)buffer;
1907
1908                 switch (desc->type) {
1909                 case VM_PKT_COMP:
1910
1911                         /*
1912                          * The host is trusted, and thus it's safe to interpret
1913                          * this transaction ID as a pointer.
1914                          */
1915                         comp_packet = (struct pci_packet *)req_id;
1916                         response = (struct pci_response *)buffer;
1917                         comp_packet->completion_func(comp_packet->compl_ctxt,
1918                                                      response,
1919                                                      bytes_recvd);
1920                         break;
1921
1922                 case VM_PKT_DATA_INBAND:
1923
1924                         new_message = (struct pci_incoming_message *)buffer;
1925                         switch (new_message->message_type.type) {
1926                         case PCI_BUS_RELATIONS:
1927
1928                                 bus_rel = (struct pci_bus_relations *)buffer;
1929                                 if (bytes_recvd <
1930                                     offsetof(struct pci_bus_relations, func) +
1931                                     (sizeof(struct pci_function_description) *
1932                                      (bus_rel->device_count))) {
1933                                         dev_err(&hbus->hdev->device,
1934                                                 "bus relations too small\n");
1935                                         break;
1936                                 }
1937
1938                                 hv_pci_devices_present(hbus, bus_rel);
1939                                 break;
1940
1941                         case PCI_EJECT:
1942
1943                                 dev_message = (struct pci_dev_incoming *)buffer;
1944                                 hpdev = get_pcichild_wslot(hbus,
1945                                                       dev_message->wslot.slot);
1946                                 if (hpdev) {
1947                                         hv_pci_eject_device(hpdev);
1948                                         put_pcichild(hpdev,
1949                                                         hv_pcidev_ref_by_slot);
1950                                 }
1951                                 break;
1952
1953                         default:
1954                                 dev_warn(&hbus->hdev->device,
1955                                         "Unimplemented protocol message %x\n",
1956                                         new_message->message_type.type);
1957                                 break;
1958                         }
1959                         break;
1960
1961                 default:
1962                         dev_err(&hbus->hdev->device,
1963                                 "unhandled packet type %d, tid %llx len %d\n",
1964                                 desc->type, req_id, bytes_recvd);
1965                         break;
1966                 }
1967         }
1968
1969         kfree(buffer);
1970 }
1971
1972 /**
1973  * hv_pci_protocol_negotiation() - Set up protocol
1974  * @hdev:       VMBus's tracking struct for this root PCI bus
1975  *
1976  * This driver is intended to support running on Windows 10
1977  * (server) and later versions. It will not run on earlier
1978  * versions, as they assume that many of the operations which
1979  * Linux needs accomplished with a spinlock held were done via
1980  * asynchronous messaging via VMBus.  Windows 10 increases the
1981  * surface area of PCI emulation so that these actions can take
1982  * place by suspending a virtual processor for their duration.
1983  *
1984  * This function negotiates the channel protocol version,
1985  * failing if the host doesn't support the necessary protocol
1986  * level.
1987  */
1988 static int hv_pci_protocol_negotiation(struct hv_device *hdev)
1989 {
1990         struct pci_version_request *version_req;
1991         struct hv_pci_compl comp_pkt;
1992         struct pci_packet *pkt;
1993         int ret;
1994         int i;
1995
1996         /*
1997          * Initiate the handshake with the host and negotiate
1998          * a version that the host can support. We start with the
1999          * highest version number and go down if the host cannot
2000          * support it.
2001          */
2002         pkt = kzalloc(sizeof(*pkt) + sizeof(*version_req), GFP_KERNEL);
2003         if (!pkt)
2004                 return -ENOMEM;
2005
2006         init_completion(&comp_pkt.host_event);
2007         pkt->completion_func = hv_pci_generic_compl;
2008         pkt->compl_ctxt = &comp_pkt;
2009         version_req = (struct pci_version_request *)&pkt->message;
2010         version_req->message_type.type = PCI_QUERY_PROTOCOL_VERSION;
2011
2012         for (i = 0; i < ARRAY_SIZE(pci_protocol_versions); i++) {
2013                 version_req->protocol_version = pci_protocol_versions[i];
2014                 ret = vmbus_sendpacket(hdev->channel, version_req,
2015                                 sizeof(struct pci_version_request),
2016                                 (unsigned long)pkt, VM_PKT_DATA_INBAND,
2017                                 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2018                 if (ret) {
2019                         dev_err(&hdev->device,
2020                                 "PCI Pass-through VSP failed sending version reqquest: %#x",
2021                                 ret);
2022                         goto exit;
2023                 }
2024
2025                 wait_for_completion(&comp_pkt.host_event);
2026
2027                 if (comp_pkt.completion_status >= 0) {
2028                         pci_protocol_version = pci_protocol_versions[i];
2029                         dev_info(&hdev->device,
2030                                 "PCI VMBus probing: Using version %#x\n",
2031                                 pci_protocol_version);
2032                         goto exit;
2033                 }
2034
2035                 if (comp_pkt.completion_status != STATUS_REVISION_MISMATCH) {
2036                         dev_err(&hdev->device,
2037                                 "PCI Pass-through VSP failed version request: %#x",
2038                                 comp_pkt.completion_status);
2039                         ret = -EPROTO;
2040                         goto exit;
2041                 }
2042
2043                 reinit_completion(&comp_pkt.host_event);
2044         }
2045
2046         dev_err(&hdev->device,
2047                 "PCI pass-through VSP failed to find supported version");
2048         ret = -EPROTO;
2049
2050 exit:
2051         kfree(pkt);
2052         return ret;
2053 }
2054
2055 /**
2056  * hv_pci_free_bridge_windows() - Release memory regions for the
2057  * bus
2058  * @hbus:       Root PCI bus, as understood by this driver
2059  */
2060 static void hv_pci_free_bridge_windows(struct hv_pcibus_device *hbus)
2061 {
2062         /*
2063          * Set the resources back to the way they looked when they
2064          * were allocated by setting IORESOURCE_BUSY again.
2065          */
2066
2067         if (hbus->low_mmio_space && hbus->low_mmio_res) {
2068                 hbus->low_mmio_res->flags |= IORESOURCE_BUSY;
2069                 vmbus_free_mmio(hbus->low_mmio_res->start,
2070                                 resource_size(hbus->low_mmio_res));
2071         }
2072
2073         if (hbus->high_mmio_space && hbus->high_mmio_res) {
2074                 hbus->high_mmio_res->flags |= IORESOURCE_BUSY;
2075                 vmbus_free_mmio(hbus->high_mmio_res->start,
2076                                 resource_size(hbus->high_mmio_res));
2077         }
2078 }
2079
2080 /**
2081  * hv_pci_allocate_bridge_windows() - Allocate memory regions
2082  * for the bus
2083  * @hbus:       Root PCI bus, as understood by this driver
2084  *
2085  * This function calls vmbus_allocate_mmio(), which is itself a
2086  * bit of a compromise.  Ideally, we might change the pnp layer
2087  * in the kernel such that it comprehends either PCI devices
2088  * which are "grandchildren of ACPI," with some intermediate bus
2089  * node (in this case, VMBus) or change it such that it
2090  * understands VMBus.  The pnp layer, however, has been declared
2091  * deprecated, and not subject to change.
2092  *
2093  * The workaround, implemented here, is to ask VMBus to allocate
2094  * MMIO space for this bus.  VMBus itself knows which ranges are
2095  * appropriate by looking at its own ACPI objects.  Then, after
2096  * these ranges are claimed, they're modified to look like they
2097  * would have looked if the ACPI and pnp code had allocated
2098  * bridge windows.  These descriptors have to exist in this form
2099  * in order to satisfy the code which will get invoked when the
2100  * endpoint PCI function driver calls request_mem_region() or
2101  * request_mem_region_exclusive().
2102  *
2103  * Return: 0 on success, -errno on failure
2104  */
2105 static int hv_pci_allocate_bridge_windows(struct hv_pcibus_device *hbus)
2106 {
2107         resource_size_t align;
2108         int ret;
2109
2110         if (hbus->low_mmio_space) {
2111                 align = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
2112                 ret = vmbus_allocate_mmio(&hbus->low_mmio_res, hbus->hdev, 0,
2113                                           (u64)(u32)0xffffffff,
2114                                           hbus->low_mmio_space,
2115                                           align, false);
2116                 if (ret) {
2117                         dev_err(&hbus->hdev->device,
2118                                 "Need %#llx of low MMIO space. Consider reconfiguring the VM.\n",
2119                                 hbus->low_mmio_space);
2120                         return ret;
2121                 }
2122
2123                 /* Modify this resource to become a bridge window. */
2124                 hbus->low_mmio_res->flags |= IORESOURCE_WINDOW;
2125                 hbus->low_mmio_res->flags &= ~IORESOURCE_BUSY;
2126                 pci_add_resource(&hbus->resources_for_children,
2127                                  hbus->low_mmio_res);
2128         }
2129
2130         if (hbus->high_mmio_space) {
2131                 align = 1ULL << (63 - __builtin_clzll(hbus->high_mmio_space));
2132                 ret = vmbus_allocate_mmio(&hbus->high_mmio_res, hbus->hdev,
2133                                           0x100000000, -1,
2134                                           hbus->high_mmio_space, align,
2135                                           false);
2136                 if (ret) {
2137                         dev_err(&hbus->hdev->device,
2138                                 "Need %#llx of high MMIO space. Consider reconfiguring the VM.\n",
2139                                 hbus->high_mmio_space);
2140                         goto release_low_mmio;
2141                 }
2142
2143                 /* Modify this resource to become a bridge window. */
2144                 hbus->high_mmio_res->flags |= IORESOURCE_WINDOW;
2145                 hbus->high_mmio_res->flags &= ~IORESOURCE_BUSY;
2146                 pci_add_resource(&hbus->resources_for_children,
2147                                  hbus->high_mmio_res);
2148         }
2149
2150         return 0;
2151
2152 release_low_mmio:
2153         if (hbus->low_mmio_res) {
2154                 vmbus_free_mmio(hbus->low_mmio_res->start,
2155                                 resource_size(hbus->low_mmio_res));
2156         }
2157
2158         return ret;
2159 }
2160
2161 /**
2162  * hv_allocate_config_window() - Find MMIO space for PCI Config
2163  * @hbus:       Root PCI bus, as understood by this driver
2164  *
2165  * This function claims memory-mapped I/O space for accessing
2166  * configuration space for the functions on this bus.
2167  *
2168  * Return: 0 on success, -errno on failure
2169  */
2170 static int hv_allocate_config_window(struct hv_pcibus_device *hbus)
2171 {
2172         int ret;
2173
2174         /*
2175          * Set up a region of MMIO space to use for accessing configuration
2176          * space.
2177          */
2178         ret = vmbus_allocate_mmio(&hbus->mem_config, hbus->hdev, 0, -1,
2179                                   PCI_CONFIG_MMIO_LENGTH, 0x1000, false);
2180         if (ret)
2181                 return ret;
2182
2183         /*
2184          * vmbus_allocate_mmio() gets used for allocating both device endpoint
2185          * resource claims (those which cannot be overlapped) and the ranges
2186          * which are valid for the children of this bus, which are intended
2187          * to be overlapped by those children.  Set the flag on this claim
2188          * meaning that this region can't be overlapped.
2189          */
2190
2191         hbus->mem_config->flags |= IORESOURCE_BUSY;
2192
2193         return 0;
2194 }
2195
2196 static void hv_free_config_window(struct hv_pcibus_device *hbus)
2197 {
2198         vmbus_free_mmio(hbus->mem_config->start, PCI_CONFIG_MMIO_LENGTH);
2199 }
2200
2201 /**
2202  * hv_pci_enter_d0() - Bring the "bus" into the D0 power state
2203  * @hdev:       VMBus's tracking struct for this root PCI bus
2204  *
2205  * Return: 0 on success, -errno on failure
2206  */
2207 static int hv_pci_enter_d0(struct hv_device *hdev)
2208 {
2209         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2210         struct pci_bus_d0_entry *d0_entry;
2211         struct hv_pci_compl comp_pkt;
2212         struct pci_packet *pkt;
2213         int ret;
2214
2215         /*
2216          * Tell the host that the bus is ready to use, and moved into the
2217          * powered-on state.  This includes telling the host which region
2218          * of memory-mapped I/O space has been chosen for configuration space
2219          * access.
2220          */
2221         pkt = kzalloc(sizeof(*pkt) + sizeof(*d0_entry), GFP_KERNEL);
2222         if (!pkt)
2223                 return -ENOMEM;
2224
2225         init_completion(&comp_pkt.host_event);
2226         pkt->completion_func = hv_pci_generic_compl;
2227         pkt->compl_ctxt = &comp_pkt;
2228         d0_entry = (struct pci_bus_d0_entry *)&pkt->message;
2229         d0_entry->message_type.type = PCI_BUS_D0ENTRY;
2230         d0_entry->mmio_base = hbus->mem_config->start;
2231
2232         ret = vmbus_sendpacket(hdev->channel, d0_entry, sizeof(*d0_entry),
2233                                (unsigned long)pkt, VM_PKT_DATA_INBAND,
2234                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2235         if (ret)
2236                 goto exit;
2237
2238         wait_for_completion(&comp_pkt.host_event);
2239
2240         if (comp_pkt.completion_status < 0) {
2241                 dev_err(&hdev->device,
2242                         "PCI Pass-through VSP failed D0 Entry with status %x\n",
2243                         comp_pkt.completion_status);
2244                 ret = -EPROTO;
2245                 goto exit;
2246         }
2247
2248         ret = 0;
2249
2250 exit:
2251         kfree(pkt);
2252         return ret;
2253 }
2254
2255 /**
2256  * hv_pci_query_relations() - Ask host to send list of child
2257  * devices
2258  * @hdev:       VMBus's tracking struct for this root PCI bus
2259  *
2260  * Return: 0 on success, -errno on failure
2261  */
2262 static int hv_pci_query_relations(struct hv_device *hdev)
2263 {
2264         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2265         struct pci_message message;
2266         struct completion comp;
2267         int ret;
2268
2269         /* Ask the host to send along the list of child devices */
2270         init_completion(&comp);
2271         if (cmpxchg(&hbus->survey_event, NULL, &comp))
2272                 return -ENOTEMPTY;
2273
2274         memset(&message, 0, sizeof(message));
2275         message.type = PCI_QUERY_BUS_RELATIONS;
2276
2277         ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
2278                                0, VM_PKT_DATA_INBAND, 0);
2279         if (ret)
2280                 return ret;
2281
2282         wait_for_completion(&comp);
2283         return 0;
2284 }
2285
2286 /**
2287  * hv_send_resources_allocated() - Report local resource choices
2288  * @hdev:       VMBus's tracking struct for this root PCI bus
2289  *
2290  * The host OS is expecting to be sent a request as a message
2291  * which contains all the resources that the device will use.
2292  * The response contains those same resources, "translated"
2293  * which is to say, the values which should be used by the
2294  * hardware, when it delivers an interrupt.  (MMIO resources are
2295  * used in local terms.)  This is nice for Windows, and lines up
2296  * with the FDO/PDO split, which doesn't exist in Linux.  Linux
2297  * is deeply expecting to scan an emulated PCI configuration
2298  * space.  So this message is sent here only to drive the state
2299  * machine on the host forward.
2300  *
2301  * Return: 0 on success, -errno on failure
2302  */
2303 static int hv_send_resources_allocated(struct hv_device *hdev)
2304 {
2305         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2306         struct pci_resources_assigned *res_assigned;
2307         struct pci_resources_assigned2 *res_assigned2;
2308         struct hv_pci_compl comp_pkt;
2309         struct hv_pci_dev *hpdev;
2310         struct pci_packet *pkt;
2311         size_t size_res;
2312         u32 wslot;
2313         int ret;
2314
2315         size_res = (pci_protocol_version < PCI_PROTOCOL_VERSION_1_2)
2316                         ? sizeof(*res_assigned) : sizeof(*res_assigned2);
2317
2318         pkt = kmalloc(sizeof(*pkt) + size_res, GFP_KERNEL);
2319         if (!pkt)
2320                 return -ENOMEM;
2321
2322         ret = 0;
2323
2324         for (wslot = 0; wslot < 256; wslot++) {
2325                 hpdev = get_pcichild_wslot(hbus, wslot);
2326                 if (!hpdev)
2327                         continue;
2328
2329                 memset(pkt, 0, sizeof(*pkt) + size_res);
2330                 init_completion(&comp_pkt.host_event);
2331                 pkt->completion_func = hv_pci_generic_compl;
2332                 pkt->compl_ctxt = &comp_pkt;
2333
2334                 if (pci_protocol_version < PCI_PROTOCOL_VERSION_1_2) {
2335                         res_assigned =
2336                                 (struct pci_resources_assigned *)&pkt->message;
2337                         res_assigned->message_type.type =
2338                                 PCI_RESOURCES_ASSIGNED;
2339                         res_assigned->wslot.slot = hpdev->desc.win_slot.slot;
2340                 } else {
2341                         res_assigned2 =
2342                                 (struct pci_resources_assigned2 *)&pkt->message;
2343                         res_assigned2->message_type.type =
2344                                 PCI_RESOURCES_ASSIGNED2;
2345                         res_assigned2->wslot.slot = hpdev->desc.win_slot.slot;
2346                 }
2347                 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
2348
2349                 ret = vmbus_sendpacket(hdev->channel, &pkt->message,
2350                                 size_res, (unsigned long)pkt,
2351                                 VM_PKT_DATA_INBAND,
2352                                 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2353                 if (ret)
2354                         break;
2355
2356                 wait_for_completion(&comp_pkt.host_event);
2357
2358                 if (comp_pkt.completion_status < 0) {
2359                         ret = -EPROTO;
2360                         dev_err(&hdev->device,
2361                                 "resource allocated returned 0x%x",
2362                                 comp_pkt.completion_status);
2363                         break;
2364                 }
2365         }
2366
2367         kfree(pkt);
2368         return ret;
2369 }
2370
2371 /**
2372  * hv_send_resources_released() - Report local resources
2373  * released
2374  * @hdev:       VMBus's tracking struct for this root PCI bus
2375  *
2376  * Return: 0 on success, -errno on failure
2377  */
2378 static int hv_send_resources_released(struct hv_device *hdev)
2379 {
2380         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2381         struct pci_child_message pkt;
2382         struct hv_pci_dev *hpdev;
2383         u32 wslot;
2384         int ret;
2385
2386         for (wslot = 0; wslot < 256; wslot++) {
2387                 hpdev = get_pcichild_wslot(hbus, wslot);
2388                 if (!hpdev)
2389                         continue;
2390
2391                 memset(&pkt, 0, sizeof(pkt));
2392                 pkt.message_type.type = PCI_RESOURCES_RELEASED;
2393                 pkt.wslot.slot = hpdev->desc.win_slot.slot;
2394
2395                 put_pcichild(hpdev, hv_pcidev_ref_by_slot);
2396
2397                 ret = vmbus_sendpacket(hdev->channel, &pkt, sizeof(pkt), 0,
2398                                        VM_PKT_DATA_INBAND, 0);
2399                 if (ret)
2400                         return ret;
2401         }
2402
2403         return 0;
2404 }
2405
2406 static void get_hvpcibus(struct hv_pcibus_device *hbus)
2407 {
2408         atomic_inc(&hbus->remove_lock);
2409 }
2410
2411 static void put_hvpcibus(struct hv_pcibus_device *hbus)
2412 {
2413         if (atomic_dec_and_test(&hbus->remove_lock))
2414                 complete(&hbus->remove_event);
2415 }
2416
2417 /**
2418  * hv_pci_probe() - New VMBus channel probe, for a root PCI bus
2419  * @hdev:       VMBus's tracking struct for this root PCI bus
2420  * @dev_id:     Identifies the device itself
2421  *
2422  * Return: 0 on success, -errno on failure
2423  */
2424 static int hv_pci_probe(struct hv_device *hdev,
2425                         const struct hv_vmbus_device_id *dev_id)
2426 {
2427         struct hv_pcibus_device *hbus;
2428         int ret;
2429
2430         /*
2431          * hv_pcibus_device contains the hypercall arguments for retargeting in
2432          * hv_irq_unmask(). Those must not cross a page boundary.
2433          */
2434         BUILD_BUG_ON(sizeof(*hbus) > PAGE_SIZE);
2435
2436         hbus = (struct hv_pcibus_device *)get_zeroed_page(GFP_KERNEL);
2437         if (!hbus)
2438                 return -ENOMEM;
2439         hbus->state = hv_pcibus_init;
2440
2441         /*
2442          * The PCI bus "domain" is what is called "segment" in ACPI and
2443          * other specs.  Pull it from the instance ID, to get something
2444          * unique.  Bytes 8 and 9 are what is used in Windows guests, so
2445          * do the same thing for consistency.  Note that, since this code
2446          * only runs in a Hyper-V VM, Hyper-V can (and does) guarantee
2447          * that (1) the only domain in use for something that looks like
2448          * a physical PCI bus (which is actually emulated by the
2449          * hypervisor) is domain 0 and (2) there will be no overlap
2450          * between domains derived from these instance IDs in the same
2451          * VM.
2452          */
2453         hbus->sysdata.domain = hdev->dev_instance.b[9] |
2454                                hdev->dev_instance.b[8] << 8;
2455
2456         hbus->hdev = hdev;
2457         atomic_inc(&hbus->remove_lock);
2458         INIT_LIST_HEAD(&hbus->children);
2459         INIT_LIST_HEAD(&hbus->dr_list);
2460         INIT_LIST_HEAD(&hbus->resources_for_children);
2461         spin_lock_init(&hbus->config_lock);
2462         spin_lock_init(&hbus->device_list_lock);
2463         spin_lock_init(&hbus->retarget_msi_interrupt_lock);
2464         sema_init(&hbus->enum_sem, 1);
2465         init_completion(&hbus->remove_event);
2466
2467         ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
2468                          hv_pci_onchannelcallback, hbus);
2469         if (ret)
2470                 goto free_bus;
2471
2472         hv_set_drvdata(hdev, hbus);
2473
2474         ret = hv_pci_protocol_negotiation(hdev);
2475         if (ret)
2476                 goto close;
2477
2478         ret = hv_allocate_config_window(hbus);
2479         if (ret)
2480                 goto close;
2481
2482         hbus->cfg_addr = ioremap(hbus->mem_config->start,
2483                                  PCI_CONFIG_MMIO_LENGTH);
2484         if (!hbus->cfg_addr) {
2485                 dev_err(&hdev->device,
2486                         "Unable to map a virtual address for config space\n");
2487                 ret = -ENOMEM;
2488                 goto free_config;
2489         }
2490
2491         hbus->sysdata.fwnode = irq_domain_alloc_fwnode(hbus);
2492         if (!hbus->sysdata.fwnode) {
2493                 ret = -ENOMEM;
2494                 goto unmap;
2495         }
2496
2497         ret = hv_pcie_init_irq_domain(hbus);
2498         if (ret)
2499                 goto free_fwnode;
2500
2501         ret = hv_pci_query_relations(hdev);
2502         if (ret)
2503                 goto free_irq_domain;
2504
2505         ret = hv_pci_enter_d0(hdev);
2506         if (ret)
2507                 goto free_irq_domain;
2508
2509         ret = hv_pci_allocate_bridge_windows(hbus);
2510         if (ret)
2511                 goto free_irq_domain;
2512
2513         ret = hv_send_resources_allocated(hdev);
2514         if (ret)
2515                 goto free_windows;
2516
2517         prepopulate_bars(hbus);
2518
2519         hbus->state = hv_pcibus_probed;
2520
2521         ret = create_root_hv_pci_bus(hbus);
2522         if (ret)
2523                 goto free_windows;
2524
2525         return 0;
2526
2527 free_windows:
2528         hv_pci_free_bridge_windows(hbus);
2529 free_irq_domain:
2530         irq_domain_remove(hbus->irq_domain);
2531 free_fwnode:
2532         irq_domain_free_fwnode(hbus->sysdata.fwnode);
2533 unmap:
2534         iounmap(hbus->cfg_addr);
2535 free_config:
2536         hv_free_config_window(hbus);
2537 close:
2538         vmbus_close(hdev->channel);
2539 free_bus:
2540         free_page((unsigned long)hbus);
2541         return ret;
2542 }
2543
2544 static void hv_pci_bus_exit(struct hv_device *hdev)
2545 {
2546         struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2547         struct {
2548                 struct pci_packet teardown_packet;
2549                 u8 buffer[sizeof(struct pci_message)];
2550         } pkt;
2551         struct pci_bus_relations relations;
2552         struct hv_pci_compl comp_pkt;
2553         int ret;
2554
2555         /*
2556          * After the host sends the RESCIND_CHANNEL message, it doesn't
2557          * access the per-channel ringbuffer any longer.
2558          */
2559         if (hdev->channel->rescind)
2560                 return;
2561
2562         /* Delete any children which might still exist. */
2563         memset(&relations, 0, sizeof(relations));
2564         hv_pci_devices_present(hbus, &relations);
2565
2566         ret = hv_send_resources_released(hdev);
2567         if (ret)
2568                 dev_err(&hdev->device,
2569                         "Couldn't send resources released packet(s)\n");
2570
2571         memset(&pkt.teardown_packet, 0, sizeof(pkt.teardown_packet));
2572         init_completion(&comp_pkt.host_event);
2573         pkt.teardown_packet.completion_func = hv_pci_generic_compl;
2574         pkt.teardown_packet.compl_ctxt = &comp_pkt;
2575         pkt.teardown_packet.message[0].type = PCI_BUS_D0EXIT;
2576
2577         ret = vmbus_sendpacket(hdev->channel, &pkt.teardown_packet.message,
2578                                sizeof(struct pci_message),
2579                                (unsigned long)&pkt.teardown_packet,
2580                                VM_PKT_DATA_INBAND,
2581                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2582         if (!ret)
2583                 wait_for_completion_timeout(&comp_pkt.host_event, 10 * HZ);
2584 }
2585
2586 /**
2587  * hv_pci_remove() - Remove routine for this VMBus channel
2588  * @hdev:       VMBus's tracking struct for this root PCI bus
2589  *
2590  * Return: 0 on success, -errno on failure
2591  */
2592 static int hv_pci_remove(struct hv_device *hdev)
2593 {
2594         struct hv_pcibus_device *hbus;
2595
2596         hbus = hv_get_drvdata(hdev);
2597         if (hbus->state == hv_pcibus_installed) {
2598                 /* Remove the bus from PCI's point of view. */
2599                 pci_lock_rescan_remove();
2600                 pci_stop_root_bus(hbus->pci_bus);
2601                 pci_remove_root_bus(hbus->pci_bus);
2602                 pci_unlock_rescan_remove();
2603                 hbus->state = hv_pcibus_removed;
2604         }
2605
2606         hv_pci_bus_exit(hdev);
2607
2608         vmbus_close(hdev->channel);
2609
2610         iounmap(hbus->cfg_addr);
2611         hv_free_config_window(hbus);
2612         pci_free_resource_list(&hbus->resources_for_children);
2613         hv_pci_free_bridge_windows(hbus);
2614         irq_domain_remove(hbus->irq_domain);
2615         irq_domain_free_fwnode(hbus->sysdata.fwnode);
2616         put_hvpcibus(hbus);
2617         wait_for_completion(&hbus->remove_event);
2618         free_page((unsigned long)hbus);
2619         return 0;
2620 }
2621
2622 static const struct hv_vmbus_device_id hv_pci_id_table[] = {
2623         /* PCI Pass-through Class ID */
2624         /* 44C4F61D-4444-4400-9D52-802E27EDE19F */
2625         { HV_PCIE_GUID, },
2626         { },
2627 };
2628
2629 MODULE_DEVICE_TABLE(vmbus, hv_pci_id_table);
2630
2631 static struct hv_driver hv_pci_drv = {
2632         .name           = "hv_pci",
2633         .id_table       = hv_pci_id_table,
2634         .probe          = hv_pci_probe,
2635         .remove         = hv_pci_remove,
2636 };
2637
2638 static void __exit exit_hv_pci_drv(void)
2639 {
2640         vmbus_driver_unregister(&hv_pci_drv);
2641 }
2642
2643 static int __init init_hv_pci_drv(void)
2644 {
2645         return vmbus_driver_register(&hv_pci_drv);
2646 }
2647
2648 module_init(init_hv_pci_drv);
2649 module_exit(exit_hv_pci_drv);
2650
2651 MODULE_DESCRIPTION("Hyper-V PCI");
2652 MODULE_LICENSE("GPL v2");