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