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