• 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 };
67 
68 #define CPU_AFFINITY_ALL	-1ULL
69 
70 /*
71  * Supported protocol versions in the order of probing - highest go
72  * first.
73  */
74 static enum pci_protocol_version_t pci_protocol_versions[] = {
75 	PCI_PROTOCOL_VERSION_1_2,
76 	PCI_PROTOCOL_VERSION_1_1,
77 };
78 
79 /*
80  * Protocol version negotiated by hv_pci_protocol_negotiation().
81  */
82 static enum pci_protocol_version_t pci_protocol_version;
83 
84 #define PCI_CONFIG_MMIO_LENGTH	0x2000
85 #define CFG_PAGE_OFFSET 0x1000
86 #define CFG_PAGE_SIZE (PCI_CONFIG_MMIO_LENGTH - CFG_PAGE_OFFSET)
87 
88 #define MAX_SUPPORTED_MSI_MESSAGES 0x400
89 
90 #define STATUS_REVISION_MISMATCH 0xC0000059
91 
92 /* space for 32bit serial number as string */
93 #define SLOT_NAME_SIZE 11
94 
95 /*
96  * Message Types
97  */
98 
99 enum pci_message_type {
100 	/*
101 	 * Version 1.1
102 	 */
103 	PCI_MESSAGE_BASE                = 0x42490000,
104 	PCI_BUS_RELATIONS               = PCI_MESSAGE_BASE + 0,
105 	PCI_QUERY_BUS_RELATIONS         = PCI_MESSAGE_BASE + 1,
106 	PCI_POWER_STATE_CHANGE          = PCI_MESSAGE_BASE + 4,
107 	PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5,
108 	PCI_QUERY_RESOURCE_RESOURCES    = PCI_MESSAGE_BASE + 6,
109 	PCI_BUS_D0ENTRY                 = PCI_MESSAGE_BASE + 7,
110 	PCI_BUS_D0EXIT                  = PCI_MESSAGE_BASE + 8,
111 	PCI_READ_BLOCK                  = PCI_MESSAGE_BASE + 9,
112 	PCI_WRITE_BLOCK                 = PCI_MESSAGE_BASE + 0xA,
113 	PCI_EJECT                       = PCI_MESSAGE_BASE + 0xB,
114 	PCI_QUERY_STOP                  = PCI_MESSAGE_BASE + 0xC,
115 	PCI_REENABLE                    = PCI_MESSAGE_BASE + 0xD,
116 	PCI_QUERY_STOP_FAILED           = PCI_MESSAGE_BASE + 0xE,
117 	PCI_EJECTION_COMPLETE           = PCI_MESSAGE_BASE + 0xF,
118 	PCI_RESOURCES_ASSIGNED          = PCI_MESSAGE_BASE + 0x10,
119 	PCI_RESOURCES_RELEASED          = PCI_MESSAGE_BASE + 0x11,
120 	PCI_INVALIDATE_BLOCK            = PCI_MESSAGE_BASE + 0x12,
121 	PCI_QUERY_PROTOCOL_VERSION      = PCI_MESSAGE_BASE + 0x13,
122 	PCI_CREATE_INTERRUPT_MESSAGE    = PCI_MESSAGE_BASE + 0x14,
123 	PCI_DELETE_INTERRUPT_MESSAGE    = PCI_MESSAGE_BASE + 0x15,
124 	PCI_RESOURCES_ASSIGNED2		= PCI_MESSAGE_BASE + 0x16,
125 	PCI_CREATE_INTERRUPT_MESSAGE2	= PCI_MESSAGE_BASE + 0x17,
126 	PCI_DELETE_INTERRUPT_MESSAGE2	= PCI_MESSAGE_BASE + 0x18, /* unused */
127 	PCI_MESSAGE_MAXIMUM
128 };
129 
130 /*
131  * Structures defining the virtual PCI Express protocol.
132  */
133 
134 union pci_version {
135 	struct {
136 		u16 minor_version;
137 		u16 major_version;
138 	} parts;
139 	u32 version;
140 } __packed;
141 
142 /*
143  * Function numbers are 8-bits wide on Express, as interpreted through ARI,
144  * which is all this driver does.  This representation is the one used in
145  * Windows, which is what is expected when sending this back and forth with
146  * the Hyper-V parent partition.
147  */
148 union win_slot_encoding {
149 	struct {
150 		u32	dev:5;
151 		u32	func:3;
152 		u32	reserved:24;
153 	} bits;
154 	u32 slot;
155 } __packed;
156 
157 /*
158  * Pretty much as defined in the PCI Specifications.
159  */
160 struct pci_function_description {
161 	u16	v_id;	/* vendor ID */
162 	u16	d_id;	/* device ID */
163 	u8	rev;
164 	u8	prog_intf;
165 	u8	subclass;
166 	u8	base_class;
167 	u32	subsystem_id;
168 	union win_slot_encoding win_slot;
169 	u32	ser;	/* serial number */
170 } __packed;
171 
172 /**
173  * struct hv_msi_desc
174  * @vector:		IDT entry
175  * @delivery_mode:	As defined in Intel's Programmer's
176  *			Reference Manual, Volume 3, Chapter 8.
177  * @vector_count:	Number of contiguous entries in the
178  *			Interrupt Descriptor Table that are
179  *			occupied by this Message-Signaled
180  *			Interrupt. For "MSI", as first defined
181  *			in PCI 2.2, this can be between 1 and
182  *			32. For "MSI-X," as first defined in PCI
183  *			3.0, this must be 1, as each MSI-X table
184  *			entry would have its own descriptor.
185  * @reserved:		Empty space
186  * @cpu_mask:		All the target virtual processors.
187  */
188 struct hv_msi_desc {
189 	u8	vector;
190 	u8	delivery_mode;
191 	u16	vector_count;
192 	u32	reserved;
193 	u64	cpu_mask;
194 } __packed;
195 
196 /**
197  * struct hv_msi_desc2 - 1.2 version of hv_msi_desc
198  * @vector:		IDT entry
199  * @delivery_mode:	As defined in Intel's Programmer's
200  *			Reference Manual, Volume 3, Chapter 8.
201  * @vector_count:	Number of contiguous entries in the
202  *			Interrupt Descriptor Table that are
203  *			occupied by this Message-Signaled
204  *			Interrupt. For "MSI", as first defined
205  *			in PCI 2.2, this can be between 1 and
206  *			32. For "MSI-X," as first defined in PCI
207  *			3.0, this must be 1, as each MSI-X table
208  *			entry would have its own descriptor.
209  * @processor_count:	number of bits enabled in array.
210  * @processor_array:	All the target virtual processors.
211  */
212 struct hv_msi_desc2 {
213 	u8	vector;
214 	u8	delivery_mode;
215 	u16	vector_count;
216 	u16	processor_count;
217 	u16	processor_array[32];
218 } __packed;
219 
220 /**
221  * struct tran_int_desc
222  * @reserved:		unused, padding
223  * @vector_count:	same as in hv_msi_desc
224  * @data:		This is the "data payload" value that is
225  *			written by the device when it generates
226  *			a message-signaled interrupt, either MSI
227  *			or MSI-X.
228  * @address:		This is the address to which the data
229  *			payload is written on interrupt
230  *			generation.
231  */
232 struct tran_int_desc {
233 	u16	reserved;
234 	u16	vector_count;
235 	u32	data;
236 	u64	address;
237 } __packed;
238 
239 /*
240  * A generic message format for virtual PCI.
241  * Specific message formats are defined later in the file.
242  */
243 
244 struct pci_message {
245 	u32 type;
246 } __packed;
247 
248 struct pci_child_message {
249 	struct pci_message message_type;
250 	union win_slot_encoding wslot;
251 } __packed;
252 
253 struct pci_incoming_message {
254 	struct vmpacket_descriptor hdr;
255 	struct pci_message message_type;
256 } __packed;
257 
258 struct pci_response {
259 	struct vmpacket_descriptor hdr;
260 	s32 status;			/* negative values are failures */
261 } __packed;
262 
263 struct pci_packet {
264 	void (*completion_func)(void *context, struct pci_response *resp,
265 				int resp_packet_size);
266 	void *compl_ctxt;
267 
268 	struct pci_message message[0];
269 };
270 
271 /*
272  * Specific message types supporting the PCI protocol.
273  */
274 
275 /*
276  * Version negotiation message. Sent from the guest to the host.
277  * The guest is free to try different versions until the host
278  * accepts the version.
279  *
280  * pci_version: The protocol version requested.
281  * is_last_attempt: If TRUE, this is the last version guest will request.
282  * reservedz: Reserved field, set to zero.
283  */
284 
285 struct pci_version_request {
286 	struct pci_message message_type;
287 	u32 protocol_version;
288 } __packed;
289 
290 /*
291  * Bus D0 Entry.  This is sent from the guest to the host when the virtual
292  * bus (PCI Express port) is ready for action.
293  */
294 
295 struct pci_bus_d0_entry {
296 	struct pci_message message_type;
297 	u32 reserved;
298 	u64 mmio_base;
299 } __packed;
300 
301 struct pci_bus_relations {
302 	struct pci_incoming_message incoming;
303 	u32 device_count;
304 	struct pci_function_description func[0];
305 } __packed;
306 
307 struct pci_q_res_req_response {
308 	struct vmpacket_descriptor hdr;
309 	s32 status;			/* negative values are failures */
310 	u32 probed_bar[6];
311 } __packed;
312 
313 struct pci_set_power {
314 	struct pci_message message_type;
315 	union win_slot_encoding wslot;
316 	u32 power_state;		/* In Windows terms */
317 	u32 reserved;
318 } __packed;
319 
320 struct pci_set_power_response {
321 	struct vmpacket_descriptor hdr;
322 	s32 status;			/* negative values are failures */
323 	union win_slot_encoding wslot;
324 	u32 resultant_state;		/* In Windows terms */
325 	u32 reserved;
326 } __packed;
327 
328 struct pci_resources_assigned {
329 	struct pci_message message_type;
330 	union win_slot_encoding wslot;
331 	u8 memory_range[0x14][6];	/* not used here */
332 	u32 msi_descriptors;
333 	u32 reserved[4];
334 } __packed;
335 
336 struct pci_resources_assigned2 {
337 	struct pci_message message_type;
338 	union win_slot_encoding wslot;
339 	u8 memory_range[0x14][6];	/* not used here */
340 	u32 msi_descriptor_count;
341 	u8 reserved[70];
342 } __packed;
343 
344 struct pci_create_interrupt {
345 	struct pci_message message_type;
346 	union win_slot_encoding wslot;
347 	struct hv_msi_desc int_desc;
348 } __packed;
349 
350 struct pci_create_int_response {
351 	struct pci_response response;
352 	u32 reserved;
353 	struct tran_int_desc int_desc;
354 } __packed;
355 
356 struct pci_create_interrupt2 {
357 	struct pci_message message_type;
358 	union win_slot_encoding wslot;
359 	struct hv_msi_desc2 int_desc;
360 } __packed;
361 
362 struct pci_delete_interrupt {
363 	struct pci_message message_type;
364 	union win_slot_encoding wslot;
365 	struct tran_int_desc int_desc;
366 } __packed;
367 
368 struct pci_dev_incoming {
369 	struct pci_incoming_message incoming;
370 	union win_slot_encoding wslot;
371 } __packed;
372 
373 struct pci_eject_response {
374 	struct pci_message message_type;
375 	union win_slot_encoding wslot;
376 	u32 status;
377 } __packed;
378 
379 static int pci_ring_size = (4 * PAGE_SIZE);
380 
381 /*
382  * Definitions or interrupt steering hypercall.
383  */
384 #define HV_PARTITION_ID_SELF		((u64)-1)
385 #define HVCALL_RETARGET_INTERRUPT	0x7e
386 
387 struct hv_interrupt_entry {
388 	u32	source;			/* 1 for MSI(-X) */
389 	u32	reserved1;
390 	u32	address;
391 	u32	data;
392 };
393 
394 #define HV_VP_SET_BANK_COUNT_MAX	5 /* current implementation limit */
395 
396 struct hv_vp_set {
397 	u64	format;			/* 0 (HvGenericSetSparse4k) */
398 	u64	valid_banks;
399 	u64	masks[HV_VP_SET_BANK_COUNT_MAX];
400 };
401 
402 /*
403  * flags for hv_device_interrupt_target.flags
404  */
405 #define HV_DEVICE_INTERRUPT_TARGET_MULTICAST		1
406 #define HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET	2
407 
408 struct hv_device_interrupt_target {
409 	u32	vector;
410 	u32	flags;
411 	union {
412 		u64		 vp_mask;
413 		struct hv_vp_set vp_set;
414 	};
415 };
416 
417 struct retarget_msi_interrupt {
418 	u64	partition_id;		/* use "self" */
419 	u64	device_id;
420 	struct hv_interrupt_entry int_entry;
421 	u64	reserved2;
422 	struct hv_device_interrupt_target int_target;
423 } __packed;
424 
425 /*
426  * Driver specific state.
427  */
428 
429 enum hv_pcibus_state {
430 	hv_pcibus_init = 0,
431 	hv_pcibus_probed,
432 	hv_pcibus_installed,
433 	hv_pcibus_removed,
434 	hv_pcibus_maximum
435 };
436 
437 struct hv_pcibus_device {
438 	struct pci_sysdata sysdata;
439 	enum hv_pcibus_state state;
440 	refcount_t remove_lock;
441 	struct hv_device *hdev;
442 	resource_size_t low_mmio_space;
443 	resource_size_t high_mmio_space;
444 	struct resource *mem_config;
445 	struct resource *low_mmio_res;
446 	struct resource *high_mmio_res;
447 	struct completion *survey_event;
448 	struct completion remove_event;
449 	struct pci_bus *pci_bus;
450 	spinlock_t config_lock;	/* Avoid two threads writing index page */
451 	spinlock_t device_list_lock;	/* Protect lists below */
452 	void __iomem *cfg_addr;
453 
454 	struct list_head resources_for_children;
455 
456 	struct list_head children;
457 	struct list_head dr_list;
458 
459 	struct msi_domain_info msi_info;
460 	struct msi_controller msi_chip;
461 	struct irq_domain *irq_domain;
462 
463 	/* hypercall arg, must not cross page boundary */
464 	struct retarget_msi_interrupt retarget_msi_interrupt_params;
465 
466 	spinlock_t retarget_msi_interrupt_lock;
467 
468 	struct workqueue_struct *wq;
469 };
470 
471 /*
472  * Tracks "Device Relations" messages from the host, which must be both
473  * processed in order and deferred so that they don't run in the context
474  * of the incoming packet callback.
475  */
476 struct hv_dr_work {
477 	struct work_struct wrk;
478 	struct hv_pcibus_device *bus;
479 };
480 
481 struct hv_dr_state {
482 	struct list_head list_entry;
483 	u32 device_count;
484 	struct pci_function_description func[0];
485 };
486 
487 enum hv_pcichild_state {
488 	hv_pcichild_init = 0,
489 	hv_pcichild_requirements,
490 	hv_pcichild_resourced,
491 	hv_pcichild_ejecting,
492 	hv_pcichild_maximum
493 };
494 
495 struct hv_pci_dev {
496 	/* List protected by pci_rescan_remove_lock */
497 	struct list_head list_entry;
498 	refcount_t refs;
499 	enum hv_pcichild_state state;
500 	struct pci_slot *pci_slot;
501 	struct pci_function_description desc;
502 	bool reported_missing;
503 	struct hv_pcibus_device *hbus;
504 	struct work_struct wrk;
505 
506 	/*
507 	 * What would be observed if one wrote 0xFFFFFFFF to a BAR and then
508 	 * read it back, for each of the BAR offsets within config space.
509 	 */
510 	u32 probed_bar[6];
511 };
512 
513 struct hv_pci_compl {
514 	struct completion host_event;
515 	s32 completion_status;
516 };
517 
518 static void hv_pci_onchannelcallback(void *context);
519 
520 /**
521  * hv_pci_generic_compl() - Invoked for a completion packet
522  * @context:		Set up by the sender of the packet.
523  * @resp:		The response packet
524  * @resp_packet_size:	Size in bytes of the packet
525  *
526  * This function is used to trigger an event and report status
527  * for any message for which the completion packet contains a
528  * status and nothing else.
529  */
hv_pci_generic_compl(void * context,struct pci_response * resp,int resp_packet_size)530 static void hv_pci_generic_compl(void *context, struct pci_response *resp,
531 				 int resp_packet_size)
532 {
533 	struct hv_pci_compl *comp_pkt = context;
534 
535 	if (resp_packet_size >= offsetofend(struct pci_response, status))
536 		comp_pkt->completion_status = resp->status;
537 	else
538 		comp_pkt->completion_status = -1;
539 
540 	complete(&comp_pkt->host_event);
541 }
542 
543 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
544 						u32 wslot);
545 
get_pcichild(struct hv_pci_dev * hpdev)546 static void get_pcichild(struct hv_pci_dev *hpdev)
547 {
548 	refcount_inc(&hpdev->refs);
549 }
550 
put_pcichild(struct hv_pci_dev * hpdev)551 static void put_pcichild(struct hv_pci_dev *hpdev)
552 {
553 	if (refcount_dec_and_test(&hpdev->refs))
554 		kfree(hpdev);
555 }
556 
557 static void get_hvpcibus(struct hv_pcibus_device *hv_pcibus);
558 static void put_hvpcibus(struct hv_pcibus_device *hv_pcibus);
559 
560 /*
561  * There is no good way to get notified from vmbus_onoffer_rescind(),
562  * so let's use polling here, since this is not a hot path.
563  */
wait_for_response(struct hv_device * hdev,struct completion * comp)564 static int wait_for_response(struct hv_device *hdev,
565 			     struct completion *comp)
566 {
567 	while (true) {
568 		if (hdev->channel->rescind) {
569 			dev_warn_once(&hdev->device, "The device is gone.\n");
570 			return -ENODEV;
571 		}
572 
573 		if (wait_for_completion_timeout(comp, HZ / 10))
574 			break;
575 	}
576 
577 	return 0;
578 }
579 
580 /**
581  * devfn_to_wslot() - Convert from Linux PCI slot to Windows
582  * @devfn:	The Linux representation of PCI slot
583  *
584  * Windows uses a slightly different representation of PCI slot.
585  *
586  * Return: The Windows representation
587  */
devfn_to_wslot(int devfn)588 static u32 devfn_to_wslot(int devfn)
589 {
590 	union win_slot_encoding wslot;
591 
592 	wslot.slot = 0;
593 	wslot.bits.dev = PCI_SLOT(devfn);
594 	wslot.bits.func = PCI_FUNC(devfn);
595 
596 	return wslot.slot;
597 }
598 
599 /**
600  * wslot_to_devfn() - Convert from Windows PCI slot to Linux
601  * @wslot:	The Windows representation of PCI slot
602  *
603  * Windows uses a slightly different representation of PCI slot.
604  *
605  * Return: The Linux representation
606  */
wslot_to_devfn(u32 wslot)607 static int wslot_to_devfn(u32 wslot)
608 {
609 	union win_slot_encoding slot_no;
610 
611 	slot_no.slot = wslot;
612 	return PCI_DEVFN(slot_no.bits.dev, slot_no.bits.func);
613 }
614 
615 /*
616  * PCI Configuration Space for these root PCI buses is implemented as a pair
617  * of pages in memory-mapped I/O space.  Writing to the first page chooses
618  * the PCI function being written or read.  Once the first page has been
619  * written to, the following page maps in the entire configuration space of
620  * the function.
621  */
622 
623 /**
624  * _hv_pcifront_read_config() - Internal PCI config read
625  * @hpdev:	The PCI driver's representation of the device
626  * @where:	Offset within config space
627  * @size:	Size of the transfer
628  * @val:	Pointer to the buffer receiving the data
629  */
_hv_pcifront_read_config(struct hv_pci_dev * hpdev,int where,int size,u32 * val)630 static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where,
631 				     int size, u32 *val)
632 {
633 	unsigned long flags;
634 	void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
635 
636 	/*
637 	 * If the attempt is to read the IDs or the ROM BAR, simulate that.
638 	 */
639 	if (where + size <= PCI_COMMAND) {
640 		memcpy(val, ((u8 *)&hpdev->desc.v_id) + where, size);
641 	} else if (where >= PCI_CLASS_REVISION && where + size <=
642 		   PCI_CACHE_LINE_SIZE) {
643 		memcpy(val, ((u8 *)&hpdev->desc.rev) + where -
644 		       PCI_CLASS_REVISION, size);
645 	} else if (where >= PCI_SUBSYSTEM_VENDOR_ID && where + size <=
646 		   PCI_ROM_ADDRESS) {
647 		memcpy(val, (u8 *)&hpdev->desc.subsystem_id + where -
648 		       PCI_SUBSYSTEM_VENDOR_ID, size);
649 	} else if (where >= PCI_ROM_ADDRESS && where + size <=
650 		   PCI_CAPABILITY_LIST) {
651 		/* ROM BARs are unimplemented */
652 		*val = 0;
653 	} else if (where >= PCI_INTERRUPT_LINE && where + size <=
654 		   PCI_INTERRUPT_PIN) {
655 		/*
656 		 * Interrupt Line and Interrupt PIN are hard-wired to zero
657 		 * because this front-end only supports message-signaled
658 		 * interrupts.
659 		 */
660 		*val = 0;
661 	} else if (where + size <= CFG_PAGE_SIZE) {
662 		spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
663 		/* Choose the function to be read. (See comment above) */
664 		writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
665 		/* Make sure the function was chosen before we start reading. */
666 		mb();
667 		/* Read from that function's config space. */
668 		switch (size) {
669 		case 1:
670 			*val = readb(addr);
671 			break;
672 		case 2:
673 			*val = readw(addr);
674 			break;
675 		default:
676 			*val = readl(addr);
677 			break;
678 		}
679 		/*
680 		 * Make sure the read was done before we release the spinlock
681 		 * allowing consecutive reads/writes.
682 		 */
683 		mb();
684 		spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
685 	} else {
686 		dev_err(&hpdev->hbus->hdev->device,
687 			"Attempt to read beyond a function's config space.\n");
688 	}
689 }
690 
hv_pcifront_get_vendor_id(struct hv_pci_dev * hpdev)691 static u16 hv_pcifront_get_vendor_id(struct hv_pci_dev *hpdev)
692 {
693 	u16 ret;
694 	unsigned long flags;
695 	void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET +
696 			     PCI_VENDOR_ID;
697 
698 	spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
699 
700 	/* Choose the function to be read. (See comment above) */
701 	writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
702 	/* Make sure the function was chosen before we start reading. */
703 	mb();
704 	/* Read from that function's config space. */
705 	ret = readw(addr);
706 	/*
707 	 * mb() is not required here, because the spin_unlock_irqrestore()
708 	 * is a barrier.
709 	 */
710 
711 	spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
712 
713 	return ret;
714 }
715 
716 /**
717  * _hv_pcifront_write_config() - Internal PCI config write
718  * @hpdev:	The PCI driver's representation of the device
719  * @where:	Offset within config space
720  * @size:	Size of the transfer
721  * @val:	The data being transferred
722  */
_hv_pcifront_write_config(struct hv_pci_dev * hpdev,int where,int size,u32 val)723 static void _hv_pcifront_write_config(struct hv_pci_dev *hpdev, int where,
724 				      int size, u32 val)
725 {
726 	unsigned long flags;
727 	void __iomem *addr = hpdev->hbus->cfg_addr + CFG_PAGE_OFFSET + where;
728 
729 	if (where >= PCI_SUBSYSTEM_VENDOR_ID &&
730 	    where + size <= PCI_CAPABILITY_LIST) {
731 		/* SSIDs and ROM BARs are read-only */
732 	} else if (where >= PCI_COMMAND && where + size <= CFG_PAGE_SIZE) {
733 		spin_lock_irqsave(&hpdev->hbus->config_lock, flags);
734 		/* Choose the function to be written. (See comment above) */
735 		writel(hpdev->desc.win_slot.slot, hpdev->hbus->cfg_addr);
736 		/* Make sure the function was chosen before we start writing. */
737 		wmb();
738 		/* Write to that function's config space. */
739 		switch (size) {
740 		case 1:
741 			writeb(val, addr);
742 			break;
743 		case 2:
744 			writew(val, addr);
745 			break;
746 		default:
747 			writel(val, addr);
748 			break;
749 		}
750 		/*
751 		 * Make sure the write was done before we release the spinlock
752 		 * allowing consecutive reads/writes.
753 		 */
754 		mb();
755 		spin_unlock_irqrestore(&hpdev->hbus->config_lock, flags);
756 	} else {
757 		dev_err(&hpdev->hbus->hdev->device,
758 			"Attempt to write beyond a function's config space.\n");
759 	}
760 }
761 
762 /**
763  * hv_pcifront_read_config() - Read configuration space
764  * @bus: PCI Bus structure
765  * @devfn: Device/function
766  * @where: Offset from base
767  * @size: Byte/word/dword
768  * @val: Value to be read
769  *
770  * Return: PCIBIOS_SUCCESSFUL on success
771  *	   PCIBIOS_DEVICE_NOT_FOUND on failure
772  */
hv_pcifront_read_config(struct pci_bus * bus,unsigned int devfn,int where,int size,u32 * val)773 static int hv_pcifront_read_config(struct pci_bus *bus, unsigned int devfn,
774 				   int where, int size, u32 *val)
775 {
776 	struct hv_pcibus_device *hbus =
777 		container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
778 	struct hv_pci_dev *hpdev;
779 
780 	hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
781 	if (!hpdev)
782 		return PCIBIOS_DEVICE_NOT_FOUND;
783 
784 	_hv_pcifront_read_config(hpdev, where, size, val);
785 
786 	put_pcichild(hpdev);
787 	return PCIBIOS_SUCCESSFUL;
788 }
789 
790 /**
791  * hv_pcifront_write_config() - Write configuration space
792  * @bus: PCI Bus structure
793  * @devfn: Device/function
794  * @where: Offset from base
795  * @size: Byte/word/dword
796  * @val: Value to be written to device
797  *
798  * Return: PCIBIOS_SUCCESSFUL on success
799  *	   PCIBIOS_DEVICE_NOT_FOUND on failure
800  */
hv_pcifront_write_config(struct pci_bus * bus,unsigned int devfn,int where,int size,u32 val)801 static int hv_pcifront_write_config(struct pci_bus *bus, unsigned int devfn,
802 				    int where, int size, u32 val)
803 {
804 	struct hv_pcibus_device *hbus =
805 	    container_of(bus->sysdata, struct hv_pcibus_device, sysdata);
806 	struct hv_pci_dev *hpdev;
807 
808 	hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(devfn));
809 	if (!hpdev)
810 		return PCIBIOS_DEVICE_NOT_FOUND;
811 
812 	_hv_pcifront_write_config(hpdev, where, size, val);
813 
814 	put_pcichild(hpdev);
815 	return PCIBIOS_SUCCESSFUL;
816 }
817 
818 /* PCIe operations */
819 static struct pci_ops hv_pcifront_ops = {
820 	.read  = hv_pcifront_read_config,
821 	.write = hv_pcifront_write_config,
822 };
823 
824 /* Interrupt management hooks */
hv_int_desc_free(struct hv_pci_dev * hpdev,struct tran_int_desc * int_desc)825 static void hv_int_desc_free(struct hv_pci_dev *hpdev,
826 			     struct tran_int_desc *int_desc)
827 {
828 	struct pci_delete_interrupt *int_pkt;
829 	struct {
830 		struct pci_packet pkt;
831 		u8 buffer[sizeof(struct pci_delete_interrupt)];
832 	} ctxt;
833 
834 	memset(&ctxt, 0, sizeof(ctxt));
835 	int_pkt = (struct pci_delete_interrupt *)&ctxt.pkt.message;
836 	int_pkt->message_type.type =
837 		PCI_DELETE_INTERRUPT_MESSAGE;
838 	int_pkt->wslot.slot = hpdev->desc.win_slot.slot;
839 	int_pkt->int_desc = *int_desc;
840 	vmbus_sendpacket(hpdev->hbus->hdev->channel, int_pkt, sizeof(*int_pkt),
841 			 (unsigned long)&ctxt.pkt, VM_PKT_DATA_INBAND, 0);
842 	kfree(int_desc);
843 }
844 
845 /**
846  * hv_msi_free() - Free the MSI.
847  * @domain:	The interrupt domain pointer
848  * @info:	Extra MSI-related context
849  * @irq:	Identifies the IRQ.
850  *
851  * The Hyper-V parent partition and hypervisor are tracking the
852  * messages that are in use, keeping the interrupt redirection
853  * table up to date.  This callback sends a message that frees
854  * the IRT entry and related tracking nonsense.
855  */
hv_msi_free(struct irq_domain * domain,struct msi_domain_info * info,unsigned int irq)856 static void hv_msi_free(struct irq_domain *domain, struct msi_domain_info *info,
857 			unsigned int irq)
858 {
859 	struct hv_pcibus_device *hbus;
860 	struct hv_pci_dev *hpdev;
861 	struct pci_dev *pdev;
862 	struct tran_int_desc *int_desc;
863 	struct irq_data *irq_data = irq_domain_get_irq_data(domain, irq);
864 	struct msi_desc *msi = irq_data_get_msi_desc(irq_data);
865 
866 	pdev = msi_desc_to_pci_dev(msi);
867 	hbus = info->data;
868 	int_desc = irq_data_get_irq_chip_data(irq_data);
869 	if (!int_desc)
870 		return;
871 
872 	irq_data->chip_data = NULL;
873 	hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
874 	if (!hpdev) {
875 		kfree(int_desc);
876 		return;
877 	}
878 
879 	hv_int_desc_free(hpdev, int_desc);
880 	put_pcichild(hpdev);
881 }
882 
hv_set_affinity(struct irq_data * data,const struct cpumask * dest,bool force)883 static int hv_set_affinity(struct irq_data *data, const struct cpumask *dest,
884 			   bool force)
885 {
886 	struct irq_data *parent = data->parent_data;
887 
888 	return parent->chip->irq_set_affinity(parent, dest, force);
889 }
890 
hv_irq_mask(struct irq_data * data)891 static void hv_irq_mask(struct irq_data *data)
892 {
893 	pci_msi_mask_irq(data);
894 }
895 
896 /**
897  * hv_irq_unmask() - "Unmask" the IRQ by setting its current
898  * affinity.
899  * @data:	Describes the IRQ
900  *
901  * Build new a destination for the MSI and make a hypercall to
902  * update the Interrupt Redirection Table. "Device Logical ID"
903  * is built out of this PCI bus's instance GUID and the function
904  * number of the device.
905  */
hv_irq_unmask(struct irq_data * data)906 static void hv_irq_unmask(struct irq_data *data)
907 {
908 	struct msi_desc *msi_desc = irq_data_get_msi_desc(data);
909 	struct irq_cfg *cfg = irqd_cfg(data);
910 	struct retarget_msi_interrupt *params;
911 	struct hv_pcibus_device *hbus;
912 	struct cpumask *dest;
913 	struct pci_bus *pbus;
914 	struct pci_dev *pdev;
915 	unsigned long flags;
916 	u32 var_size = 0;
917 	int cpu_vmbus;
918 	int cpu;
919 	u64 res;
920 
921 	dest = irq_data_get_effective_affinity_mask(data);
922 	pdev = msi_desc_to_pci_dev(msi_desc);
923 	pbus = pdev->bus;
924 	hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
925 
926 	spin_lock_irqsave(&hbus->retarget_msi_interrupt_lock, flags);
927 
928 	params = &hbus->retarget_msi_interrupt_params;
929 	memset(params, 0, sizeof(*params));
930 	params->partition_id = HV_PARTITION_ID_SELF;
931 	params->int_entry.source = 1; /* MSI(-X) */
932 	params->int_entry.address = msi_desc->msg.address_lo;
933 	params->int_entry.data = msi_desc->msg.data;
934 	params->device_id = (hbus->hdev->dev_instance.b[5] << 24) |
935 			   (hbus->hdev->dev_instance.b[4] << 16) |
936 			   (hbus->hdev->dev_instance.b[7] << 8) |
937 			   (hbus->hdev->dev_instance.b[6] & 0xf8) |
938 			   PCI_FUNC(pdev->devfn);
939 	params->int_target.vector = cfg->vector;
940 
941 	/*
942 	 * Honoring apic->irq_delivery_mode set to dest_Fixed by
943 	 * setting the HV_DEVICE_INTERRUPT_TARGET_MULTICAST flag results in a
944 	 * spurious interrupt storm. Not doing so does not seem to have a
945 	 * negative effect (yet?).
946 	 */
947 
948 	if (pci_protocol_version >= PCI_PROTOCOL_VERSION_1_2) {
949 		/*
950 		 * PCI_PROTOCOL_VERSION_1_2 supports the VP_SET version of the
951 		 * HVCALL_RETARGET_INTERRUPT hypercall, which also coincides
952 		 * with >64 VP support.
953 		 * ms_hyperv.hints & HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED
954 		 * is not sufficient for this hypercall.
955 		 */
956 		params->int_target.flags |=
957 			HV_DEVICE_INTERRUPT_TARGET_PROCESSOR_SET;
958 		params->int_target.vp_set.valid_banks =
959 			(1ull << HV_VP_SET_BANK_COUNT_MAX) - 1;
960 
961 		/*
962 		 * var-sized hypercall, var-size starts after vp_mask (thus
963 		 * vp_set.format does not count, but vp_set.valid_banks does).
964 		 */
965 		var_size = 1 + HV_VP_SET_BANK_COUNT_MAX;
966 
967 		for_each_cpu_and(cpu, dest, cpu_online_mask) {
968 			cpu_vmbus = hv_cpu_number_to_vp_number(cpu);
969 
970 			if (cpu_vmbus >= HV_VP_SET_BANK_COUNT_MAX * 64) {
971 				dev_err(&hbus->hdev->device,
972 					"too high CPU %d", cpu_vmbus);
973 				res = 1;
974 				goto exit_unlock;
975 			}
976 
977 			params->int_target.vp_set.masks[cpu_vmbus / 64] |=
978 				(1ULL << (cpu_vmbus & 63));
979 		}
980 	} else {
981 		for_each_cpu_and(cpu, dest, cpu_online_mask) {
982 			params->int_target.vp_mask |=
983 				(1ULL << hv_cpu_number_to_vp_number(cpu));
984 		}
985 	}
986 
987 	res = hv_do_hypercall(HVCALL_RETARGET_INTERRUPT | (var_size << 17),
988 			      params, NULL);
989 
990 exit_unlock:
991 	spin_unlock_irqrestore(&hbus->retarget_msi_interrupt_lock, flags);
992 
993 	if (res) {
994 		dev_err(&hbus->hdev->device,
995 			"%s() failed: %#llx", __func__, res);
996 		return;
997 	}
998 
999 	pci_msi_unmask_irq(data);
1000 }
1001 
1002 struct compose_comp_ctxt {
1003 	struct hv_pci_compl comp_pkt;
1004 	struct tran_int_desc int_desc;
1005 };
1006 
hv_pci_compose_compl(void * context,struct pci_response * resp,int resp_packet_size)1007 static void hv_pci_compose_compl(void *context, struct pci_response *resp,
1008 				 int resp_packet_size)
1009 {
1010 	struct compose_comp_ctxt *comp_pkt = context;
1011 	struct pci_create_int_response *int_resp =
1012 		(struct pci_create_int_response *)resp;
1013 
1014 	comp_pkt->comp_pkt.completion_status = resp->status;
1015 	comp_pkt->int_desc = int_resp->int_desc;
1016 	complete(&comp_pkt->comp_pkt.host_event);
1017 }
1018 
hv_compose_msi_req_v1(struct pci_create_interrupt * int_pkt,struct cpumask * affinity,u32 slot,u8 vector)1019 static u32 hv_compose_msi_req_v1(
1020 	struct pci_create_interrupt *int_pkt, struct cpumask *affinity,
1021 	u32 slot, u8 vector)
1022 {
1023 	int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE;
1024 	int_pkt->wslot.slot = slot;
1025 	int_pkt->int_desc.vector = vector;
1026 	int_pkt->int_desc.vector_count = 1;
1027 	int_pkt->int_desc.delivery_mode = dest_Fixed;
1028 
1029 	/*
1030 	 * Create MSI w/ dummy vCPU set, overwritten by subsequent retarget in
1031 	 * hv_irq_unmask().
1032 	 */
1033 	int_pkt->int_desc.cpu_mask = CPU_AFFINITY_ALL;
1034 
1035 	return sizeof(*int_pkt);
1036 }
1037 
hv_compose_msi_req_v2(struct pci_create_interrupt2 * int_pkt,struct cpumask * affinity,u32 slot,u8 vector)1038 static u32 hv_compose_msi_req_v2(
1039 	struct pci_create_interrupt2 *int_pkt, struct cpumask *affinity,
1040 	u32 slot, u8 vector)
1041 {
1042 	int cpu;
1043 
1044 	int_pkt->message_type.type = PCI_CREATE_INTERRUPT_MESSAGE2;
1045 	int_pkt->wslot.slot = slot;
1046 	int_pkt->int_desc.vector = vector;
1047 	int_pkt->int_desc.vector_count = 1;
1048 	int_pkt->int_desc.delivery_mode = dest_Fixed;
1049 
1050 	/*
1051 	 * Create MSI w/ dummy vCPU set targeting just one vCPU, overwritten
1052 	 * by subsequent retarget in hv_irq_unmask().
1053 	 */
1054 	cpu = cpumask_first_and(affinity, cpu_online_mask);
1055 	int_pkt->int_desc.processor_array[0] =
1056 		hv_cpu_number_to_vp_number(cpu);
1057 	int_pkt->int_desc.processor_count = 1;
1058 
1059 	return sizeof(*int_pkt);
1060 }
1061 
1062 /**
1063  * hv_compose_msi_msg() - Supplies a valid MSI address/data
1064  * @data:	Everything about this MSI
1065  * @msg:	Buffer that is filled in by this function
1066  *
1067  * This function unpacks the IRQ looking for target CPU set, IDT
1068  * vector and mode and sends a message to the parent partition
1069  * asking for a mapping for that tuple in this partition.  The
1070  * response supplies a data value and address to which that data
1071  * should be written to trigger that interrupt.
1072  */
hv_compose_msi_msg(struct irq_data * data,struct msi_msg * msg)1073 static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
1074 {
1075 	struct irq_cfg *cfg = irqd_cfg(data);
1076 	struct hv_pcibus_device *hbus;
1077 	struct hv_pci_dev *hpdev;
1078 	struct pci_bus *pbus;
1079 	struct pci_dev *pdev;
1080 	struct cpumask *dest;
1081 	unsigned long flags;
1082 	struct compose_comp_ctxt comp;
1083 	struct tran_int_desc *int_desc;
1084 	struct {
1085 		struct pci_packet pci_pkt;
1086 		union {
1087 			struct pci_create_interrupt v1;
1088 			struct pci_create_interrupt2 v2;
1089 		} int_pkts;
1090 	} __packed ctxt;
1091 
1092 	u32 size;
1093 	int ret;
1094 
1095 	pdev = msi_desc_to_pci_dev(irq_data_get_msi_desc(data));
1096 	dest = irq_data_get_effective_affinity_mask(data);
1097 	pbus = pdev->bus;
1098 	hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata);
1099 	hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn));
1100 	if (!hpdev)
1101 		goto return_null_message;
1102 
1103 	/* Free any previous message that might have already been composed. */
1104 	if (data->chip_data) {
1105 		int_desc = data->chip_data;
1106 		data->chip_data = NULL;
1107 		hv_int_desc_free(hpdev, int_desc);
1108 	}
1109 
1110 	int_desc = kzalloc(sizeof(*int_desc), GFP_ATOMIC);
1111 	if (!int_desc)
1112 		goto drop_reference;
1113 
1114 	memset(&ctxt, 0, sizeof(ctxt));
1115 	init_completion(&comp.comp_pkt.host_event);
1116 	ctxt.pci_pkt.completion_func = hv_pci_compose_compl;
1117 	ctxt.pci_pkt.compl_ctxt = &comp;
1118 
1119 	switch (pci_protocol_version) {
1120 	case PCI_PROTOCOL_VERSION_1_1:
1121 		size = hv_compose_msi_req_v1(&ctxt.int_pkts.v1,
1122 					dest,
1123 					hpdev->desc.win_slot.slot,
1124 					cfg->vector);
1125 		break;
1126 
1127 	case PCI_PROTOCOL_VERSION_1_2:
1128 		size = hv_compose_msi_req_v2(&ctxt.int_pkts.v2,
1129 					dest,
1130 					hpdev->desc.win_slot.slot,
1131 					cfg->vector);
1132 		break;
1133 
1134 	default:
1135 		/* As we only negotiate protocol versions known to this driver,
1136 		 * this path should never hit. However, this is it not a hot
1137 		 * path so we print a message to aid future updates.
1138 		 */
1139 		dev_err(&hbus->hdev->device,
1140 			"Unexpected vPCI protocol, update driver.");
1141 		goto free_int_desc;
1142 	}
1143 
1144 	ret = vmbus_sendpacket(hpdev->hbus->hdev->channel, &ctxt.int_pkts,
1145 			       size, (unsigned long)&ctxt.pci_pkt,
1146 			       VM_PKT_DATA_INBAND,
1147 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1148 	if (ret) {
1149 		dev_err(&hbus->hdev->device,
1150 			"Sending request for interrupt failed: 0x%x",
1151 			comp.comp_pkt.completion_status);
1152 		goto free_int_desc;
1153 	}
1154 
1155 	/*
1156 	 * Since this function is called with IRQ locks held, can't
1157 	 * do normal wait for completion; instead poll.
1158 	 */
1159 	while (!try_wait_for_completion(&comp.comp_pkt.host_event)) {
1160 		/* 0xFFFF means an invalid PCI VENDOR ID. */
1161 		if (hv_pcifront_get_vendor_id(hpdev) == 0xFFFF) {
1162 			dev_err_once(&hbus->hdev->device,
1163 				     "the device has gone\n");
1164 			goto free_int_desc;
1165 		}
1166 
1167 		/*
1168 		 * When the higher level interrupt code calls us with
1169 		 * interrupt disabled, we must poll the channel by calling
1170 		 * the channel callback directly when channel->target_cpu is
1171 		 * the current CPU. When the higher level interrupt code
1172 		 * calls us with interrupt enabled, let's add the
1173 		 * local_irq_save()/restore() to avoid race:
1174 		 * hv_pci_onchannelcallback() can also run in tasklet.
1175 		 */
1176 		local_irq_save(flags);
1177 
1178 		if (hbus->hdev->channel->target_cpu == smp_processor_id())
1179 			hv_pci_onchannelcallback(hbus);
1180 
1181 		local_irq_restore(flags);
1182 
1183 		if (hpdev->state == hv_pcichild_ejecting) {
1184 			dev_err_once(&hbus->hdev->device,
1185 				     "the device is being ejected\n");
1186 			goto free_int_desc;
1187 		}
1188 
1189 		udelay(100);
1190 	}
1191 
1192 	if (comp.comp_pkt.completion_status < 0) {
1193 		dev_err(&hbus->hdev->device,
1194 			"Request for interrupt failed: 0x%x",
1195 			comp.comp_pkt.completion_status);
1196 		goto free_int_desc;
1197 	}
1198 
1199 	/*
1200 	 * Record the assignment so that this can be unwound later. Using
1201 	 * irq_set_chip_data() here would be appropriate, but the lock it takes
1202 	 * is already held.
1203 	 */
1204 	*int_desc = comp.int_desc;
1205 	data->chip_data = int_desc;
1206 
1207 	/* Pass up the result. */
1208 	msg->address_hi = comp.int_desc.address >> 32;
1209 	msg->address_lo = comp.int_desc.address & 0xffffffff;
1210 	msg->data = comp.int_desc.data;
1211 
1212 	put_pcichild(hpdev);
1213 	return;
1214 
1215 free_int_desc:
1216 	kfree(int_desc);
1217 drop_reference:
1218 	put_pcichild(hpdev);
1219 return_null_message:
1220 	msg->address_hi = 0;
1221 	msg->address_lo = 0;
1222 	msg->data = 0;
1223 }
1224 
1225 /* HW Interrupt Chip Descriptor */
1226 static struct irq_chip hv_msi_irq_chip = {
1227 	.name			= "Hyper-V PCIe MSI",
1228 	.irq_compose_msi_msg	= hv_compose_msi_msg,
1229 	.irq_set_affinity	= hv_set_affinity,
1230 	.irq_ack		= irq_chip_ack_parent,
1231 	.irq_mask		= hv_irq_mask,
1232 	.irq_unmask		= hv_irq_unmask,
1233 };
1234 
hv_msi_domain_ops_get_hwirq(struct msi_domain_info * info,msi_alloc_info_t * arg)1235 static irq_hw_number_t hv_msi_domain_ops_get_hwirq(struct msi_domain_info *info,
1236 						   msi_alloc_info_t *arg)
1237 {
1238 	return arg->msi_hwirq;
1239 }
1240 
1241 static struct msi_domain_ops hv_msi_ops = {
1242 	.get_hwirq	= hv_msi_domain_ops_get_hwirq,
1243 	.msi_prepare	= pci_msi_prepare,
1244 	.set_desc	= pci_msi_set_desc,
1245 	.msi_free	= hv_msi_free,
1246 };
1247 
1248 /**
1249  * hv_pcie_init_irq_domain() - Initialize IRQ domain
1250  * @hbus:	The root PCI bus
1251  *
1252  * This function creates an IRQ domain which will be used for
1253  * interrupts from devices that have been passed through.  These
1254  * devices only support MSI and MSI-X, not line-based interrupts
1255  * or simulations of line-based interrupts through PCIe's
1256  * fabric-layer messages.  Because interrupts are remapped, we
1257  * can support multi-message MSI here.
1258  *
1259  * Return: '0' on success and error value on failure
1260  */
hv_pcie_init_irq_domain(struct hv_pcibus_device * hbus)1261 static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus)
1262 {
1263 	hbus->msi_info.chip = &hv_msi_irq_chip;
1264 	hbus->msi_info.ops = &hv_msi_ops;
1265 	hbus->msi_info.flags = (MSI_FLAG_USE_DEF_DOM_OPS |
1266 		MSI_FLAG_USE_DEF_CHIP_OPS | MSI_FLAG_MULTI_PCI_MSI |
1267 		MSI_FLAG_PCI_MSIX);
1268 	hbus->msi_info.handler = handle_edge_irq;
1269 	hbus->msi_info.handler_name = "edge";
1270 	hbus->msi_info.data = hbus;
1271 	hbus->irq_domain = pci_msi_create_irq_domain(hbus->sysdata.fwnode,
1272 						     &hbus->msi_info,
1273 						     x86_vector_domain);
1274 	if (!hbus->irq_domain) {
1275 		dev_err(&hbus->hdev->device,
1276 			"Failed to build an MSI IRQ domain\n");
1277 		return -ENODEV;
1278 	}
1279 
1280 	return 0;
1281 }
1282 
1283 /**
1284  * get_bar_size() - Get the address space consumed by a BAR
1285  * @bar_val:	Value that a BAR returned after -1 was written
1286  *              to it.
1287  *
1288  * This function returns the size of the BAR, rounded up to 1
1289  * page.  It has to be rounded up because the hypervisor's page
1290  * table entry that maps the BAR into the VM can't specify an
1291  * offset within a page.  The invariant is that the hypervisor
1292  * must place any BARs of smaller than page length at the
1293  * beginning of a page.
1294  *
1295  * Return:	Size in bytes of the consumed MMIO space.
1296  */
get_bar_size(u64 bar_val)1297 static u64 get_bar_size(u64 bar_val)
1298 {
1299 	return round_up((1 + ~(bar_val & PCI_BASE_ADDRESS_MEM_MASK)),
1300 			PAGE_SIZE);
1301 }
1302 
1303 /**
1304  * survey_child_resources() - Total all MMIO requirements
1305  * @hbus:	Root PCI bus, as understood by this driver
1306  */
survey_child_resources(struct hv_pcibus_device * hbus)1307 static void survey_child_resources(struct hv_pcibus_device *hbus)
1308 {
1309 	struct hv_pci_dev *hpdev;
1310 	resource_size_t bar_size = 0;
1311 	unsigned long flags;
1312 	struct completion *event;
1313 	u64 bar_val;
1314 	int i;
1315 
1316 	/* If nobody is waiting on the answer, don't compute it. */
1317 	event = xchg(&hbus->survey_event, NULL);
1318 	if (!event)
1319 		return;
1320 
1321 	/* If the answer has already been computed, go with it. */
1322 	if (hbus->low_mmio_space || hbus->high_mmio_space) {
1323 		complete(event);
1324 		return;
1325 	}
1326 
1327 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1328 
1329 	/*
1330 	 * Due to an interesting quirk of the PCI spec, all memory regions
1331 	 * for a child device are a power of 2 in size and aligned in memory,
1332 	 * so it's sufficient to just add them up without tracking alignment.
1333 	 */
1334 	list_for_each_entry(hpdev, &hbus->children, list_entry) {
1335 		for (i = 0; i < 6; i++) {
1336 			if (hpdev->probed_bar[i] & PCI_BASE_ADDRESS_SPACE_IO)
1337 				dev_err(&hbus->hdev->device,
1338 					"There's an I/O BAR in this list!\n");
1339 
1340 			if (hpdev->probed_bar[i] != 0) {
1341 				/*
1342 				 * A probed BAR has all the upper bits set that
1343 				 * can be changed.
1344 				 */
1345 
1346 				bar_val = hpdev->probed_bar[i];
1347 				if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1348 					bar_val |=
1349 					((u64)hpdev->probed_bar[++i] << 32);
1350 				else
1351 					bar_val |= 0xffffffff00000000ULL;
1352 
1353 				bar_size = get_bar_size(bar_val);
1354 
1355 				if (bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64)
1356 					hbus->high_mmio_space += bar_size;
1357 				else
1358 					hbus->low_mmio_space += bar_size;
1359 			}
1360 		}
1361 	}
1362 
1363 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1364 	complete(event);
1365 }
1366 
1367 /**
1368  * prepopulate_bars() - Fill in BARs with defaults
1369  * @hbus:	Root PCI bus, as understood by this driver
1370  *
1371  * The core PCI driver code seems much, much happier if the BARs
1372  * for a device have values upon first scan. So fill them in.
1373  * The algorithm below works down from large sizes to small,
1374  * attempting to pack the assignments optimally. The assumption,
1375  * enforced in other parts of the code, is that the beginning of
1376  * the memory-mapped I/O space will be aligned on the largest
1377  * BAR size.
1378  */
prepopulate_bars(struct hv_pcibus_device * hbus)1379 static void prepopulate_bars(struct hv_pcibus_device *hbus)
1380 {
1381 	resource_size_t high_size = 0;
1382 	resource_size_t low_size = 0;
1383 	resource_size_t high_base = 0;
1384 	resource_size_t low_base = 0;
1385 	resource_size_t bar_size;
1386 	struct hv_pci_dev *hpdev;
1387 	unsigned long flags;
1388 	u64 bar_val;
1389 	u32 command;
1390 	bool high;
1391 	int i;
1392 
1393 	if (hbus->low_mmio_space) {
1394 		low_size = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
1395 		low_base = hbus->low_mmio_res->start;
1396 	}
1397 
1398 	if (hbus->high_mmio_space) {
1399 		high_size = 1ULL <<
1400 			(63 - __builtin_clzll(hbus->high_mmio_space));
1401 		high_base = hbus->high_mmio_res->start;
1402 	}
1403 
1404 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1405 
1406 	/* Pick addresses for the BARs. */
1407 	do {
1408 		list_for_each_entry(hpdev, &hbus->children, list_entry) {
1409 			for (i = 0; i < 6; i++) {
1410 				bar_val = hpdev->probed_bar[i];
1411 				if (bar_val == 0)
1412 					continue;
1413 				high = bar_val & PCI_BASE_ADDRESS_MEM_TYPE_64;
1414 				if (high) {
1415 					bar_val |=
1416 						((u64)hpdev->probed_bar[i + 1]
1417 						 << 32);
1418 				} else {
1419 					bar_val |= 0xffffffffULL << 32;
1420 				}
1421 				bar_size = get_bar_size(bar_val);
1422 				if (high) {
1423 					if (high_size != bar_size) {
1424 						i++;
1425 						continue;
1426 					}
1427 					_hv_pcifront_write_config(hpdev,
1428 						PCI_BASE_ADDRESS_0 + (4 * i),
1429 						4,
1430 						(u32)(high_base & 0xffffff00));
1431 					i++;
1432 					_hv_pcifront_write_config(hpdev,
1433 						PCI_BASE_ADDRESS_0 + (4 * i),
1434 						4, (u32)(high_base >> 32));
1435 					high_base += bar_size;
1436 				} else {
1437 					if (low_size != bar_size)
1438 						continue;
1439 					_hv_pcifront_write_config(hpdev,
1440 						PCI_BASE_ADDRESS_0 + (4 * i),
1441 						4,
1442 						(u32)(low_base & 0xffffff00));
1443 					low_base += bar_size;
1444 				}
1445 			}
1446 			if (high_size <= 1 && low_size <= 1) {
1447 				/* Set the memory enable bit. */
1448 				_hv_pcifront_read_config(hpdev, PCI_COMMAND, 2,
1449 							 &command);
1450 				command |= PCI_COMMAND_MEMORY;
1451 				_hv_pcifront_write_config(hpdev, PCI_COMMAND, 2,
1452 							  command);
1453 				break;
1454 			}
1455 		}
1456 
1457 		high_size >>= 1;
1458 		low_size >>= 1;
1459 	}  while (high_size || low_size);
1460 
1461 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1462 }
1463 
1464 /*
1465  * Assign entries in sysfs pci slot directory.
1466  *
1467  * Note that this function does not need to lock the children list
1468  * because it is called from pci_devices_present_work which
1469  * is serialized with hv_eject_device_work because they are on the
1470  * same ordered workqueue. Therefore hbus->children list will not change
1471  * even when pci_create_slot sleeps.
1472  */
hv_pci_assign_slots(struct hv_pcibus_device * hbus)1473 static void hv_pci_assign_slots(struct hv_pcibus_device *hbus)
1474 {
1475 	struct hv_pci_dev *hpdev;
1476 	char name[SLOT_NAME_SIZE];
1477 	int slot_nr;
1478 
1479 	list_for_each_entry(hpdev, &hbus->children, list_entry) {
1480 		if (hpdev->pci_slot)
1481 			continue;
1482 
1483 		slot_nr = PCI_SLOT(wslot_to_devfn(hpdev->desc.win_slot.slot));
1484 		snprintf(name, SLOT_NAME_SIZE, "%u", hpdev->desc.ser);
1485 		hpdev->pci_slot = pci_create_slot(hbus->pci_bus, slot_nr,
1486 					  name, NULL);
1487 		if (IS_ERR(hpdev->pci_slot)) {
1488 			pr_warn("pci_create slot %s failed\n", name);
1489 			hpdev->pci_slot = NULL;
1490 		}
1491 	}
1492 }
1493 
1494 /*
1495  * Remove entries in sysfs pci slot directory.
1496  */
hv_pci_remove_slots(struct hv_pcibus_device * hbus)1497 static void hv_pci_remove_slots(struct hv_pcibus_device *hbus)
1498 {
1499 	struct hv_pci_dev *hpdev;
1500 
1501 	list_for_each_entry(hpdev, &hbus->children, list_entry) {
1502 		if (!hpdev->pci_slot)
1503 			continue;
1504 		pci_destroy_slot(hpdev->pci_slot);
1505 		hpdev->pci_slot = NULL;
1506 	}
1507 }
1508 
1509 /**
1510  * create_root_hv_pci_bus() - Expose a new root PCI bus
1511  * @hbus:	Root PCI bus, as understood by this driver
1512  *
1513  * Return: 0 on success, -errno on failure
1514  */
create_root_hv_pci_bus(struct hv_pcibus_device * hbus)1515 static int create_root_hv_pci_bus(struct hv_pcibus_device *hbus)
1516 {
1517 	/* Register the device */
1518 	hbus->pci_bus = pci_create_root_bus(&hbus->hdev->device,
1519 					    0, /* bus number is always zero */
1520 					    &hv_pcifront_ops,
1521 					    &hbus->sysdata,
1522 					    &hbus->resources_for_children);
1523 	if (!hbus->pci_bus)
1524 		return -ENODEV;
1525 
1526 	hbus->pci_bus->msi = &hbus->msi_chip;
1527 	hbus->pci_bus->msi->dev = &hbus->hdev->device;
1528 
1529 	pci_lock_rescan_remove();
1530 	pci_scan_child_bus(hbus->pci_bus);
1531 	pci_bus_assign_resources(hbus->pci_bus);
1532 	hv_pci_assign_slots(hbus);
1533 	pci_bus_add_devices(hbus->pci_bus);
1534 	pci_unlock_rescan_remove();
1535 	hbus->state = hv_pcibus_installed;
1536 	return 0;
1537 }
1538 
1539 struct q_res_req_compl {
1540 	struct completion host_event;
1541 	struct hv_pci_dev *hpdev;
1542 };
1543 
1544 /**
1545  * q_resource_requirements() - Query Resource Requirements
1546  * @context:		The completion context.
1547  * @resp:		The response that came from the host.
1548  * @resp_packet_size:	The size in bytes of resp.
1549  *
1550  * This function is invoked on completion of a Query Resource
1551  * Requirements packet.
1552  */
q_resource_requirements(void * context,struct pci_response * resp,int resp_packet_size)1553 static void q_resource_requirements(void *context, struct pci_response *resp,
1554 				    int resp_packet_size)
1555 {
1556 	struct q_res_req_compl *completion = context;
1557 	struct pci_q_res_req_response *q_res_req =
1558 		(struct pci_q_res_req_response *)resp;
1559 	int i;
1560 
1561 	if (resp->status < 0) {
1562 		dev_err(&completion->hpdev->hbus->hdev->device,
1563 			"query resource requirements failed: %x\n",
1564 			resp->status);
1565 	} else {
1566 		for (i = 0; i < 6; i++) {
1567 			completion->hpdev->probed_bar[i] =
1568 				q_res_req->probed_bar[i];
1569 		}
1570 	}
1571 
1572 	complete(&completion->host_event);
1573 }
1574 
1575 /**
1576  * new_pcichild_device() - Create a new child device
1577  * @hbus:	The internal struct tracking this root PCI bus.
1578  * @desc:	The information supplied so far from the host
1579  *              about the device.
1580  *
1581  * This function creates the tracking structure for a new child
1582  * device and kicks off the process of figuring out what it is.
1583  *
1584  * Return: Pointer to the new tracking struct
1585  */
new_pcichild_device(struct hv_pcibus_device * hbus,struct pci_function_description * desc)1586 static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
1587 		struct pci_function_description *desc)
1588 {
1589 	struct hv_pci_dev *hpdev;
1590 	struct pci_child_message *res_req;
1591 	struct q_res_req_compl comp_pkt;
1592 	struct {
1593 		struct pci_packet init_packet;
1594 		u8 buffer[sizeof(struct pci_child_message)];
1595 	} pkt;
1596 	unsigned long flags;
1597 	int ret;
1598 
1599 	hpdev = kzalloc(sizeof(*hpdev), GFP_KERNEL);
1600 	if (!hpdev)
1601 		return NULL;
1602 
1603 	hpdev->hbus = hbus;
1604 
1605 	memset(&pkt, 0, sizeof(pkt));
1606 	init_completion(&comp_pkt.host_event);
1607 	comp_pkt.hpdev = hpdev;
1608 	pkt.init_packet.compl_ctxt = &comp_pkt;
1609 	pkt.init_packet.completion_func = q_resource_requirements;
1610 	res_req = (struct pci_child_message *)&pkt.init_packet.message;
1611 	res_req->message_type.type = PCI_QUERY_RESOURCE_REQUIREMENTS;
1612 	res_req->wslot.slot = desc->win_slot.slot;
1613 
1614 	ret = vmbus_sendpacket(hbus->hdev->channel, res_req,
1615 			       sizeof(struct pci_child_message),
1616 			       (unsigned long)&pkt.init_packet,
1617 			       VM_PKT_DATA_INBAND,
1618 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1619 	if (ret)
1620 		goto error;
1621 
1622 	if (wait_for_response(hbus->hdev, &comp_pkt.host_event))
1623 		goto error;
1624 
1625 	hpdev->desc = *desc;
1626 	refcount_set(&hpdev->refs, 1);
1627 	get_pcichild(hpdev);
1628 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1629 
1630 	list_add_tail(&hpdev->list_entry, &hbus->children);
1631 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1632 	return hpdev;
1633 
1634 error:
1635 	kfree(hpdev);
1636 	return NULL;
1637 }
1638 
1639 /**
1640  * get_pcichild_wslot() - Find device from slot
1641  * @hbus:	Root PCI bus, as understood by this driver
1642  * @wslot:	Location on the bus
1643  *
1644  * This function looks up a PCI device and returns the internal
1645  * representation of it.  It acquires a reference on it, so that
1646  * the device won't be deleted while somebody is using it.  The
1647  * caller is responsible for calling put_pcichild() to release
1648  * this reference.
1649  *
1650  * Return:	Internal representation of a PCI device
1651  */
get_pcichild_wslot(struct hv_pcibus_device * hbus,u32 wslot)1652 static struct hv_pci_dev *get_pcichild_wslot(struct hv_pcibus_device *hbus,
1653 					     u32 wslot)
1654 {
1655 	unsigned long flags;
1656 	struct hv_pci_dev *iter, *hpdev = NULL;
1657 
1658 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1659 	list_for_each_entry(iter, &hbus->children, list_entry) {
1660 		if (iter->desc.win_slot.slot == wslot) {
1661 			hpdev = iter;
1662 			get_pcichild(hpdev);
1663 			break;
1664 		}
1665 	}
1666 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1667 
1668 	return hpdev;
1669 }
1670 
1671 /**
1672  * pci_devices_present_work() - Handle new list of child devices
1673  * @work:	Work struct embedded in struct hv_dr_work
1674  *
1675  * "Bus Relations" is the Windows term for "children of this
1676  * bus."  The terminology is preserved here for people trying to
1677  * debug the interaction between Hyper-V and Linux.  This
1678  * function is called when the parent partition reports a list
1679  * of functions that should be observed under this PCI Express
1680  * port (bus).
1681  *
1682  * This function updates the list, and must tolerate being
1683  * called multiple times with the same information.  The typical
1684  * number of child devices is one, with very atypical cases
1685  * involving three or four, so the algorithms used here can be
1686  * simple and inefficient.
1687  *
1688  * It must also treat the omission of a previously observed device as
1689  * notification that the device no longer exists.
1690  *
1691  * Note that this function is serialized with hv_eject_device_work(),
1692  * because both are pushed to the ordered workqueue hbus->wq.
1693  */
pci_devices_present_work(struct work_struct * work)1694 static void pci_devices_present_work(struct work_struct *work)
1695 {
1696 	u32 child_no;
1697 	bool found;
1698 	struct pci_function_description *new_desc;
1699 	struct hv_pci_dev *hpdev;
1700 	struct hv_pcibus_device *hbus;
1701 	struct list_head removed;
1702 	struct hv_dr_work *dr_wrk;
1703 	struct hv_dr_state *dr = NULL;
1704 	unsigned long flags;
1705 
1706 	dr_wrk = container_of(work, struct hv_dr_work, wrk);
1707 	hbus = dr_wrk->bus;
1708 	kfree(dr_wrk);
1709 
1710 	INIT_LIST_HEAD(&removed);
1711 
1712 	/* Pull this off the queue and process it if it was the last one. */
1713 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1714 	while (!list_empty(&hbus->dr_list)) {
1715 		dr = list_first_entry(&hbus->dr_list, struct hv_dr_state,
1716 				      list_entry);
1717 		list_del(&dr->list_entry);
1718 
1719 		/* Throw this away if the list still has stuff in it. */
1720 		if (!list_empty(&hbus->dr_list)) {
1721 			kfree(dr);
1722 			continue;
1723 		}
1724 	}
1725 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1726 
1727 	if (!dr) {
1728 		put_hvpcibus(hbus);
1729 		return;
1730 	}
1731 
1732 	/* First, mark all existing children as reported missing. */
1733 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1734 	list_for_each_entry(hpdev, &hbus->children, list_entry) {
1735 		hpdev->reported_missing = true;
1736 	}
1737 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1738 
1739 	/* Next, add back any reported devices. */
1740 	for (child_no = 0; child_no < dr->device_count; child_no++) {
1741 		found = false;
1742 		new_desc = &dr->func[child_no];
1743 
1744 		spin_lock_irqsave(&hbus->device_list_lock, flags);
1745 		list_for_each_entry(hpdev, &hbus->children, list_entry) {
1746 			if ((hpdev->desc.win_slot.slot == new_desc->win_slot.slot) &&
1747 			    (hpdev->desc.v_id == new_desc->v_id) &&
1748 			    (hpdev->desc.d_id == new_desc->d_id) &&
1749 			    (hpdev->desc.ser == new_desc->ser)) {
1750 				hpdev->reported_missing = false;
1751 				found = true;
1752 			}
1753 		}
1754 		spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1755 
1756 		if (!found) {
1757 			hpdev = new_pcichild_device(hbus, new_desc);
1758 			if (!hpdev)
1759 				dev_err(&hbus->hdev->device,
1760 					"couldn't record a child device.\n");
1761 		}
1762 	}
1763 
1764 	/* Move missing children to a list on the stack. */
1765 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1766 	do {
1767 		found = false;
1768 		list_for_each_entry(hpdev, &hbus->children, list_entry) {
1769 			if (hpdev->reported_missing) {
1770 				found = true;
1771 				put_pcichild(hpdev);
1772 				list_move_tail(&hpdev->list_entry, &removed);
1773 				break;
1774 			}
1775 		}
1776 	} while (found);
1777 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1778 
1779 	/* Delete everything that should no longer exist. */
1780 	while (!list_empty(&removed)) {
1781 		hpdev = list_first_entry(&removed, struct hv_pci_dev,
1782 					 list_entry);
1783 		list_del(&hpdev->list_entry);
1784 
1785 		if (hpdev->pci_slot)
1786 			pci_destroy_slot(hpdev->pci_slot);
1787 
1788 		put_pcichild(hpdev);
1789 	}
1790 
1791 	switch (hbus->state) {
1792 	case hv_pcibus_installed:
1793 		/*
1794 		 * Tell the core to rescan bus
1795 		 * because there may have been changes.
1796 		 */
1797 		pci_lock_rescan_remove();
1798 		pci_scan_child_bus(hbus->pci_bus);
1799 		hv_pci_assign_slots(hbus);
1800 		pci_unlock_rescan_remove();
1801 		break;
1802 
1803 	case hv_pcibus_init:
1804 	case hv_pcibus_probed:
1805 		survey_child_resources(hbus);
1806 		break;
1807 
1808 	default:
1809 		break;
1810 	}
1811 
1812 	put_hvpcibus(hbus);
1813 	kfree(dr);
1814 }
1815 
1816 /**
1817  * hv_pci_devices_present() - Handles list of new children
1818  * @hbus:	Root PCI bus, as understood by this driver
1819  * @relations:	Packet from host listing children
1820  *
1821  * This function is invoked whenever a new list of devices for
1822  * this bus appears.
1823  */
hv_pci_devices_present(struct hv_pcibus_device * hbus,struct pci_bus_relations * relations)1824 static void hv_pci_devices_present(struct hv_pcibus_device *hbus,
1825 				   struct pci_bus_relations *relations)
1826 {
1827 	struct hv_dr_state *dr;
1828 	struct hv_dr_work *dr_wrk;
1829 	unsigned long flags;
1830 	bool pending_dr;
1831 
1832 	dr_wrk = kzalloc(sizeof(*dr_wrk), GFP_NOWAIT);
1833 	if (!dr_wrk)
1834 		return;
1835 
1836 	dr = kzalloc(offsetof(struct hv_dr_state, func) +
1837 		     (sizeof(struct pci_function_description) *
1838 		      (relations->device_count)), GFP_NOWAIT);
1839 	if (!dr)  {
1840 		kfree(dr_wrk);
1841 		return;
1842 	}
1843 
1844 	INIT_WORK(&dr_wrk->wrk, pci_devices_present_work);
1845 	dr_wrk->bus = hbus;
1846 	dr->device_count = relations->device_count;
1847 	if (dr->device_count != 0) {
1848 		memcpy(dr->func, relations->func,
1849 		       sizeof(struct pci_function_description) *
1850 		       dr->device_count);
1851 	}
1852 
1853 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1854 	/*
1855 	 * If pending_dr is true, we have already queued a work,
1856 	 * which will see the new dr. Otherwise, we need to
1857 	 * queue a new work.
1858 	 */
1859 	pending_dr = !list_empty(&hbus->dr_list);
1860 	list_add_tail(&dr->list_entry, &hbus->dr_list);
1861 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1862 
1863 	if (pending_dr) {
1864 		kfree(dr_wrk);
1865 	} else {
1866 		get_hvpcibus(hbus);
1867 		queue_work(hbus->wq, &dr_wrk->wrk);
1868 	}
1869 }
1870 
1871 /**
1872  * hv_eject_device_work() - Asynchronously handles ejection
1873  * @work:	Work struct embedded in internal device struct
1874  *
1875  * This function handles ejecting a device.  Windows will
1876  * attempt to gracefully eject a device, waiting 60 seconds to
1877  * hear back from the guest OS that this completed successfully.
1878  * If this timer expires, the device will be forcibly removed.
1879  */
hv_eject_device_work(struct work_struct * work)1880 static void hv_eject_device_work(struct work_struct *work)
1881 {
1882 	struct pci_eject_response *ejct_pkt;
1883 	struct hv_pcibus_device *hbus;
1884 	struct hv_pci_dev *hpdev;
1885 	struct pci_dev *pdev;
1886 	unsigned long flags;
1887 	int wslot;
1888 	struct {
1889 		struct pci_packet pkt;
1890 		u8 buffer[sizeof(struct pci_eject_response)];
1891 	} ctxt;
1892 
1893 	hpdev = container_of(work, struct hv_pci_dev, wrk);
1894 	hbus = hpdev->hbus;
1895 
1896 	WARN_ON(hpdev->state != hv_pcichild_ejecting);
1897 
1898 	/*
1899 	 * Ejection can come before or after the PCI bus has been set up, so
1900 	 * attempt to find it and tear down the bus state, if it exists.  This
1901 	 * must be done without constructs like pci_domain_nr(hbus->pci_bus)
1902 	 * because hbus->pci_bus may not exist yet.
1903 	 */
1904 	wslot = wslot_to_devfn(hpdev->desc.win_slot.slot);
1905 	pdev = pci_get_domain_bus_and_slot(hbus->sysdata.domain, 0, wslot);
1906 	if (pdev) {
1907 		pci_lock_rescan_remove();
1908 		pci_stop_and_remove_bus_device(pdev);
1909 		pci_dev_put(pdev);
1910 		pci_unlock_rescan_remove();
1911 	}
1912 
1913 	spin_lock_irqsave(&hbus->device_list_lock, flags);
1914 	list_del(&hpdev->list_entry);
1915 	spin_unlock_irqrestore(&hbus->device_list_lock, flags);
1916 
1917 	if (hpdev->pci_slot)
1918 		pci_destroy_slot(hpdev->pci_slot);
1919 
1920 	memset(&ctxt, 0, sizeof(ctxt));
1921 	ejct_pkt = (struct pci_eject_response *)&ctxt.pkt.message;
1922 	ejct_pkt->message_type.type = PCI_EJECTION_COMPLETE;
1923 	ejct_pkt->wslot.slot = hpdev->desc.win_slot.slot;
1924 	vmbus_sendpacket(hbus->hdev->channel, ejct_pkt,
1925 			 sizeof(*ejct_pkt), (unsigned long)&ctxt.pkt,
1926 			 VM_PKT_DATA_INBAND, 0);
1927 
1928 	/* For the get_pcichild() in hv_pci_eject_device() */
1929 	put_pcichild(hpdev);
1930 	/* For the two refs got in new_pcichild_device() */
1931 	put_pcichild(hpdev);
1932 	put_pcichild(hpdev);
1933 	/* hpdev has been freed. Do not use it any more. */
1934 
1935 	put_hvpcibus(hbus);
1936 }
1937 
1938 /**
1939  * hv_pci_eject_device() - Handles device ejection
1940  * @hpdev:	Internal device tracking struct
1941  *
1942  * This function is invoked when an ejection packet arrives.  It
1943  * just schedules work so that we don't re-enter the packet
1944  * delivery code handling the ejection.
1945  */
hv_pci_eject_device(struct hv_pci_dev * hpdev)1946 static void hv_pci_eject_device(struct hv_pci_dev *hpdev)
1947 {
1948 	hpdev->state = hv_pcichild_ejecting;
1949 	get_pcichild(hpdev);
1950 	INIT_WORK(&hpdev->wrk, hv_eject_device_work);
1951 	get_hvpcibus(hpdev->hbus);
1952 	queue_work(hpdev->hbus->wq, &hpdev->wrk);
1953 }
1954 
1955 /**
1956  * hv_pci_onchannelcallback() - Handles incoming packets
1957  * @context:	Internal bus tracking struct
1958  *
1959  * This function is invoked whenever the host sends a packet to
1960  * this channel (which is private to this root PCI bus).
1961  */
hv_pci_onchannelcallback(void * context)1962 static void hv_pci_onchannelcallback(void *context)
1963 {
1964 	const int packet_size = 0x100;
1965 	int ret;
1966 	struct hv_pcibus_device *hbus = context;
1967 	u32 bytes_recvd;
1968 	u64 req_id;
1969 	struct vmpacket_descriptor *desc;
1970 	unsigned char *buffer;
1971 	int bufferlen = packet_size;
1972 	struct pci_packet *comp_packet;
1973 	struct pci_response *response;
1974 	struct pci_incoming_message *new_message;
1975 	struct pci_bus_relations *bus_rel;
1976 	struct pci_dev_incoming *dev_message;
1977 	struct hv_pci_dev *hpdev;
1978 
1979 	buffer = kmalloc(bufferlen, GFP_ATOMIC);
1980 	if (!buffer)
1981 		return;
1982 
1983 	while (1) {
1984 		ret = vmbus_recvpacket_raw(hbus->hdev->channel, buffer,
1985 					   bufferlen, &bytes_recvd, &req_id);
1986 
1987 		if (ret == -ENOBUFS) {
1988 			kfree(buffer);
1989 			/* Handle large packet */
1990 			bufferlen = bytes_recvd;
1991 			buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
1992 			if (!buffer)
1993 				return;
1994 			continue;
1995 		}
1996 
1997 		/* Zero length indicates there are no more packets. */
1998 		if (ret || !bytes_recvd)
1999 			break;
2000 
2001 		/*
2002 		 * All incoming packets must be at least as large as a
2003 		 * response.
2004 		 */
2005 		if (bytes_recvd <= sizeof(struct pci_response))
2006 			continue;
2007 		desc = (struct vmpacket_descriptor *)buffer;
2008 
2009 		switch (desc->type) {
2010 		case VM_PKT_COMP:
2011 
2012 			/*
2013 			 * The host is trusted, and thus it's safe to interpret
2014 			 * this transaction ID as a pointer.
2015 			 */
2016 			comp_packet = (struct pci_packet *)req_id;
2017 			response = (struct pci_response *)buffer;
2018 			comp_packet->completion_func(comp_packet->compl_ctxt,
2019 						     response,
2020 						     bytes_recvd);
2021 			break;
2022 
2023 		case VM_PKT_DATA_INBAND:
2024 
2025 			new_message = (struct pci_incoming_message *)buffer;
2026 			switch (new_message->message_type.type) {
2027 			case PCI_BUS_RELATIONS:
2028 
2029 				bus_rel = (struct pci_bus_relations *)buffer;
2030 				if (bytes_recvd <
2031 				    offsetof(struct pci_bus_relations, func) +
2032 				    (sizeof(struct pci_function_description) *
2033 				     (bus_rel->device_count))) {
2034 					dev_err(&hbus->hdev->device,
2035 						"bus relations too small\n");
2036 					break;
2037 				}
2038 
2039 				hv_pci_devices_present(hbus, bus_rel);
2040 				break;
2041 
2042 			case PCI_EJECT:
2043 
2044 				dev_message = (struct pci_dev_incoming *)buffer;
2045 				hpdev = get_pcichild_wslot(hbus,
2046 						      dev_message->wslot.slot);
2047 				if (hpdev) {
2048 					hv_pci_eject_device(hpdev);
2049 					put_pcichild(hpdev);
2050 				}
2051 				break;
2052 
2053 			default:
2054 				dev_warn(&hbus->hdev->device,
2055 					"Unimplemented protocol message %x\n",
2056 					new_message->message_type.type);
2057 				break;
2058 			}
2059 			break;
2060 
2061 		default:
2062 			dev_err(&hbus->hdev->device,
2063 				"unhandled packet type %d, tid %llx len %d\n",
2064 				desc->type, req_id, bytes_recvd);
2065 			break;
2066 		}
2067 	}
2068 
2069 	kfree(buffer);
2070 }
2071 
2072 /**
2073  * hv_pci_protocol_negotiation() - Set up protocol
2074  * @hdev:	VMBus's tracking struct for this root PCI bus
2075  *
2076  * This driver is intended to support running on Windows 10
2077  * (server) and later versions. It will not run on earlier
2078  * versions, as they assume that many of the operations which
2079  * Linux needs accomplished with a spinlock held were done via
2080  * asynchronous messaging via VMBus.  Windows 10 increases the
2081  * surface area of PCI emulation so that these actions can take
2082  * place by suspending a virtual processor for their duration.
2083  *
2084  * This function negotiates the channel protocol version,
2085  * failing if the host doesn't support the necessary protocol
2086  * level.
2087  */
hv_pci_protocol_negotiation(struct hv_device * hdev)2088 static int hv_pci_protocol_negotiation(struct hv_device *hdev)
2089 {
2090 	struct pci_version_request *version_req;
2091 	struct hv_pci_compl comp_pkt;
2092 	struct pci_packet *pkt;
2093 	int ret;
2094 	int i;
2095 
2096 	/*
2097 	 * Initiate the handshake with the host and negotiate
2098 	 * a version that the host can support. We start with the
2099 	 * highest version number and go down if the host cannot
2100 	 * support it.
2101 	 */
2102 	pkt = kzalloc(sizeof(*pkt) + sizeof(*version_req), GFP_KERNEL);
2103 	if (!pkt)
2104 		return -ENOMEM;
2105 
2106 	init_completion(&comp_pkt.host_event);
2107 	pkt->completion_func = hv_pci_generic_compl;
2108 	pkt->compl_ctxt = &comp_pkt;
2109 	version_req = (struct pci_version_request *)&pkt->message;
2110 	version_req->message_type.type = PCI_QUERY_PROTOCOL_VERSION;
2111 
2112 	for (i = 0; i < ARRAY_SIZE(pci_protocol_versions); i++) {
2113 		version_req->protocol_version = pci_protocol_versions[i];
2114 		ret = vmbus_sendpacket(hdev->channel, version_req,
2115 				sizeof(struct pci_version_request),
2116 				(unsigned long)pkt, VM_PKT_DATA_INBAND,
2117 				VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2118 		if (!ret)
2119 			ret = wait_for_response(hdev, &comp_pkt.host_event);
2120 
2121 		if (ret) {
2122 			dev_err(&hdev->device,
2123 				"PCI Pass-through VSP failed to request version: %d",
2124 				ret);
2125 			goto exit;
2126 		}
2127 
2128 		if (comp_pkt.completion_status >= 0) {
2129 			pci_protocol_version = pci_protocol_versions[i];
2130 			dev_info(&hdev->device,
2131 				"PCI VMBus probing: Using version %#x\n",
2132 				pci_protocol_version);
2133 			goto exit;
2134 		}
2135 
2136 		if (comp_pkt.completion_status != STATUS_REVISION_MISMATCH) {
2137 			dev_err(&hdev->device,
2138 				"PCI Pass-through VSP failed version request: %#x",
2139 				comp_pkt.completion_status);
2140 			ret = -EPROTO;
2141 			goto exit;
2142 		}
2143 
2144 		reinit_completion(&comp_pkt.host_event);
2145 	}
2146 
2147 	dev_err(&hdev->device,
2148 		"PCI pass-through VSP failed to find supported version");
2149 	ret = -EPROTO;
2150 
2151 exit:
2152 	kfree(pkt);
2153 	return ret;
2154 }
2155 
2156 /**
2157  * hv_pci_free_bridge_windows() - Release memory regions for the
2158  * bus
2159  * @hbus:	Root PCI bus, as understood by this driver
2160  */
hv_pci_free_bridge_windows(struct hv_pcibus_device * hbus)2161 static void hv_pci_free_bridge_windows(struct hv_pcibus_device *hbus)
2162 {
2163 	/*
2164 	 * Set the resources back to the way they looked when they
2165 	 * were allocated by setting IORESOURCE_BUSY again.
2166 	 */
2167 
2168 	if (hbus->low_mmio_space && hbus->low_mmio_res) {
2169 		hbus->low_mmio_res->flags |= IORESOURCE_BUSY;
2170 		vmbus_free_mmio(hbus->low_mmio_res->start,
2171 				resource_size(hbus->low_mmio_res));
2172 	}
2173 
2174 	if (hbus->high_mmio_space && hbus->high_mmio_res) {
2175 		hbus->high_mmio_res->flags |= IORESOURCE_BUSY;
2176 		vmbus_free_mmio(hbus->high_mmio_res->start,
2177 				resource_size(hbus->high_mmio_res));
2178 	}
2179 }
2180 
2181 /**
2182  * hv_pci_allocate_bridge_windows() - Allocate memory regions
2183  * for the bus
2184  * @hbus:	Root PCI bus, as understood by this driver
2185  *
2186  * This function calls vmbus_allocate_mmio(), which is itself a
2187  * bit of a compromise.  Ideally, we might change the pnp layer
2188  * in the kernel such that it comprehends either PCI devices
2189  * which are "grandchildren of ACPI," with some intermediate bus
2190  * node (in this case, VMBus) or change it such that it
2191  * understands VMBus.  The pnp layer, however, has been declared
2192  * deprecated, and not subject to change.
2193  *
2194  * The workaround, implemented here, is to ask VMBus to allocate
2195  * MMIO space for this bus.  VMBus itself knows which ranges are
2196  * appropriate by looking at its own ACPI objects.  Then, after
2197  * these ranges are claimed, they're modified to look like they
2198  * would have looked if the ACPI and pnp code had allocated
2199  * bridge windows.  These descriptors have to exist in this form
2200  * in order to satisfy the code which will get invoked when the
2201  * endpoint PCI function driver calls request_mem_region() or
2202  * request_mem_region_exclusive().
2203  *
2204  * Return: 0 on success, -errno on failure
2205  */
hv_pci_allocate_bridge_windows(struct hv_pcibus_device * hbus)2206 static int hv_pci_allocate_bridge_windows(struct hv_pcibus_device *hbus)
2207 {
2208 	resource_size_t align;
2209 	int ret;
2210 
2211 	if (hbus->low_mmio_space) {
2212 		align = 1ULL << (63 - __builtin_clzll(hbus->low_mmio_space));
2213 		ret = vmbus_allocate_mmio(&hbus->low_mmio_res, hbus->hdev, 0,
2214 					  (u64)(u32)0xffffffff,
2215 					  hbus->low_mmio_space,
2216 					  align, false);
2217 		if (ret) {
2218 			dev_err(&hbus->hdev->device,
2219 				"Need %#llx of low MMIO space. Consider reconfiguring the VM.\n",
2220 				hbus->low_mmio_space);
2221 			return ret;
2222 		}
2223 
2224 		/* Modify this resource to become a bridge window. */
2225 		hbus->low_mmio_res->flags |= IORESOURCE_WINDOW;
2226 		hbus->low_mmio_res->flags &= ~IORESOURCE_BUSY;
2227 		pci_add_resource(&hbus->resources_for_children,
2228 				 hbus->low_mmio_res);
2229 	}
2230 
2231 	if (hbus->high_mmio_space) {
2232 		align = 1ULL << (63 - __builtin_clzll(hbus->high_mmio_space));
2233 		ret = vmbus_allocate_mmio(&hbus->high_mmio_res, hbus->hdev,
2234 					  0x100000000, -1,
2235 					  hbus->high_mmio_space, align,
2236 					  false);
2237 		if (ret) {
2238 			dev_err(&hbus->hdev->device,
2239 				"Need %#llx of high MMIO space. Consider reconfiguring the VM.\n",
2240 				hbus->high_mmio_space);
2241 			goto release_low_mmio;
2242 		}
2243 
2244 		/* Modify this resource to become a bridge window. */
2245 		hbus->high_mmio_res->flags |= IORESOURCE_WINDOW;
2246 		hbus->high_mmio_res->flags &= ~IORESOURCE_BUSY;
2247 		pci_add_resource(&hbus->resources_for_children,
2248 				 hbus->high_mmio_res);
2249 	}
2250 
2251 	return 0;
2252 
2253 release_low_mmio:
2254 	if (hbus->low_mmio_res) {
2255 		vmbus_free_mmio(hbus->low_mmio_res->start,
2256 				resource_size(hbus->low_mmio_res));
2257 	}
2258 
2259 	return ret;
2260 }
2261 
2262 /**
2263  * hv_allocate_config_window() - Find MMIO space for PCI Config
2264  * @hbus:	Root PCI bus, as understood by this driver
2265  *
2266  * This function claims memory-mapped I/O space for accessing
2267  * configuration space for the functions on this bus.
2268  *
2269  * Return: 0 on success, -errno on failure
2270  */
hv_allocate_config_window(struct hv_pcibus_device * hbus)2271 static int hv_allocate_config_window(struct hv_pcibus_device *hbus)
2272 {
2273 	int ret;
2274 
2275 	/*
2276 	 * Set up a region of MMIO space to use for accessing configuration
2277 	 * space.
2278 	 */
2279 	ret = vmbus_allocate_mmio(&hbus->mem_config, hbus->hdev, 0, -1,
2280 				  PCI_CONFIG_MMIO_LENGTH, 0x1000, false);
2281 	if (ret)
2282 		return ret;
2283 
2284 	/*
2285 	 * vmbus_allocate_mmio() gets used for allocating both device endpoint
2286 	 * resource claims (those which cannot be overlapped) and the ranges
2287 	 * which are valid for the children of this bus, which are intended
2288 	 * to be overlapped by those children.  Set the flag on this claim
2289 	 * meaning that this region can't be overlapped.
2290 	 */
2291 
2292 	hbus->mem_config->flags |= IORESOURCE_BUSY;
2293 
2294 	return 0;
2295 }
2296 
hv_free_config_window(struct hv_pcibus_device * hbus)2297 static void hv_free_config_window(struct hv_pcibus_device *hbus)
2298 {
2299 	vmbus_free_mmio(hbus->mem_config->start, PCI_CONFIG_MMIO_LENGTH);
2300 }
2301 
2302 /**
2303  * hv_pci_enter_d0() - Bring the "bus" into the D0 power state
2304  * @hdev:	VMBus's tracking struct for this root PCI bus
2305  *
2306  * Return: 0 on success, -errno on failure
2307  */
hv_pci_enter_d0(struct hv_device * hdev)2308 static int hv_pci_enter_d0(struct hv_device *hdev)
2309 {
2310 	struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2311 	struct pci_bus_d0_entry *d0_entry;
2312 	struct hv_pci_compl comp_pkt;
2313 	struct pci_packet *pkt;
2314 	int ret;
2315 
2316 	/*
2317 	 * Tell the host that the bus is ready to use, and moved into the
2318 	 * powered-on state.  This includes telling the host which region
2319 	 * of memory-mapped I/O space has been chosen for configuration space
2320 	 * access.
2321 	 */
2322 	pkt = kzalloc(sizeof(*pkt) + sizeof(*d0_entry), GFP_KERNEL);
2323 	if (!pkt)
2324 		return -ENOMEM;
2325 
2326 	init_completion(&comp_pkt.host_event);
2327 	pkt->completion_func = hv_pci_generic_compl;
2328 	pkt->compl_ctxt = &comp_pkt;
2329 	d0_entry = (struct pci_bus_d0_entry *)&pkt->message;
2330 	d0_entry->message_type.type = PCI_BUS_D0ENTRY;
2331 	d0_entry->mmio_base = hbus->mem_config->start;
2332 
2333 	ret = vmbus_sendpacket(hdev->channel, d0_entry, sizeof(*d0_entry),
2334 			       (unsigned long)pkt, VM_PKT_DATA_INBAND,
2335 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2336 	if (!ret)
2337 		ret = wait_for_response(hdev, &comp_pkt.host_event);
2338 
2339 	if (ret)
2340 		goto exit;
2341 
2342 	if (comp_pkt.completion_status < 0) {
2343 		dev_err(&hdev->device,
2344 			"PCI Pass-through VSP failed D0 Entry with status %x\n",
2345 			comp_pkt.completion_status);
2346 		ret = -EPROTO;
2347 		goto exit;
2348 	}
2349 
2350 	ret = 0;
2351 
2352 exit:
2353 	kfree(pkt);
2354 	return ret;
2355 }
2356 
2357 /**
2358  * hv_pci_query_relations() - Ask host to send list of child
2359  * devices
2360  * @hdev:	VMBus's tracking struct for this root PCI bus
2361  *
2362  * Return: 0 on success, -errno on failure
2363  */
hv_pci_query_relations(struct hv_device * hdev)2364 static int hv_pci_query_relations(struct hv_device *hdev)
2365 {
2366 	struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2367 	struct pci_message message;
2368 	struct completion comp;
2369 	int ret;
2370 
2371 	/* Ask the host to send along the list of child devices */
2372 	init_completion(&comp);
2373 	if (cmpxchg(&hbus->survey_event, NULL, &comp))
2374 		return -ENOTEMPTY;
2375 
2376 	memset(&message, 0, sizeof(message));
2377 	message.type = PCI_QUERY_BUS_RELATIONS;
2378 
2379 	ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
2380 			       0, VM_PKT_DATA_INBAND, 0);
2381 	if (!ret)
2382 		ret = wait_for_response(hdev, &comp);
2383 
2384 	return ret;
2385 }
2386 
2387 /**
2388  * hv_send_resources_allocated() - Report local resource choices
2389  * @hdev:	VMBus's tracking struct for this root PCI bus
2390  *
2391  * The host OS is expecting to be sent a request as a message
2392  * which contains all the resources that the device will use.
2393  * The response contains those same resources, "translated"
2394  * which is to say, the values which should be used by the
2395  * hardware, when it delivers an interrupt.  (MMIO resources are
2396  * used in local terms.)  This is nice for Windows, and lines up
2397  * with the FDO/PDO split, which doesn't exist in Linux.  Linux
2398  * is deeply expecting to scan an emulated PCI configuration
2399  * space.  So this message is sent here only to drive the state
2400  * machine on the host forward.
2401  *
2402  * Return: 0 on success, -errno on failure
2403  */
hv_send_resources_allocated(struct hv_device * hdev)2404 static int hv_send_resources_allocated(struct hv_device *hdev)
2405 {
2406 	struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2407 	struct pci_resources_assigned *res_assigned;
2408 	struct pci_resources_assigned2 *res_assigned2;
2409 	struct hv_pci_compl comp_pkt;
2410 	struct hv_pci_dev *hpdev;
2411 	struct pci_packet *pkt;
2412 	size_t size_res;
2413 	u32 wslot;
2414 	int ret;
2415 
2416 	size_res = (pci_protocol_version < PCI_PROTOCOL_VERSION_1_2)
2417 			? sizeof(*res_assigned) : sizeof(*res_assigned2);
2418 
2419 	pkt = kmalloc(sizeof(*pkt) + size_res, GFP_KERNEL);
2420 	if (!pkt)
2421 		return -ENOMEM;
2422 
2423 	ret = 0;
2424 
2425 	for (wslot = 0; wslot < 256; wslot++) {
2426 		hpdev = get_pcichild_wslot(hbus, wslot);
2427 		if (!hpdev)
2428 			continue;
2429 
2430 		memset(pkt, 0, sizeof(*pkt) + size_res);
2431 		init_completion(&comp_pkt.host_event);
2432 		pkt->completion_func = hv_pci_generic_compl;
2433 		pkt->compl_ctxt = &comp_pkt;
2434 
2435 		if (pci_protocol_version < PCI_PROTOCOL_VERSION_1_2) {
2436 			res_assigned =
2437 				(struct pci_resources_assigned *)&pkt->message;
2438 			res_assigned->message_type.type =
2439 				PCI_RESOURCES_ASSIGNED;
2440 			res_assigned->wslot.slot = hpdev->desc.win_slot.slot;
2441 		} else {
2442 			res_assigned2 =
2443 				(struct pci_resources_assigned2 *)&pkt->message;
2444 			res_assigned2->message_type.type =
2445 				PCI_RESOURCES_ASSIGNED2;
2446 			res_assigned2->wslot.slot = hpdev->desc.win_slot.slot;
2447 		}
2448 		put_pcichild(hpdev);
2449 
2450 		ret = vmbus_sendpacket(hdev->channel, &pkt->message,
2451 				size_res, (unsigned long)pkt,
2452 				VM_PKT_DATA_INBAND,
2453 				VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2454 		if (!ret)
2455 			ret = wait_for_response(hdev, &comp_pkt.host_event);
2456 		if (ret)
2457 			break;
2458 
2459 		if (comp_pkt.completion_status < 0) {
2460 			ret = -EPROTO;
2461 			dev_err(&hdev->device,
2462 				"resource allocated returned 0x%x",
2463 				comp_pkt.completion_status);
2464 			break;
2465 		}
2466 	}
2467 
2468 	kfree(pkt);
2469 	return ret;
2470 }
2471 
2472 /**
2473  * hv_send_resources_released() - Report local resources
2474  * released
2475  * @hdev:	VMBus's tracking struct for this root PCI bus
2476  *
2477  * Return: 0 on success, -errno on failure
2478  */
hv_send_resources_released(struct hv_device * hdev)2479 static int hv_send_resources_released(struct hv_device *hdev)
2480 {
2481 	struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2482 	struct pci_child_message pkt;
2483 	struct hv_pci_dev *hpdev;
2484 	u32 wslot;
2485 	int ret;
2486 
2487 	for (wslot = 0; wslot < 256; wslot++) {
2488 		hpdev = get_pcichild_wslot(hbus, wslot);
2489 		if (!hpdev)
2490 			continue;
2491 
2492 		memset(&pkt, 0, sizeof(pkt));
2493 		pkt.message_type.type = PCI_RESOURCES_RELEASED;
2494 		pkt.wslot.slot = hpdev->desc.win_slot.slot;
2495 
2496 		put_pcichild(hpdev);
2497 
2498 		ret = vmbus_sendpacket(hdev->channel, &pkt, sizeof(pkt), 0,
2499 				       VM_PKT_DATA_INBAND, 0);
2500 		if (ret)
2501 			return ret;
2502 	}
2503 
2504 	return 0;
2505 }
2506 
get_hvpcibus(struct hv_pcibus_device * hbus)2507 static void get_hvpcibus(struct hv_pcibus_device *hbus)
2508 {
2509 	refcount_inc(&hbus->remove_lock);
2510 }
2511 
put_hvpcibus(struct hv_pcibus_device * hbus)2512 static void put_hvpcibus(struct hv_pcibus_device *hbus)
2513 {
2514 	if (refcount_dec_and_test(&hbus->remove_lock))
2515 		complete(&hbus->remove_event);
2516 }
2517 
2518 /**
2519  * hv_pci_probe() - New VMBus channel probe, for a root PCI bus
2520  * @hdev:	VMBus's tracking struct for this root PCI bus
2521  * @dev_id:	Identifies the device itself
2522  *
2523  * Return: 0 on success, -errno on failure
2524  */
hv_pci_probe(struct hv_device * hdev,const struct hv_vmbus_device_id * dev_id)2525 static int hv_pci_probe(struct hv_device *hdev,
2526 			const struct hv_vmbus_device_id *dev_id)
2527 {
2528 	struct hv_pcibus_device *hbus;
2529 	int ret;
2530 
2531 	/*
2532 	 * hv_pcibus_device contains the hypercall arguments for retargeting in
2533 	 * hv_irq_unmask(). Those must not cross a page boundary.
2534 	 */
2535 	BUILD_BUG_ON(sizeof(*hbus) > PAGE_SIZE);
2536 
2537 	hbus = (struct hv_pcibus_device *)get_zeroed_page(GFP_KERNEL);
2538 	if (!hbus)
2539 		return -ENOMEM;
2540 	hbus->state = hv_pcibus_init;
2541 
2542 	/*
2543 	 * The PCI bus "domain" is what is called "segment" in ACPI and
2544 	 * other specs.  Pull it from the instance ID, to get something
2545 	 * unique.  Bytes 8 and 9 are what is used in Windows guests, so
2546 	 * do the same thing for consistency.  Note that, since this code
2547 	 * only runs in a Hyper-V VM, Hyper-V can (and does) guarantee
2548 	 * that (1) the only domain in use for something that looks like
2549 	 * a physical PCI bus (which is actually emulated by the
2550 	 * hypervisor) is domain 0 and (2) there will be no overlap
2551 	 * between domains derived from these instance IDs in the same
2552 	 * VM.
2553 	 */
2554 	hbus->sysdata.domain = hdev->dev_instance.b[9] |
2555 			       hdev->dev_instance.b[8] << 8;
2556 
2557 	hbus->hdev = hdev;
2558 	refcount_set(&hbus->remove_lock, 1);
2559 	INIT_LIST_HEAD(&hbus->children);
2560 	INIT_LIST_HEAD(&hbus->dr_list);
2561 	INIT_LIST_HEAD(&hbus->resources_for_children);
2562 	spin_lock_init(&hbus->config_lock);
2563 	spin_lock_init(&hbus->device_list_lock);
2564 	spin_lock_init(&hbus->retarget_msi_interrupt_lock);
2565 	init_completion(&hbus->remove_event);
2566 	hbus->wq = alloc_ordered_workqueue("hv_pci_%x", 0,
2567 					   hbus->sysdata.domain);
2568 	if (!hbus->wq) {
2569 		ret = -ENOMEM;
2570 		goto free_bus;
2571 	}
2572 
2573 	ret = vmbus_open(hdev->channel, pci_ring_size, pci_ring_size, NULL, 0,
2574 			 hv_pci_onchannelcallback, hbus);
2575 	if (ret)
2576 		goto destroy_wq;
2577 
2578 	hv_set_drvdata(hdev, hbus);
2579 
2580 	ret = hv_pci_protocol_negotiation(hdev);
2581 	if (ret)
2582 		goto close;
2583 
2584 	ret = hv_allocate_config_window(hbus);
2585 	if (ret)
2586 		goto close;
2587 
2588 	hbus->cfg_addr = ioremap(hbus->mem_config->start,
2589 				 PCI_CONFIG_MMIO_LENGTH);
2590 	if (!hbus->cfg_addr) {
2591 		dev_err(&hdev->device,
2592 			"Unable to map a virtual address for config space\n");
2593 		ret = -ENOMEM;
2594 		goto free_config;
2595 	}
2596 
2597 	hbus->sysdata.fwnode = irq_domain_alloc_fwnode(hbus);
2598 	if (!hbus->sysdata.fwnode) {
2599 		ret = -ENOMEM;
2600 		goto unmap;
2601 	}
2602 
2603 	ret = hv_pcie_init_irq_domain(hbus);
2604 	if (ret)
2605 		goto free_fwnode;
2606 
2607 	ret = hv_pci_query_relations(hdev);
2608 	if (ret)
2609 		goto free_irq_domain;
2610 
2611 	ret = hv_pci_enter_d0(hdev);
2612 	if (ret)
2613 		goto free_irq_domain;
2614 
2615 	ret = hv_pci_allocate_bridge_windows(hbus);
2616 	if (ret)
2617 		goto free_irq_domain;
2618 
2619 	ret = hv_send_resources_allocated(hdev);
2620 	if (ret)
2621 		goto free_windows;
2622 
2623 	prepopulate_bars(hbus);
2624 
2625 	hbus->state = hv_pcibus_probed;
2626 
2627 	ret = create_root_hv_pci_bus(hbus);
2628 	if (ret)
2629 		goto free_windows;
2630 
2631 	return 0;
2632 
2633 free_windows:
2634 	hv_pci_free_bridge_windows(hbus);
2635 free_irq_domain:
2636 	irq_domain_remove(hbus->irq_domain);
2637 free_fwnode:
2638 	irq_domain_free_fwnode(hbus->sysdata.fwnode);
2639 unmap:
2640 	iounmap(hbus->cfg_addr);
2641 free_config:
2642 	hv_free_config_window(hbus);
2643 close:
2644 	vmbus_close(hdev->channel);
2645 destroy_wq:
2646 	destroy_workqueue(hbus->wq);
2647 free_bus:
2648 	free_page((unsigned long)hbus);
2649 	return ret;
2650 }
2651 
hv_pci_bus_exit(struct hv_device * hdev)2652 static void hv_pci_bus_exit(struct hv_device *hdev)
2653 {
2654 	struct hv_pcibus_device *hbus = hv_get_drvdata(hdev);
2655 	struct {
2656 		struct pci_packet teardown_packet;
2657 		u8 buffer[sizeof(struct pci_message)];
2658 	} pkt;
2659 	struct pci_bus_relations relations;
2660 	struct hv_pci_compl comp_pkt;
2661 	int ret;
2662 
2663 	/*
2664 	 * After the host sends the RESCIND_CHANNEL message, it doesn't
2665 	 * access the per-channel ringbuffer any longer.
2666 	 */
2667 	if (hdev->channel->rescind)
2668 		return;
2669 
2670 	/* Delete any children which might still exist. */
2671 	memset(&relations, 0, sizeof(relations));
2672 	hv_pci_devices_present(hbus, &relations);
2673 
2674 	ret = hv_send_resources_released(hdev);
2675 	if (ret)
2676 		dev_err(&hdev->device,
2677 			"Couldn't send resources released packet(s)\n");
2678 
2679 	memset(&pkt.teardown_packet, 0, sizeof(pkt.teardown_packet));
2680 	init_completion(&comp_pkt.host_event);
2681 	pkt.teardown_packet.completion_func = hv_pci_generic_compl;
2682 	pkt.teardown_packet.compl_ctxt = &comp_pkt;
2683 	pkt.teardown_packet.message[0].type = PCI_BUS_D0EXIT;
2684 
2685 	ret = vmbus_sendpacket(hdev->channel, &pkt.teardown_packet.message,
2686 			       sizeof(struct pci_message),
2687 			       (unsigned long)&pkt.teardown_packet,
2688 			       VM_PKT_DATA_INBAND,
2689 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
2690 	if (!ret)
2691 		wait_for_completion_timeout(&comp_pkt.host_event, 10 * HZ);
2692 }
2693 
2694 /**
2695  * hv_pci_remove() - Remove routine for this VMBus channel
2696  * @hdev:	VMBus's tracking struct for this root PCI bus
2697  *
2698  * Return: 0 on success, -errno on failure
2699  */
hv_pci_remove(struct hv_device * hdev)2700 static int hv_pci_remove(struct hv_device *hdev)
2701 {
2702 	struct hv_pcibus_device *hbus;
2703 
2704 	hbus = hv_get_drvdata(hdev);
2705 	if (hbus->state == hv_pcibus_installed) {
2706 		/* Remove the bus from PCI's point of view. */
2707 		pci_lock_rescan_remove();
2708 		pci_stop_root_bus(hbus->pci_bus);
2709 		hv_pci_remove_slots(hbus);
2710 		pci_remove_root_bus(hbus->pci_bus);
2711 		pci_unlock_rescan_remove();
2712 		hbus->state = hv_pcibus_removed;
2713 	}
2714 
2715 	hv_pci_bus_exit(hdev);
2716 
2717 	vmbus_close(hdev->channel);
2718 
2719 	iounmap(hbus->cfg_addr);
2720 	hv_free_config_window(hbus);
2721 	pci_free_resource_list(&hbus->resources_for_children);
2722 	hv_pci_free_bridge_windows(hbus);
2723 	irq_domain_remove(hbus->irq_domain);
2724 	irq_domain_free_fwnode(hbus->sysdata.fwnode);
2725 	put_hvpcibus(hbus);
2726 	wait_for_completion(&hbus->remove_event);
2727 	destroy_workqueue(hbus->wq);
2728 	free_page((unsigned long)hbus);
2729 	return 0;
2730 }
2731 
2732 static const struct hv_vmbus_device_id hv_pci_id_table[] = {
2733 	/* PCI Pass-through Class ID */
2734 	/* 44C4F61D-4444-4400-9D52-802E27EDE19F */
2735 	{ HV_PCIE_GUID, },
2736 	{ },
2737 };
2738 
2739 MODULE_DEVICE_TABLE(vmbus, hv_pci_id_table);
2740 
2741 static struct hv_driver hv_pci_drv = {
2742 	.name		= "hv_pci",
2743 	.id_table	= hv_pci_id_table,
2744 	.probe		= hv_pci_probe,
2745 	.remove		= hv_pci_remove,
2746 };
2747 
exit_hv_pci_drv(void)2748 static void __exit exit_hv_pci_drv(void)
2749 {
2750 	vmbus_driver_unregister(&hv_pci_drv);
2751 }
2752 
init_hv_pci_drv(void)2753 static int __init init_hv_pci_drv(void)
2754 {
2755 	return vmbus_driver_register(&hv_pci_drv);
2756 }
2757 
2758 module_init(init_hv_pci_drv);
2759 module_exit(exit_hv_pci_drv);
2760 
2761 MODULE_DESCRIPTION("Hyper-V PCI");
2762 MODULE_LICENSE("GPL v2");
2763