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