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