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