Linux Audio

Check our new training course

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