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