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