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