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