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