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