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