File Index
Files and directories
Sign in
FILE

vmbus_drv.c

File preview with syntax highlighting.

linux-6.19.14/drivers/hv/vmbus_drv.c C
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Copyright (c) 2009, Microsoft Corporation.
   4 *
   5 * Authors:
   6 *   Haiyang Zhang <haiyangz@microsoft.com>
   7 *   Hank Janssen  <hjanssen@microsoft.com>
   8 *   K. Y. Srinivasan <kys@microsoft.com>
   9 */
  10#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  11
  12#include <linux/init.h>
  13#include <linux/module.h>
  14#include <linux/device.h>
  15#include <linux/platform_device.h>
  16#include <linux/interrupt.h>
  17#include <linux/sysctl.h>
  18#include <linux/slab.h>
  19#include <linux/acpi.h>
  20#include <linux/completion.h>
  21#include <linux/hyperv.h>
  22#include <linux/kernel_stat.h>
  23#include <linux/of_address.h>
  24#include <linux/clockchips.h>
  25#include <linux/cpu.h>
  26#include <linux/sched/isolation.h>
  27#include <linux/sched/task_stack.h>
  28#include <linux/smpboot.h>
  29
  30#include <linux/delay.h>
  31#include <linux/panic_notifier.h>
  32#include <linux/ptrace.h>
  33#include <linux/screen_info.h>
  34#include <linux/efi.h>
  35#include <linux/random.h>
  36#include <linux/kernel.h>
  37#include <linux/syscore_ops.h>
  38#include <linux/dma-map-ops.h>
  39#include <linux/pci.h>
  40#include <linux/export.h>
  41#include <clocksource/hyperv_timer.h>
  42#include <asm/mshyperv.h>
  43#include "hyperv_vmbus.h"
  44
  45struct vmbus_dynid {
  46	struct list_head node;
  47	struct hv_vmbus_device_id id;
  48};
  49
  50/* VMBus Root Device */
  51static struct device  *vmbus_root_device;
  52
  53static int hyperv_cpuhp_online;
  54
  55static long __percpu *vmbus_evt;
  56
  57/* Values parsed from ACPI DSDT */
  58int vmbus_irq;
  59int vmbus_interrupt;
  60
  61/*
  62 * If the Confidential VMBus is used, the data on the "wire" is not
  63 * visible to either the host or the hypervisor.
  64 */
  65static bool is_confidential;
  66
  67bool vmbus_is_confidential(void)
  68{
  69	return is_confidential;
  70}
  71EXPORT_SYMBOL_GPL(vmbus_is_confidential);
  72
  73/*
  74 * The panic notifier below is responsible solely for unloading the
  75 * vmbus connection, which is necessary in a panic event.
  76 *
  77 * Notice an intrincate relation of this notifier with Hyper-V
  78 * framebuffer panic notifier exists - we need vmbus connection alive
  79 * there in order to succeed, so we need to order both with each other
  80 * [see hvfb_on_panic()] - this is done using notifiers' priorities.
  81 */
  82static int hv_panic_vmbus_unload(struct notifier_block *nb, unsigned long val,
  83			      void *args)
  84{
  85	vmbus_initiate_unload(true);
  86	return NOTIFY_DONE;
  87}
  88static struct notifier_block hyperv_panic_vmbus_unload_block = {
  89	.notifier_call	= hv_panic_vmbus_unload,
  90	.priority	= INT_MIN + 1, /* almost the latest one to execute */
  91};
  92
  93static const char *fb_mmio_name = "fb_range";
  94static struct resource *fb_mmio;
  95static struct resource *hyperv_mmio;
  96static DEFINE_MUTEX(hyperv_mmio_lock);
  97
  98struct device *hv_get_vmbus_root_device(void)
  99{
 100	return vmbus_root_device;
 101}
 102EXPORT_SYMBOL_GPL(hv_get_vmbus_root_device);
 103
 104static int vmbus_exists(void)
 105{
 106	if (vmbus_root_device == NULL)
 107		return -ENODEV;
 108
 109	return 0;
 110}
 111
 112static u8 channel_monitor_group(const struct vmbus_channel *channel)
 113{
 114	return (u8)channel->offermsg.monitorid / 32;
 115}
 116
 117static u8 channel_monitor_offset(const struct vmbus_channel *channel)
 118{
 119	return (u8)channel->offermsg.monitorid % 32;
 120}
 121
 122static u32 channel_pending(const struct vmbus_channel *channel,
 123			   const struct hv_monitor_page *monitor_page)
 124{
 125	u8 monitor_group = channel_monitor_group(channel);
 126
 127	return monitor_page->trigger_group[monitor_group].pending;
 128}
 129
 130static u32 channel_latency(const struct vmbus_channel *channel,
 131			   const struct hv_monitor_page *monitor_page)
 132{
 133	u8 monitor_group = channel_monitor_group(channel);
 134	u8 monitor_offset = channel_monitor_offset(channel);
 135
 136	return monitor_page->latency[monitor_group][monitor_offset];
 137}
 138
 139static u32 channel_conn_id(struct vmbus_channel *channel,
 140			   struct hv_monitor_page *monitor_page)
 141{
 142	u8 monitor_group = channel_monitor_group(channel);
 143	u8 monitor_offset = channel_monitor_offset(channel);
 144
 145	return monitor_page->parameter[monitor_group][monitor_offset].connectionid.u.id;
 146}
 147
 148static ssize_t id_show(struct device *dev, struct device_attribute *dev_attr,
 149		       char *buf)
 150{
 151	struct hv_device *hv_dev = device_to_hv_device(dev);
 152
 153	if (!hv_dev->channel)
 154		return -ENODEV;
 155	return sysfs_emit(buf, "%d\n", hv_dev->channel->offermsg.child_relid);
 156}
 157static DEVICE_ATTR_RO(id);
 158
 159static ssize_t state_show(struct device *dev, struct device_attribute *dev_attr,
 160			  char *buf)
 161{
 162	struct hv_device *hv_dev = device_to_hv_device(dev);
 163
 164	if (!hv_dev->channel)
 165		return -ENODEV;
 166	return sysfs_emit(buf, "%d\n", hv_dev->channel->state);
 167}
 168static DEVICE_ATTR_RO(state);
 169
 170static ssize_t monitor_id_show(struct device *dev,
 171			       struct device_attribute *dev_attr, char *buf)
 172{
 173	struct hv_device *hv_dev = device_to_hv_device(dev);
 174
 175	if (!hv_dev->channel)
 176		return -ENODEV;
 177	return sysfs_emit(buf, "%d\n", hv_dev->channel->offermsg.monitorid);
 178}
 179static DEVICE_ATTR_RO(monitor_id);
 180
 181static ssize_t class_id_show(struct device *dev,
 182			       struct device_attribute *dev_attr, char *buf)
 183{
 184	struct hv_device *hv_dev = device_to_hv_device(dev);
 185
 186	if (!hv_dev->channel)
 187		return -ENODEV;
 188	return sysfs_emit(buf, "{%pUl}\n",
 189			  &hv_dev->channel->offermsg.offer.if_type);
 190}
 191static DEVICE_ATTR_RO(class_id);
 192
 193static ssize_t device_id_show(struct device *dev,
 194			      struct device_attribute *dev_attr, char *buf)
 195{
 196	struct hv_device *hv_dev = device_to_hv_device(dev);
 197
 198	if (!hv_dev->channel)
 199		return -ENODEV;
 200	return sysfs_emit(buf, "{%pUl}\n",
 201			  &hv_dev->channel->offermsg.offer.if_instance);
 202}
 203static DEVICE_ATTR_RO(device_id);
 204
 205static ssize_t modalias_show(struct device *dev,
 206			     struct device_attribute *dev_attr, char *buf)
 207{
 208	struct hv_device *hv_dev = device_to_hv_device(dev);
 209
 210	return sysfs_emit(buf, "vmbus:%*phN\n", UUID_SIZE, &hv_dev->dev_type);
 211}
 212static DEVICE_ATTR_RO(modalias);
 213
 214#ifdef CONFIG_NUMA
 215static ssize_t numa_node_show(struct device *dev,
 216			      struct device_attribute *attr, char *buf)
 217{
 218	struct hv_device *hv_dev = device_to_hv_device(dev);
 219
 220	if (!hv_dev->channel)
 221		return -ENODEV;
 222
 223	return sysfs_emit(buf, "%d\n", cpu_to_node(hv_dev->channel->target_cpu));
 224}
 225static DEVICE_ATTR_RO(numa_node);
 226#endif
 227
 228static ssize_t server_monitor_pending_show(struct device *dev,
 229					   struct device_attribute *dev_attr,
 230					   char *buf)
 231{
 232	struct hv_device *hv_dev = device_to_hv_device(dev);
 233
 234	if (!hv_dev->channel)
 235		return -ENODEV;
 236	return sysfs_emit(buf, "%d\n", channel_pending(hv_dev->channel,
 237			  vmbus_connection.monitor_pages[0]));
 238}
 239static DEVICE_ATTR_RO(server_monitor_pending);
 240
 241static ssize_t client_monitor_pending_show(struct device *dev,
 242					   struct device_attribute *dev_attr,
 243					   char *buf)
 244{
 245	struct hv_device *hv_dev = device_to_hv_device(dev);
 246
 247	if (!hv_dev->channel)
 248		return -ENODEV;
 249	return sysfs_emit(buf, "%d\n", channel_pending(hv_dev->channel,
 250			  vmbus_connection.monitor_pages[1]));
 251}
 252static DEVICE_ATTR_RO(client_monitor_pending);
 253
 254static ssize_t server_monitor_latency_show(struct device *dev,
 255					   struct device_attribute *dev_attr,
 256					   char *buf)
 257{
 258	struct hv_device *hv_dev = device_to_hv_device(dev);
 259
 260	if (!hv_dev->channel)
 261		return -ENODEV;
 262	return sysfs_emit(buf, "%d\n", channel_latency(hv_dev->channel,
 263			  vmbus_connection.monitor_pages[0]));
 264}
 265static DEVICE_ATTR_RO(server_monitor_latency);
 266
 267static ssize_t client_monitor_latency_show(struct device *dev,
 268					   struct device_attribute *dev_attr,
 269					   char *buf)
 270{
 271	struct hv_device *hv_dev = device_to_hv_device(dev);
 272
 273	if (!hv_dev->channel)
 274		return -ENODEV;
 275	return sysfs_emit(buf, "%d\n", channel_latency(hv_dev->channel,
 276			  vmbus_connection.monitor_pages[1]));
 277}
 278static DEVICE_ATTR_RO(client_monitor_latency);
 279
 280static ssize_t server_monitor_conn_id_show(struct device *dev,
 281					   struct device_attribute *dev_attr,
 282					   char *buf)
 283{
 284	struct hv_device *hv_dev = device_to_hv_device(dev);
 285
 286	if (!hv_dev->channel)
 287		return -ENODEV;
 288	return sysfs_emit(buf, "%d\n", channel_conn_id(hv_dev->channel,
 289			  vmbus_connection.monitor_pages[0]));
 290}
 291static DEVICE_ATTR_RO(server_monitor_conn_id);
 292
 293static ssize_t client_monitor_conn_id_show(struct device *dev,
 294					   struct device_attribute *dev_attr,
 295					   char *buf)
 296{
 297	struct hv_device *hv_dev = device_to_hv_device(dev);
 298
 299	if (!hv_dev->channel)
 300		return -ENODEV;
 301	return sysfs_emit(buf, "%d\n", channel_conn_id(hv_dev->channel,
 302			  vmbus_connection.monitor_pages[1]));
 303}
 304static DEVICE_ATTR_RO(client_monitor_conn_id);
 305
 306static ssize_t out_intr_mask_show(struct device *dev,
 307				  struct device_attribute *dev_attr, char *buf)
 308{
 309	struct hv_device *hv_dev = device_to_hv_device(dev);
 310	struct hv_ring_buffer_debug_info outbound;
 311	int ret;
 312
 313	if (!hv_dev->channel)
 314		return -ENODEV;
 315
 316	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound,
 317					  &outbound);
 318	if (ret < 0)
 319		return ret;
 320
 321	return sysfs_emit(buf, "%d\n", outbound.current_interrupt_mask);
 322}
 323static DEVICE_ATTR_RO(out_intr_mask);
 324
 325static ssize_t out_read_index_show(struct device *dev,
 326				   struct device_attribute *dev_attr, char *buf)
 327{
 328	struct hv_device *hv_dev = device_to_hv_device(dev);
 329	struct hv_ring_buffer_debug_info outbound;
 330	int ret;
 331
 332	if (!hv_dev->channel)
 333		return -ENODEV;
 334
 335	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound,
 336					  &outbound);
 337	if (ret < 0)
 338		return ret;
 339	return sysfs_emit(buf, "%u\n", outbound.current_read_index);
 340}
 341static DEVICE_ATTR_RO(out_read_index);
 342
 343static ssize_t out_write_index_show(struct device *dev,
 344				    struct device_attribute *dev_attr,
 345				    char *buf)
 346{
 347	struct hv_device *hv_dev = device_to_hv_device(dev);
 348	struct hv_ring_buffer_debug_info outbound;
 349	int ret;
 350
 351	if (!hv_dev->channel)
 352		return -ENODEV;
 353
 354	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound,
 355					  &outbound);
 356	if (ret < 0)
 357		return ret;
 358	return sysfs_emit(buf, "%u\n", outbound.current_write_index);
 359}
 360static DEVICE_ATTR_RO(out_write_index);
 361
 362static ssize_t out_read_bytes_avail_show(struct device *dev,
 363					 struct device_attribute *dev_attr,
 364					 char *buf)
 365{
 366	struct hv_device *hv_dev = device_to_hv_device(dev);
 367	struct hv_ring_buffer_debug_info outbound;
 368	int ret;
 369
 370	if (!hv_dev->channel)
 371		return -ENODEV;
 372
 373	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound,
 374					  &outbound);
 375	if (ret < 0)
 376		return ret;
 377	return sysfs_emit(buf, "%d\n", outbound.bytes_avail_toread);
 378}
 379static DEVICE_ATTR_RO(out_read_bytes_avail);
 380
 381static ssize_t out_write_bytes_avail_show(struct device *dev,
 382					  struct device_attribute *dev_attr,
 383					  char *buf)
 384{
 385	struct hv_device *hv_dev = device_to_hv_device(dev);
 386	struct hv_ring_buffer_debug_info outbound;
 387	int ret;
 388
 389	if (!hv_dev->channel)
 390		return -ENODEV;
 391
 392	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->outbound,
 393					  &outbound);
 394	if (ret < 0)
 395		return ret;
 396	return sysfs_emit(buf, "%d\n", outbound.bytes_avail_towrite);
 397}
 398static DEVICE_ATTR_RO(out_write_bytes_avail);
 399
 400static ssize_t in_intr_mask_show(struct device *dev,
 401				 struct device_attribute *dev_attr, char *buf)
 402{
 403	struct hv_device *hv_dev = device_to_hv_device(dev);
 404	struct hv_ring_buffer_debug_info inbound;
 405	int ret;
 406
 407	if (!hv_dev->channel)
 408		return -ENODEV;
 409
 410	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
 411	if (ret < 0)
 412		return ret;
 413
 414	return sysfs_emit(buf, "%d\n", inbound.current_interrupt_mask);
 415}
 416static DEVICE_ATTR_RO(in_intr_mask);
 417
 418static ssize_t in_read_index_show(struct device *dev,
 419				  struct device_attribute *dev_attr, char *buf)
 420{
 421	struct hv_device *hv_dev = device_to_hv_device(dev);
 422	struct hv_ring_buffer_debug_info inbound;
 423	int ret;
 424
 425	if (!hv_dev->channel)
 426		return -ENODEV;
 427
 428	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
 429	if (ret < 0)
 430		return ret;
 431
 432	return sysfs_emit(buf, "%d\n", inbound.current_read_index);
 433}
 434static DEVICE_ATTR_RO(in_read_index);
 435
 436static ssize_t in_write_index_show(struct device *dev,
 437				   struct device_attribute *dev_attr, char *buf)
 438{
 439	struct hv_device *hv_dev = device_to_hv_device(dev);
 440	struct hv_ring_buffer_debug_info inbound;
 441	int ret;
 442
 443	if (!hv_dev->channel)
 444		return -ENODEV;
 445
 446	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
 447	if (ret < 0)
 448		return ret;
 449
 450	return sysfs_emit(buf, "%d\n", inbound.current_write_index);
 451}
 452static DEVICE_ATTR_RO(in_write_index);
 453
 454static ssize_t in_read_bytes_avail_show(struct device *dev,
 455					struct device_attribute *dev_attr,
 456					char *buf)
 457{
 458	struct hv_device *hv_dev = device_to_hv_device(dev);
 459	struct hv_ring_buffer_debug_info inbound;
 460	int ret;
 461
 462	if (!hv_dev->channel)
 463		return -ENODEV;
 464
 465	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
 466	if (ret < 0)
 467		return ret;
 468
 469	return sysfs_emit(buf, "%d\n", inbound.bytes_avail_toread);
 470}
 471static DEVICE_ATTR_RO(in_read_bytes_avail);
 472
 473static ssize_t in_write_bytes_avail_show(struct device *dev,
 474					 struct device_attribute *dev_attr,
 475					 char *buf)
 476{
 477	struct hv_device *hv_dev = device_to_hv_device(dev);
 478	struct hv_ring_buffer_debug_info inbound;
 479	int ret;
 480
 481	if (!hv_dev->channel)
 482		return -ENODEV;
 483
 484	ret = hv_ringbuffer_get_debuginfo(&hv_dev->channel->inbound, &inbound);
 485	if (ret < 0)
 486		return ret;
 487
 488	return sysfs_emit(buf, "%d\n", inbound.bytes_avail_towrite);
 489}
 490static DEVICE_ATTR_RO(in_write_bytes_avail);
 491
 492static ssize_t channel_vp_mapping_show(struct device *dev,
 493				       struct device_attribute *dev_attr,
 494				       char *buf)
 495{
 496	struct hv_device *hv_dev = device_to_hv_device(dev);
 497	struct vmbus_channel *channel = hv_dev->channel, *cur_sc;
 498	int n_written;
 499	struct list_head *cur;
 500
 501	if (!channel)
 502		return -ENODEV;
 503
 504	mutex_lock(&vmbus_connection.channel_mutex);
 505
 506	n_written = sysfs_emit(buf, "%u:%u\n",
 507			       channel->offermsg.child_relid,
 508			       channel->target_cpu);
 509
 510	list_for_each(cur, &channel->sc_list) {
 511
 512		cur_sc = list_entry(cur, struct vmbus_channel, sc_list);
 513		n_written += sysfs_emit_at(buf, n_written, "%u:%u\n",
 514					  cur_sc->offermsg.child_relid,
 515					  cur_sc->target_cpu);
 516	}
 517
 518	mutex_unlock(&vmbus_connection.channel_mutex);
 519
 520	return n_written;
 521}
 522static DEVICE_ATTR_RO(channel_vp_mapping);
 523
 524static ssize_t vendor_show(struct device *dev,
 525			   struct device_attribute *dev_attr,
 526			   char *buf)
 527{
 528	struct hv_device *hv_dev = device_to_hv_device(dev);
 529
 530	return sysfs_emit(buf, "0x%x\n", hv_dev->vendor_id);
 531}
 532static DEVICE_ATTR_RO(vendor);
 533
 534static ssize_t device_show(struct device *dev,
 535			   struct device_attribute *dev_attr,
 536			   char *buf)
 537{
 538	struct hv_device *hv_dev = device_to_hv_device(dev);
 539
 540	return sysfs_emit(buf, "0x%x\n", hv_dev->device_id);
 541}
 542static DEVICE_ATTR_RO(device);
 543
 544static ssize_t driver_override_store(struct device *dev,
 545				     struct device_attribute *attr,
 546				     const char *buf, size_t count)
 547{
 548	struct hv_device *hv_dev = device_to_hv_device(dev);
 549	int ret;
 550
 551	ret = driver_set_override(dev, &hv_dev->driver_override, buf, count);
 552	if (ret)
 553		return ret;
 554
 555	return count;
 556}
 557
 558static ssize_t driver_override_show(struct device *dev,
 559				    struct device_attribute *attr, char *buf)
 560{
 561	struct hv_device *hv_dev = device_to_hv_device(dev);
 562	ssize_t len;
 563
 564	device_lock(dev);
 565	len = sysfs_emit(buf, "%s\n", hv_dev->driver_override);
 566	device_unlock(dev);
 567
 568	return len;
 569}
 570static DEVICE_ATTR_RW(driver_override);
 571
 572/* Set up per device attributes in /sys/bus/vmbus/devices/<bus device> */
 573static struct attribute *vmbus_dev_attrs[] = {
 574	&dev_attr_id.attr,
 575	&dev_attr_state.attr,
 576	&dev_attr_monitor_id.attr,
 577	&dev_attr_class_id.attr,
 578	&dev_attr_device_id.attr,
 579	&dev_attr_modalias.attr,
 580#ifdef CONFIG_NUMA
 581	&dev_attr_numa_node.attr,
 582#endif
 583	&dev_attr_server_monitor_pending.attr,
 584	&dev_attr_client_monitor_pending.attr,
 585	&dev_attr_server_monitor_latency.attr,
 586	&dev_attr_client_monitor_latency.attr,
 587	&dev_attr_server_monitor_conn_id.attr,
 588	&dev_attr_client_monitor_conn_id.attr,
 589	&dev_attr_out_intr_mask.attr,
 590	&dev_attr_out_read_index.attr,
 591	&dev_attr_out_write_index.attr,
 592	&dev_attr_out_read_bytes_avail.attr,
 593	&dev_attr_out_write_bytes_avail.attr,
 594	&dev_attr_in_intr_mask.attr,
 595	&dev_attr_in_read_index.attr,
 596	&dev_attr_in_write_index.attr,
 597	&dev_attr_in_read_bytes_avail.attr,
 598	&dev_attr_in_write_bytes_avail.attr,
 599	&dev_attr_channel_vp_mapping.attr,
 600	&dev_attr_vendor.attr,
 601	&dev_attr_device.attr,
 602	&dev_attr_driver_override.attr,
 603	NULL,
 604};
 605
 606/*
 607 * Device-level attribute_group callback function. Returns the permission for
 608 * each attribute, and returns 0 if an attribute is not visible.
 609 */
 610static umode_t vmbus_dev_attr_is_visible(struct kobject *kobj,
 611					 struct attribute *attr, int idx)
 612{
 613	struct device *dev = kobj_to_dev(kobj);
 614	const struct hv_device *hv_dev = device_to_hv_device(dev);
 615
 616	/* Hide the monitor attributes if the monitor mechanism is not used. */
 617	if (!hv_dev->channel->offermsg.monitor_allocated &&
 618	    (attr == &dev_attr_monitor_id.attr ||
 619	     attr == &dev_attr_server_monitor_pending.attr ||
 620	     attr == &dev_attr_client_monitor_pending.attr ||
 621	     attr == &dev_attr_server_monitor_latency.attr ||
 622	     attr == &dev_attr_client_monitor_latency.attr ||
 623	     attr == &dev_attr_server_monitor_conn_id.attr ||
 624	     attr == &dev_attr_client_monitor_conn_id.attr))
 625		return 0;
 626
 627	return attr->mode;
 628}
 629
 630static const struct attribute_group vmbus_dev_group = {
 631	.attrs = vmbus_dev_attrs,
 632	.is_visible = vmbus_dev_attr_is_visible
 633};
 634__ATTRIBUTE_GROUPS(vmbus_dev);
 635
 636/* Set up the attribute for /sys/bus/vmbus/hibernation */
 637static ssize_t hibernation_show(const struct bus_type *bus, char *buf)
 638{
 639	return sprintf(buf, "%d\n", !!hv_is_hibernation_supported());
 640}
 641
 642static BUS_ATTR_RO(hibernation);
 643
 644static struct attribute *vmbus_bus_attrs[] = {
 645	&bus_attr_hibernation.attr,
 646	NULL,
 647};
 648static const struct attribute_group vmbus_bus_group = {
 649	.attrs = vmbus_bus_attrs,
 650};
 651__ATTRIBUTE_GROUPS(vmbus_bus);
 652
 653/*
 654 * vmbus_uevent - add uevent for our device
 655 *
 656 * This routine is invoked when a device is added or removed on the vmbus to
 657 * generate a uevent to udev in the userspace. The udev will then look at its
 658 * rule and the uevent generated here to load the appropriate driver
 659 *
 660 * The alias string will be of the form vmbus:guid where guid is the string
 661 * representation of the device guid (each byte of the guid will be
 662 * represented with two hex characters.
 663 */
 664static int vmbus_uevent(const struct device *device, struct kobj_uevent_env *env)
 665{
 666	const struct hv_device *dev = device_to_hv_device(device);
 667	const char *format = "MODALIAS=vmbus:%*phN";
 668
 669	return add_uevent_var(env, format, UUID_SIZE, &dev->dev_type);
 670}
 671
 672static const struct hv_vmbus_device_id *
 673hv_vmbus_dev_match(const struct hv_vmbus_device_id *id, const guid_t *guid)
 674{
 675	if (id == NULL)
 676		return NULL; /* empty device table */
 677
 678	for (; !guid_is_null(&id->guid); id++)
 679		if (guid_equal(&id->guid, guid))
 680			return id;
 681
 682	return NULL;
 683}
 684
 685static const struct hv_vmbus_device_id *
 686hv_vmbus_dynid_match(struct hv_driver *drv, const guid_t *guid)
 687{
 688	const struct hv_vmbus_device_id *id = NULL;
 689	struct vmbus_dynid *dynid;
 690
 691	spin_lock(&drv->dynids.lock);
 692	list_for_each_entry(dynid, &drv->dynids.list, node) {
 693		if (guid_equal(&dynid->id.guid, guid)) {
 694			id = &dynid->id;
 695			break;
 696		}
 697	}
 698	spin_unlock(&drv->dynids.lock);
 699
 700	return id;
 701}
 702
 703static const struct hv_vmbus_device_id vmbus_device_null;
 704
 705/*
 706 * Return a matching hv_vmbus_device_id pointer.
 707 * If there is no match, return NULL.
 708 */
 709static const struct hv_vmbus_device_id *hv_vmbus_get_id(const struct hv_driver *drv,
 710							struct hv_device *dev)
 711{
 712	const guid_t *guid = &dev->dev_type;
 713	const struct hv_vmbus_device_id *id;
 714
 715	/* When driver_override is set, only bind to the matching driver */
 716	if (dev->driver_override && strcmp(dev->driver_override, drv->name))
 717		return NULL;
 718
 719	/* Look at the dynamic ids first, before the static ones */
 720	id = hv_vmbus_dynid_match((struct hv_driver *)drv, guid);
 721	if (!id)
 722		id = hv_vmbus_dev_match(drv->id_table, guid);
 723
 724	/* driver_override will always match, send a dummy id */
 725	if (!id && dev->driver_override)
 726		id = &vmbus_device_null;
 727
 728	return id;
 729}
 730
 731/* vmbus_add_dynid - add a new device ID to this driver and re-probe devices
 732 *
 733 * This function can race with vmbus_device_register(). This function is
 734 * typically running on a user thread in response to writing to the "new_id"
 735 * sysfs entry for a driver. vmbus_device_register() is running on a
 736 * workqueue thread in response to the Hyper-V host offering a device to the
 737 * guest. This function calls driver_attach(), which looks for an existing
 738 * device matching the new id, and attaches the driver to which the new id
 739 * has been assigned. vmbus_device_register() calls device_register(), which
 740 * looks for a driver that matches the device being registered. If both
 741 * operations are running simultaneously, the device driver probe function runs
 742 * on whichever thread establishes the linkage between the driver and device.
 743 *
 744 * In most cases, it doesn't matter which thread runs the driver probe
 745 * function. But if vmbus_device_register() does not find a matching driver,
 746 * it proceeds to create the "channels" subdirectory and numbered per-channel
 747 * subdirectory in sysfs. While that multi-step creation is in progress, this
 748 * function could run the driver probe function. If the probe function checks
 749 * for, or operates on, entries in the "channels" subdirectory, including by
 750 * calling hv_create_ring_sysfs(), the operation may or may not succeed
 751 * depending on the race. The race can't create a kernel failure in VMBus
 752 * or device subsystem code, but probe functions in VMBus drivers doing such
 753 * operations must be prepared for the failure case.
 754 */
 755static int vmbus_add_dynid(struct hv_driver *drv, guid_t *guid)
 756{
 757	struct vmbus_dynid *dynid;
 758
 759	dynid = kzalloc(sizeof(*dynid), GFP_KERNEL);
 760	if (!dynid)
 761		return -ENOMEM;
 762
 763	dynid->id.guid = *guid;
 764
 765	spin_lock(&drv->dynids.lock);
 766	list_add_tail(&dynid->node, &drv->dynids.list);
 767	spin_unlock(&drv->dynids.lock);
 768
 769	return driver_attach(&drv->driver);
 770}
 771
 772static void vmbus_free_dynids(struct hv_driver *drv)
 773{
 774	struct vmbus_dynid *dynid, *n;
 775
 776	spin_lock(&drv->dynids.lock);
 777	list_for_each_entry_safe(dynid, n, &drv->dynids.list, node) {
 778		list_del(&dynid->node);
 779		kfree(dynid);
 780	}
 781	spin_unlock(&drv->dynids.lock);
 782}
 783
 784/*
 785 * store_new_id - sysfs frontend to vmbus_add_dynid()
 786 *
 787 * Allow GUIDs to be added to an existing driver via sysfs.
 788 */
 789static ssize_t new_id_store(struct device_driver *driver, const char *buf,
 790			    size_t count)
 791{
 792	struct hv_driver *drv = drv_to_hv_drv(driver);
 793	guid_t guid;
 794	ssize_t retval;
 795
 796	retval = guid_parse(buf, &guid);
 797	if (retval)
 798		return retval;
 799
 800	if (hv_vmbus_dynid_match(drv, &guid))
 801		return -EEXIST;
 802
 803	retval = vmbus_add_dynid(drv, &guid);
 804	if (retval)
 805		return retval;
 806	return count;
 807}
 808static DRIVER_ATTR_WO(new_id);
 809
 810/*
 811 * store_remove_id - remove a PCI device ID from this driver
 812 *
 813 * Removes a dynamic pci device ID to this driver.
 814 */
 815static ssize_t remove_id_store(struct device_driver *driver, const char *buf,
 816			       size_t count)
 817{
 818	struct hv_driver *drv = drv_to_hv_drv(driver);
 819	struct vmbus_dynid *dynid, *n;
 820	guid_t guid;
 821	ssize_t retval;
 822
 823	retval = guid_parse(buf, &guid);
 824	if (retval)
 825		return retval;
 826
 827	retval = -ENODEV;
 828	spin_lock(&drv->dynids.lock);
 829	list_for_each_entry_safe(dynid, n, &drv->dynids.list, node) {
 830		struct hv_vmbus_device_id *id = &dynid->id;
 831
 832		if (guid_equal(&id->guid, &guid)) {
 833			list_del(&dynid->node);
 834			kfree(dynid);
 835			retval = count;
 836			break;
 837		}
 838	}
 839	spin_unlock(&drv->dynids.lock);
 840
 841	return retval;
 842}
 843static DRIVER_ATTR_WO(remove_id);
 844
 845static struct attribute *vmbus_drv_attrs[] = {
 846	&driver_attr_new_id.attr,
 847	&driver_attr_remove_id.attr,
 848	NULL,
 849};
 850ATTRIBUTE_GROUPS(vmbus_drv);
 851
 852
 853/*
 854 * vmbus_match - Attempt to match the specified device to the specified driver
 855 */
 856static int vmbus_match(struct device *device, const struct device_driver *driver)
 857{
 858	const struct hv_driver *drv = drv_to_hv_drv(driver);
 859	struct hv_device *hv_dev = device_to_hv_device(device);
 860
 861	/* The hv_sock driver handles all hv_sock offers. */
 862	if (is_hvsock_channel(hv_dev->channel))
 863		return drv->hvsock;
 864
 865	if (hv_vmbus_get_id(drv, hv_dev))
 866		return 1;
 867
 868	return 0;
 869}
 870
 871/*
 872 * vmbus_probe - Add the new vmbus's child device
 873 */
 874static int vmbus_probe(struct device *child_device)
 875{
 876	int ret = 0;
 877	struct hv_driver *drv =
 878			drv_to_hv_drv(child_device->driver);
 879	struct hv_device *dev = device_to_hv_device(child_device);
 880	const struct hv_vmbus_device_id *dev_id;
 881
 882	dev_id = hv_vmbus_get_id(drv, dev);
 883	if (drv->probe) {
 884		ret = drv->probe(dev, dev_id);
 885		if (ret != 0)
 886			pr_err("probe failed for device %s (%d)\n",
 887			       dev_name(child_device), ret);
 888
 889	} else {
 890		pr_err("probe not set for driver %s\n",
 891		       dev_name(child_device));
 892		ret = -ENODEV;
 893	}
 894	return ret;
 895}
 896
 897/*
 898 * vmbus_dma_configure -- Configure DMA coherence for VMbus device
 899 */
 900static int vmbus_dma_configure(struct device *child_device)
 901{
 902	/*
 903	 * On ARM64, propagate the DMA coherence setting from the top level
 904	 * VMbus ACPI device to the child VMbus device being added here.
 905	 * On x86/x64 coherence is assumed and these calls have no effect.
 906	 */
 907	hv_setup_dma_ops(child_device,
 908		device_get_dma_attr(vmbus_root_device) == DEV_DMA_COHERENT);
 909	return 0;
 910}
 911
 912/*
 913 * vmbus_remove - Remove a vmbus device
 914 */
 915static void vmbus_remove(struct device *child_device)
 916{
 917	struct hv_driver *drv;
 918	struct hv_device *dev = device_to_hv_device(child_device);
 919
 920	if (child_device->driver) {
 921		drv = drv_to_hv_drv(child_device->driver);
 922		if (drv->remove)
 923			drv->remove(dev);
 924	}
 925}
 926
 927/*
 928 * vmbus_shutdown - Shutdown a vmbus device
 929 */
 930static void vmbus_shutdown(struct device *child_device)
 931{
 932	struct hv_driver *drv;
 933	struct hv_device *dev = device_to_hv_device(child_device);
 934
 935
 936	/* The device may not be attached yet */
 937	if (!child_device->driver)
 938		return;
 939
 940	drv = drv_to_hv_drv(child_device->driver);
 941
 942	if (drv->shutdown)
 943		drv->shutdown(dev);
 944}
 945
 946#ifdef CONFIG_PM_SLEEP
 947/*
 948 * vmbus_suspend - Suspend a vmbus device
 949 */
 950static int vmbus_suspend(struct device *child_device)
 951{
 952	struct hv_driver *drv;
 953	struct hv_device *dev = device_to_hv_device(child_device);
 954
 955	/* The device may not be attached yet */
 956	if (!child_device->driver)
 957		return 0;
 958
 959	drv = drv_to_hv_drv(child_device->driver);
 960	if (!drv->suspend)
 961		return -EOPNOTSUPP;
 962
 963	return drv->suspend(dev);
 964}
 965
 966/*
 967 * vmbus_resume - Resume a vmbus device
 968 */
 969static int vmbus_resume(struct device *child_device)
 970{
 971	struct hv_driver *drv;
 972	struct hv_device *dev = device_to_hv_device(child_device);
 973
 974	/* The device may not be attached yet */
 975	if (!child_device->driver)
 976		return 0;
 977
 978	drv = drv_to_hv_drv(child_device->driver);
 979	if (!drv->resume)
 980		return -EOPNOTSUPP;
 981
 982	return drv->resume(dev);
 983}
 984#else
 985#define vmbus_suspend NULL
 986#define vmbus_resume NULL
 987#endif /* CONFIG_PM_SLEEP */
 988
 989/*
 990 * vmbus_device_release - Final callback release of the vmbus child device
 991 */
 992static void vmbus_device_release(struct device *device)
 993{
 994	struct hv_device *hv_dev = device_to_hv_device(device);
 995	struct vmbus_channel *channel = hv_dev->channel;
 996
 997	hv_debug_rm_dev_dir(hv_dev);
 998
 999	mutex_lock(&vmbus_connection.channel_mutex);
1000	hv_process_channel_removal(channel);
1001	mutex_unlock(&vmbus_connection.channel_mutex);
1002	kfree(hv_dev);
1003}
1004
1005/*
1006 * Note: we must use the "noirq" ops: see the comment before vmbus_bus_pm.
1007 *
1008 * suspend_noirq/resume_noirq are set to NULL to support Suspend-to-Idle: we
1009 * shouldn't suspend the vmbus devices upon Suspend-to-Idle, otherwise there
1010 * is no way to wake up a Generation-2 VM.
1011 *
1012 * The other 4 ops are for hibernation.
1013 */
1014
1015static const struct dev_pm_ops vmbus_pm = {
1016	.suspend_noirq	= NULL,
1017	.resume_noirq	= NULL,
1018	.freeze_noirq	= vmbus_suspend,
1019	.thaw_noirq	= vmbus_resume,
1020	.poweroff_noirq	= vmbus_suspend,
1021	.restore_noirq	= vmbus_resume,
1022};
1023
1024/* The one and only one */
1025static const struct bus_type  hv_bus = {
1026	.name =		"vmbus",
1027	.match =		vmbus_match,
1028	.shutdown =		vmbus_shutdown,
1029	.remove =		vmbus_remove,
1030	.probe =		vmbus_probe,
1031	.uevent =		vmbus_uevent,
1032	.dma_configure =	vmbus_dma_configure,
1033	.dev_groups =		vmbus_dev_groups,
1034	.drv_groups =		vmbus_drv_groups,
1035	.bus_groups =		vmbus_bus_groups,
1036	.pm =			&vmbus_pm,
1037};
1038
1039struct onmessage_work_context {
1040	struct work_struct work;
1041	struct {
1042		struct hv_message_header header;
1043		u8 payload[];
1044	} msg;
1045};
1046
1047static void vmbus_onmessage_work(struct work_struct *work)
1048{
1049	struct onmessage_work_context *ctx;
1050
1051	/* Do not process messages if we're in DISCONNECTED state */
1052	if (vmbus_connection.conn_state == DISCONNECTED)
1053		return;
1054
1055	ctx = container_of(work, struct onmessage_work_context,
1056			   work);
1057	vmbus_onmessage((struct vmbus_channel_message_header *)
1058			&ctx->msg.payload);
1059	kfree(ctx);
1060}
1061
1062static void __vmbus_on_msg_dpc(void *message_page_addr)
1063{
1064	struct hv_message msg_copy, *msg;
1065	struct vmbus_channel_message_header *hdr;
1066	enum vmbus_channel_message_type msgtype;
1067	const struct vmbus_channel_message_table_entry *entry;
1068	struct onmessage_work_context *ctx;
1069	__u8 payload_size;
1070	u32 message_type;
1071
1072	if (!message_page_addr)
1073		return;
1074	msg = (struct hv_message *)message_page_addr + VMBUS_MESSAGE_SINT;
1075
1076	/*
1077	 * 'enum vmbus_channel_message_type' is supposed to always be 'u32' as
1078	 * it is being used in 'struct vmbus_channel_message_header' definition
1079	 * which is supposed to match hypervisor ABI.
1080	 */
1081	BUILD_BUG_ON(sizeof(enum vmbus_channel_message_type) != sizeof(u32));
1082
1083	/*
1084	 * Since the message is in memory shared with the host, an erroneous or
1085	 * malicious Hyper-V could modify the message while vmbus_on_msg_dpc()
1086	 * or individual message handlers are executing; to prevent this, copy
1087	 * the message into private memory.
1088	 */
1089	memcpy(&msg_copy, msg, sizeof(struct hv_message));
1090
1091	message_type = msg_copy.header.message_type;
1092	if (message_type == HVMSG_NONE)
1093		/* no msg */
1094		return;
1095
1096	hdr = (struct vmbus_channel_message_header *)msg_copy.u.payload;
1097	msgtype = hdr->msgtype;
1098
1099	trace_vmbus_on_msg_dpc(hdr);
1100
1101	if (msgtype >= CHANNELMSG_COUNT) {
1102		WARN_ONCE(1, "unknown msgtype=%d\n", msgtype);
1103		goto msg_handled;
1104	}
1105
1106	payload_size = msg_copy.header.payload_size;
1107	if (payload_size > HV_MESSAGE_PAYLOAD_BYTE_COUNT) {
1108		WARN_ONCE(1, "payload size is too large (%d)\n", payload_size);
1109		goto msg_handled;
1110	}
1111
1112	entry = &channel_message_table[msgtype];
1113
1114	if (!entry->message_handler)
1115		goto msg_handled;
1116
1117	if (payload_size < entry->min_payload_len) {
1118		WARN_ONCE(1, "message too short: msgtype=%d len=%d\n", msgtype, payload_size);
1119		goto msg_handled;
1120	}
1121
1122	if (entry->handler_type	== VMHT_BLOCKING) {
1123		ctx = kmalloc(struct_size(ctx, msg.payload, payload_size), GFP_ATOMIC);
1124		if (ctx == NULL)
1125			return;
1126
1127		INIT_WORK(&ctx->work, vmbus_onmessage_work);
1128		ctx->msg.header = msg_copy.header;
1129		memcpy(&ctx->msg.payload, msg_copy.u.payload, payload_size);
1130
1131		/*
1132		 * The host can generate a rescind message while we
1133		 * may still be handling the original offer. We deal with
1134		 * this condition by relying on the synchronization provided
1135		 * by offer_in_progress and by channel_mutex.  See also the
1136		 * inline comments in vmbus_onoffer_rescind().
1137		 */
1138		switch (msgtype) {
1139		case CHANNELMSG_RESCIND_CHANNELOFFER:
1140			/*
1141			 * If we are handling the rescind message;
1142			 * schedule the work on the global work queue.
1143			 *
1144			 * The OFFER message and the RESCIND message should
1145			 * not be handled by the same serialized work queue,
1146			 * because the OFFER handler may call vmbus_open(),
1147			 * which tries to open the channel by sending an
1148			 * OPEN_CHANNEL message to the host and waits for
1149			 * the host's response; however, if the host has
1150			 * rescinded the channel before it receives the
1151			 * OPEN_CHANNEL message, the host just silently
1152			 * ignores the OPEN_CHANNEL message; as a result,
1153			 * the guest's OFFER handler hangs for ever, if we
1154			 * handle the RESCIND message in the same serialized
1155			 * work queue: the RESCIND handler can not start to
1156			 * run before the OFFER handler finishes.
1157			 */
1158			if (vmbus_connection.ignore_any_offer_msg)
1159				break;
1160			queue_work(vmbus_connection.rescind_work_queue, &ctx->work);
1161			break;
1162
1163		case CHANNELMSG_OFFERCHANNEL:
1164			/*
1165			 * The host sends the offer message of a given channel
1166			 * before sending the rescind message of the same
1167			 * channel.  These messages are sent to the guest's
1168			 * connect CPU; the guest then starts processing them
1169			 * in the tasklet handler on this CPU:
1170			 *
1171			 * VMBUS_CONNECT_CPU
1172			 *
1173			 * [vmbus_on_msg_dpc()]
1174			 * atomic_inc()  // CHANNELMSG_OFFERCHANNEL
1175			 * queue_work()
1176			 * ...
1177			 * [vmbus_on_msg_dpc()]
1178			 * schedule_work()  // CHANNELMSG_RESCIND_CHANNELOFFER
1179			 *
1180			 * We rely on the memory-ordering properties of the
1181			 * queue_work() and schedule_work() primitives, which
1182			 * guarantee that the atomic increment will be visible
1183			 * to the CPUs which will execute the offer & rescind
1184			 * works by the time these works will start execution.
1185			 */
1186			if (vmbus_connection.ignore_any_offer_msg)
1187				break;
1188			atomic_inc(&vmbus_connection.offer_in_progress);
1189			fallthrough;
1190
1191		default:
1192			queue_work(vmbus_connection.work_queue, &ctx->work);
1193		}
1194	} else
1195		entry->message_handler(hdr);
1196
1197msg_handled:
1198	vmbus_signal_eom(msg, message_type);
1199}
1200
1201void vmbus_on_msg_dpc(unsigned long data)
1202{
1203	struct hv_per_cpu_context *hv_cpu = (void *)data;
1204
1205	__vmbus_on_msg_dpc(hv_cpu->hyp_synic_message_page);
1206	__vmbus_on_msg_dpc(hv_cpu->para_synic_message_page);
1207}
1208
1209#ifdef CONFIG_PM_SLEEP
1210/*
1211 * Fake RESCIND_CHANNEL messages to clean up hv_sock channels by force for
1212 * hibernation, because hv_sock connections can not persist across hibernation.
1213 */
1214static void vmbus_force_channel_rescinded(struct vmbus_channel *channel)
1215{
1216	struct onmessage_work_context *ctx;
1217	struct vmbus_channel_rescind_offer *rescind;
1218
1219	WARN_ON(!is_hvsock_channel(channel));
1220
1221	/*
1222	 * Allocation size is small and the allocation should really not fail,
1223	 * otherwise the state of the hv_sock connections ends up in limbo.
1224	 */
1225	ctx = kzalloc(sizeof(*ctx) + sizeof(*rescind),
1226		      GFP_KERNEL | __GFP_NOFAIL);
1227
1228	/*
1229	 * So far, these are not really used by Linux. Just set them to the
1230	 * reasonable values conforming to the definitions of the fields.
1231	 */
1232	ctx->msg.header.message_type = 1;
1233	ctx->msg.header.payload_size = sizeof(*rescind);
1234
1235	/* These values are actually used by Linux. */
1236	rescind = (struct vmbus_channel_rescind_offer *)ctx->msg.payload;
1237	rescind->header.msgtype = CHANNELMSG_RESCIND_CHANNELOFFER;
1238	rescind->child_relid = channel->offermsg.child_relid;
1239
1240	INIT_WORK(&ctx->work, vmbus_onmessage_work);
1241
1242	queue_work(vmbus_connection.work_queue, &ctx->work);
1243}
1244#endif /* CONFIG_PM_SLEEP */
1245
1246/*
1247 * Schedule all channels with events pending.
1248 * The event page can be directly checked to get the id of
1249 * the channel that has the interrupt pending.
1250 */
1251static void vmbus_chan_sched(void *event_page_addr)
1252{
1253	unsigned long *recv_int_page;
1254	u32 maxbits, relid;
1255	union hv_synic_event_flags *event;
1256
1257	if (!event_page_addr)
1258		return;
1259	event = (union hv_synic_event_flags *)event_page_addr + VMBUS_MESSAGE_SINT;
1260
1261	maxbits = HV_EVENT_FLAGS_COUNT;
1262	recv_int_page = event->flags;
1263
1264	if (unlikely(!recv_int_page))
1265		return;
1266
1267	/*
1268	 * Suggested-by: Michael Kelley <mhklinux@outlook.com>
1269	 * One possible optimization would be to keep track of the largest relID that's in use,
1270	 * and only scan up to that relID.
1271	 */
1272	for_each_set_bit(relid, recv_int_page, maxbits) {
1273		void (*callback_fn)(void *context);
1274		struct vmbus_channel *channel;
1275
1276		if (!sync_test_and_clear_bit(relid, recv_int_page))
1277			continue;
1278
1279		/* Special case - vmbus channel protocol msg */
1280		if (relid == 0)
1281			continue;
1282
1283		/*
1284		 * Pairs with the kfree_rcu() in vmbus_chan_release().
1285		 * Guarantees that the channel data structure doesn't
1286		 * get freed while the channel pointer below is being
1287		 * dereferenced.
1288		 */
1289		rcu_read_lock();
1290
1291		/* Find channel based on relid */
1292		channel = relid2channel(relid);
1293		if (channel == NULL)
1294			goto sched_unlock_rcu;
1295
1296		if (channel->rescind)
1297			goto sched_unlock_rcu;
1298
1299		/*
1300		 * Make sure that the ring buffer data structure doesn't get
1301		 * freed while we dereference the ring buffer pointer.  Test
1302		 * for the channel's onchannel_callback being NULL within a
1303		 * sched_lock critical section.  See also the inline comments
1304		 * in vmbus_reset_channel_cb().
1305		 */
1306		spin_lock(&channel->sched_lock);
1307
1308		callback_fn = channel->onchannel_callback;
1309		if (unlikely(callback_fn == NULL))
1310			goto sched_unlock;
1311
1312		trace_vmbus_chan_sched(channel);
1313
1314		++channel->interrupts;
1315
1316		switch (channel->callback_mode) {
1317		case HV_CALL_ISR:
1318			(*callback_fn)(channel->channel_callback_context);
1319			break;
1320
1321		case HV_CALL_BATCHED:
1322			hv_begin_read(&channel->inbound);
1323			fallthrough;
1324		case HV_CALL_DIRECT:
1325			tasklet_schedule(&channel->callback_event);
1326		}
1327
1328sched_unlock:
1329		spin_unlock(&channel->sched_lock);
1330sched_unlock_rcu:
1331		rcu_read_unlock();
1332	}
1333}
1334
1335static void vmbus_message_sched(struct hv_per_cpu_context *hv_cpu, void *message_page_addr)
1336{
1337	struct hv_message *msg;
1338
1339	if (!message_page_addr)
1340		return;
1341	msg = (struct hv_message *)message_page_addr + VMBUS_MESSAGE_SINT;
1342
1343	/* Check if there are actual msgs to be processed */
1344	if (msg->header.message_type != HVMSG_NONE) {
1345		if (msg->header.message_type == HVMSG_TIMER_EXPIRED) {
1346			hv_stimer0_isr();
1347			vmbus_signal_eom(msg, HVMSG_TIMER_EXPIRED);
1348		} else {
1349			tasklet_schedule(&hv_cpu->msg_dpc);
1350		}
1351	}
1352}
1353
1354static void __vmbus_isr(void)
1355{
1356	struct hv_per_cpu_context *hv_cpu
1357		= this_cpu_ptr(hv_context.cpu_context);
1358
1359	vmbus_chan_sched(hv_cpu->hyp_synic_event_page);
1360	vmbus_chan_sched(hv_cpu->para_synic_event_page);
1361
1362	vmbus_message_sched(hv_cpu, hv_cpu->hyp_synic_message_page);
1363	vmbus_message_sched(hv_cpu, hv_cpu->para_synic_message_page);
1364
1365	add_interrupt_randomness(vmbus_interrupt);
1366}
1367
1368static DEFINE_PER_CPU(bool, vmbus_irq_pending);
1369static DEFINE_PER_CPU(struct task_struct *, vmbus_irqd);
1370
1371static void vmbus_irqd_wake(void)
1372{
1373	struct task_struct *tsk = __this_cpu_read(vmbus_irqd);
1374
1375	__this_cpu_write(vmbus_irq_pending, true);
1376	wake_up_process(tsk);
1377}
1378
1379static void vmbus_irqd_setup(unsigned int cpu)
1380{
1381	sched_set_fifo(current);
1382}
1383
1384static int vmbus_irqd_should_run(unsigned int cpu)
1385{
1386	return __this_cpu_read(vmbus_irq_pending);
1387}
1388
1389static void run_vmbus_irqd(unsigned int cpu)
1390{
1391	__this_cpu_write(vmbus_irq_pending, false);
1392	__vmbus_isr();
1393}
1394
1395static bool vmbus_irq_initialized;
1396
1397static struct smp_hotplug_thread vmbus_irq_threads = {
1398	.store                  = &vmbus_irqd,
1399	.setup			= vmbus_irqd_setup,
1400	.thread_should_run      = vmbus_irqd_should_run,
1401	.thread_fn              = run_vmbus_irqd,
1402	.thread_comm            = "vmbus_irq/%u",
1403};
1404
1405void vmbus_isr(void)
1406{
1407	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
1408		vmbus_irqd_wake();
1409	} else {
1410		lockdep_hardirq_threaded();
1411		__vmbus_isr();
1412	}
1413}
1414EXPORT_SYMBOL_FOR_MODULES(vmbus_isr, "mshv_vtl");
1415
1416static irqreturn_t vmbus_percpu_isr(int irq, void *dev_id)
1417{
1418	vmbus_isr();
1419	return IRQ_HANDLED;
1420}
1421
1422static void vmbus_percpu_work(struct work_struct *work)
1423{
1424	unsigned int cpu = smp_processor_id();
1425
1426	hv_synic_init(cpu);
1427}
1428
1429static int vmbus_alloc_synic_and_connect(void)
1430{
1431	int ret, cpu;
1432	struct work_struct __percpu *works;
1433	int hyperv_cpuhp_online;
1434
1435	ret = hv_synic_alloc();
1436	if (ret < 0)
1437		goto err_alloc;
1438
1439	works = alloc_percpu(struct work_struct);
1440	if (!works) {
1441		ret = -ENOMEM;
1442		goto err_alloc;
1443	}
1444
1445	/*
1446	 * Initialize the per-cpu interrupt state and stimer state.
1447	 * Then connect to the host.
1448	 */
1449	cpus_read_lock();
1450	for_each_online_cpu(cpu) {
1451		struct work_struct *work = per_cpu_ptr(works, cpu);
1452
1453		INIT_WORK(work, vmbus_percpu_work);
1454		schedule_work_on(cpu, work);
1455	}
1456
1457	for_each_online_cpu(cpu)
1458		flush_work(per_cpu_ptr(works, cpu));
1459
1460	/* Register the callbacks for possible CPU online/offline'ing */
1461	ret = cpuhp_setup_state_nocalls_cpuslocked(CPUHP_AP_ONLINE_DYN, "hyperv/vmbus:online",
1462						   hv_synic_init, hv_synic_cleanup);
1463	cpus_read_unlock();
1464	free_percpu(works);
1465	if (ret < 0)
1466		goto err_alloc;
1467	hyperv_cpuhp_online = ret;
1468
1469	ret = vmbus_connect();
1470	if (ret)
1471		goto err_connect;
1472	return 0;
1473
1474err_connect:
1475	cpuhp_remove_state(hyperv_cpuhp_online);
1476	return -ENODEV;
1477err_alloc:
1478	hv_synic_free();
1479	return -ENOMEM;
1480}
1481
1482/*
1483 * vmbus_bus_init -Main vmbus driver initialization routine.
1484 *
1485 * Here, we
1486 *	- initialize the vmbus driver context
1487 *	- invoke the vmbus hv main init routine
1488 *	- retrieve the channel offers
1489 */
1490static int vmbus_bus_init(void)
1491{
1492	int ret;
1493
1494	ret = hv_init();
1495	if (ret != 0) {
1496		pr_err("Unable to initialize the hypervisor - 0x%x\n", ret);
1497		return ret;
1498	}
1499
1500	ret = bus_register(&hv_bus);
1501	if (ret)
1502		return ret;
1503
1504	/*
1505	 * VMbus interrupts are best modeled as per-cpu interrupts. If
1506	 * on an architecture with support for per-cpu IRQs (e.g. ARM64),
1507	 * allocate a per-cpu IRQ using standard Linux kernel functionality.
1508	 * If not on such an architecture (e.g., x86/x64), then rely on
1509	 * code in the arch-specific portion of the code tree to connect
1510	 * the VMbus interrupt handler.
1511	 */
1512
1513	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !vmbus_irq_initialized) {
1514		ret = smpboot_register_percpu_thread(&vmbus_irq_threads);
1515		if (ret)
1516			goto err_kthread;
1517		vmbus_irq_initialized = true;
1518	}
1519
1520	if (vmbus_irq == -1) {
1521		hv_setup_vmbus_handler(vmbus_isr);
1522	} else {
1523		vmbus_evt = alloc_percpu(long);
1524		ret = request_percpu_irq(vmbus_irq, vmbus_percpu_isr,
1525				"Hyper-V VMbus", vmbus_evt);
1526		if (ret) {
1527			pr_err("Can't request Hyper-V VMbus IRQ %d, Err %d",
1528					vmbus_irq, ret);
1529			free_percpu(vmbus_evt);
1530			goto err_setup;
1531		}
1532	}
1533
1534	/*
1535	 * Cache the value as getting it involves a VM exit on x86(_64), and
1536	 * doing that on each VP while initializing SynIC's wastes time.
1537	 */
1538	is_confidential = ms_hyperv.confidential_vmbus_available;
1539	if (is_confidential)
1540		pr_info("Establishing connection to the confidential VMBus\n");
1541	hv_para_set_sint_proxy(!is_confidential);
1542	ret = vmbus_alloc_synic_and_connect();
1543	if (ret)
1544		goto err_connect;
1545
1546	/*
1547	 * Always register the vmbus unload panic notifier because we
1548	 * need to shut the VMbus channel connection on panic.
1549	 */
1550	atomic_notifier_chain_register(&panic_notifier_list,
1551			       &hyperv_panic_vmbus_unload_block);
1552
1553	vmbus_request_offers();
1554
1555	return 0;
1556
1557err_connect:
1558	if (vmbus_irq == -1) {
1559		hv_remove_vmbus_handler();
1560	} else {
1561		free_percpu_irq(vmbus_irq, vmbus_evt);
1562		free_percpu(vmbus_evt);
1563	}
1564err_setup:
1565	if (IS_ENABLED(CONFIG_PREEMPT_RT) && vmbus_irq_initialized) {
1566		smpboot_unregister_percpu_thread(&vmbus_irq_threads);
1567		vmbus_irq_initialized = false;
1568	}
1569err_kthread:
1570	bus_unregister(&hv_bus);
1571	return ret;
1572}
1573
1574/**
1575 * __vmbus_driver_register() - Register a vmbus's driver
1576 * @hv_driver: Pointer to driver structure you want to register
1577 * @owner: owner module of the drv
1578 * @mod_name: module name string
1579 *
1580 * Registers the given driver with Linux through the 'driver_register()' call
1581 * and sets up the hyper-v vmbus handling for this driver.
1582 * It will return the state of the 'driver_register()' call.
1583 *
1584 */
1585int __vmbus_driver_register(struct hv_driver *hv_driver, struct module *owner, const char *mod_name)
1586{
1587	int ret;
1588
1589	pr_info("registering driver %s\n", hv_driver->name);
1590
1591	ret = vmbus_exists();
1592	if (ret < 0)
1593		return ret;
1594
1595	hv_driver->driver.name = hv_driver->name;
1596	hv_driver->driver.owner = owner;
1597	hv_driver->driver.mod_name = mod_name;
1598	hv_driver->driver.bus = &hv_bus;
1599
1600	spin_lock_init(&hv_driver->dynids.lock);
1601	INIT_LIST_HEAD(&hv_driver->dynids.list);
1602
1603	ret = driver_register(&hv_driver->driver);
1604
1605	return ret;
1606}
1607EXPORT_SYMBOL_GPL(__vmbus_driver_register);
1608
1609/**
1610 * vmbus_driver_unregister() - Unregister a vmbus's driver
1611 * @hv_driver: Pointer to driver structure you want to
1612 *             un-register
1613 *
1614 * Un-register the given driver that was previous registered with a call to
1615 * vmbus_driver_register()
1616 */
1617void vmbus_driver_unregister(struct hv_driver *hv_driver)
1618{
1619	pr_info("unregistering driver %s\n", hv_driver->name);
1620
1621	if (!vmbus_exists()) {
1622		driver_unregister(&hv_driver->driver);
1623		vmbus_free_dynids(hv_driver);
1624	}
1625}
1626EXPORT_SYMBOL_GPL(vmbus_driver_unregister);
1627
1628
1629/*
1630 * Called when last reference to channel is gone.
1631 */
1632static void vmbus_chan_release(struct kobject *kobj)
1633{
1634	struct vmbus_channel *channel
1635		= container_of(kobj, struct vmbus_channel, kobj);
1636
1637	kfree_rcu(channel, rcu);
1638}
1639
1640struct vmbus_chan_attribute {
1641	struct attribute attr;
1642	ssize_t (*show)(struct vmbus_channel *chan, char *buf);
1643	ssize_t (*store)(struct vmbus_channel *chan,
1644			 const char *buf, size_t count);
1645};
1646#define VMBUS_CHAN_ATTR(_name, _mode, _show, _store) \
1647	struct vmbus_chan_attribute chan_attr_##_name \
1648		= __ATTR(_name, _mode, _show, _store)
1649#define VMBUS_CHAN_ATTR_RW(_name) \
1650	struct vmbus_chan_attribute chan_attr_##_name = __ATTR_RW(_name)
1651#define VMBUS_CHAN_ATTR_RO(_name) \
1652	struct vmbus_chan_attribute chan_attr_##_name = __ATTR_RO(_name)
1653#define VMBUS_CHAN_ATTR_WO(_name) \
1654	struct vmbus_chan_attribute chan_attr_##_name = __ATTR_WO(_name)
1655
1656static ssize_t vmbus_chan_attr_show(struct kobject *kobj,
1657				    struct attribute *attr, char *buf)
1658{
1659	const struct vmbus_chan_attribute *attribute
1660		= container_of(attr, struct vmbus_chan_attribute, attr);
1661	struct vmbus_channel *chan
1662		= container_of(kobj, struct vmbus_channel, kobj);
1663
1664	if (!attribute->show)
1665		return -EIO;
1666
1667	return attribute->show(chan, buf);
1668}
1669
1670static ssize_t vmbus_chan_attr_store(struct kobject *kobj,
1671				     struct attribute *attr, const char *buf,
1672				     size_t count)
1673{
1674	const struct vmbus_chan_attribute *attribute
1675		= container_of(attr, struct vmbus_chan_attribute, attr);
1676	struct vmbus_channel *chan
1677		= container_of(kobj, struct vmbus_channel, kobj);
1678
1679	if (!attribute->store)
1680		return -EIO;
1681
1682	return attribute->store(chan, buf, count);
1683}
1684
1685static const struct sysfs_ops vmbus_chan_sysfs_ops = {
1686	.show = vmbus_chan_attr_show,
1687	.store = vmbus_chan_attr_store,
1688};
1689
1690static ssize_t out_mask_show(struct vmbus_channel *channel, char *buf)
1691{
1692	struct hv_ring_buffer_info *rbi = &channel->outbound;
1693	ssize_t ret;
1694
1695	mutex_lock(&rbi->ring_buffer_mutex);
1696	if (!rbi->ring_buffer) {
1697		mutex_unlock(&rbi->ring_buffer_mutex);
1698		return -EINVAL;
1699	}
1700
1701	ret = sprintf(buf, "%u\n", rbi->ring_buffer->interrupt_mask);
1702	mutex_unlock(&rbi->ring_buffer_mutex);
1703	return ret;
1704}
1705static VMBUS_CHAN_ATTR_RO(out_mask);
1706
1707static ssize_t in_mask_show(struct vmbus_channel *channel, char *buf)
1708{
1709	struct hv_ring_buffer_info *rbi = &channel->inbound;
1710	ssize_t ret;
1711
1712	mutex_lock(&rbi->ring_buffer_mutex);
1713	if (!rbi->ring_buffer) {
1714		mutex_unlock(&rbi->ring_buffer_mutex);
1715		return -EINVAL;
1716	}
1717
1718	ret = sprintf(buf, "%u\n", rbi->ring_buffer->interrupt_mask);
1719	mutex_unlock(&rbi->ring_buffer_mutex);
1720	return ret;
1721}
1722static VMBUS_CHAN_ATTR_RO(in_mask);
1723
1724static ssize_t read_avail_show(struct vmbus_channel *channel, char *buf)
1725{
1726	struct hv_ring_buffer_info *rbi = &channel->inbound;
1727	ssize_t ret;
1728
1729	mutex_lock(&rbi->ring_buffer_mutex);
1730	if (!rbi->ring_buffer) {
1731		mutex_unlock(&rbi->ring_buffer_mutex);
1732		return -EINVAL;
1733	}
1734
1735	ret = sprintf(buf, "%u\n", hv_get_bytes_to_read(rbi));
1736	mutex_unlock(&rbi->ring_buffer_mutex);
1737	return ret;
1738}
1739static VMBUS_CHAN_ATTR_RO(read_avail);
1740
1741static ssize_t write_avail_show(struct vmbus_channel *channel, char *buf)
1742{
1743	struct hv_ring_buffer_info *rbi = &channel->outbound;
1744	ssize_t ret;
1745
1746	mutex_lock(&rbi->ring_buffer_mutex);
1747	if (!rbi->ring_buffer) {
1748		mutex_unlock(&rbi->ring_buffer_mutex);
1749		return -EINVAL;
1750	}
1751
1752	ret = sprintf(buf, "%u\n", hv_get_bytes_to_write(rbi));
1753	mutex_unlock(&rbi->ring_buffer_mutex);
1754	return ret;
1755}
1756static VMBUS_CHAN_ATTR_RO(write_avail);
1757
1758static ssize_t target_cpu_show(struct vmbus_channel *channel, char *buf)
1759{
1760	return sprintf(buf, "%u\n", channel->target_cpu);
1761}
1762
1763int vmbus_channel_set_cpu(struct vmbus_channel *channel, u32 target_cpu)
1764{
1765	u32 origin_cpu;
1766	int ret = 0;
1767
1768	lockdep_assert_cpus_held();
1769	lockdep_assert_held(&vmbus_connection.channel_mutex);
1770
1771	if (vmbus_proto_version < VERSION_WIN10_V4_1)
1772		return -EIO;
1773
1774	/* Validate target_cpu for the cpumask_test_cpu() operation below. */
1775	if (target_cpu >= nr_cpumask_bits)
1776		return -EINVAL;
1777
1778	if (!cpumask_test_cpu(target_cpu, housekeeping_cpumask(HK_TYPE_MANAGED_IRQ)))
1779		return -EINVAL;
1780
1781	if (!cpu_online(target_cpu))
1782		return -EINVAL;
1783
1784	/*
1785	 * Synchronizes vmbus_channel_set_cpu() and channel closure:
1786	 *
1787	 * { Initially: state = CHANNEL_OPENED }
1788	 *
1789	 * CPU1				CPU2
1790	 *
1791	 * [vmbus_channel_set_cpu()]	[vmbus_disconnect_ring()]
1792	 *
1793	 * LOCK channel_mutex		LOCK channel_mutex
1794	 * LOAD r1 = state		LOAD r2 = state
1795	 * IF (r1 == CHANNEL_OPENED)	IF (r2 == CHANNEL_OPENED)
1796	 *   SEND MODIFYCHANNEL		  STORE state = CHANNEL_OPEN
1797	 *   [...]			  SEND CLOSECHANNEL
1798	 * UNLOCK channel_mutex		UNLOCK channel_mutex
1799	 *
1800	 * Forbids: r1 == r2 == CHANNEL_OPENED (i.e., CPU1's LOCK precedes
1801	 * 		CPU2's LOCK) && CPU2's SEND precedes CPU1's SEND
1802	 *
1803	 * Note.  The host processes the channel messages "sequentially", in
1804	 * the order in which they are received on a per-partition basis.
1805	 */
1806
1807	/*
1808	 * Hyper-V will ignore MODIFYCHANNEL messages for "non-open" channels;
1809	 * avoid sending the message and fail here for such channels.
1810	 */
1811	if (channel->state != CHANNEL_OPENED_STATE) {
1812		ret = -EIO;
1813		goto end;
1814	}
1815
1816	origin_cpu = channel->target_cpu;
1817	if (target_cpu == origin_cpu)
1818		goto end;
1819
1820	if (vmbus_send_modifychannel(channel,
1821				     hv_cpu_number_to_vp_number(target_cpu))) {
1822		ret = -EIO;
1823		goto end;
1824	}
1825
1826	/*
1827	 * For version before VERSION_WIN10_V5_3, the following warning holds:
1828	 *
1829	 * Warning.  At this point, there is *no* guarantee that the host will
1830	 * have successfully processed the vmbus_send_modifychannel() request.
1831	 * See the header comment of vmbus_send_modifychannel() for more info.
1832	 *
1833	 * Lags in the processing of the above vmbus_send_modifychannel() can
1834	 * result in missed interrupts if the "old" target CPU is taken offline
1835	 * before Hyper-V starts sending interrupts to the "new" target CPU.
1836	 * But apart from this offlining scenario, the code tolerates such
1837	 * lags.  It will function correctly even if a channel interrupt comes
1838	 * in on a CPU that is different from the channel target_cpu value.
1839	 */
1840
1841	channel->target_cpu = target_cpu;
1842
1843	/* See init_vp_index(). */
1844	if (hv_is_perf_channel(channel))
1845		hv_update_allocated_cpus(origin_cpu, target_cpu);
1846
1847	/* Currently set only for storvsc channels. */
1848	if (channel->change_target_cpu_callback) {
1849		(*channel->change_target_cpu_callback)(channel,
1850				origin_cpu, target_cpu);
1851	}
1852
1853end:
1854	return ret;
1855}
1856
1857static ssize_t target_cpu_store(struct vmbus_channel *channel,
1858				const char *buf, size_t count)
1859{
1860	u32 target_cpu;
1861	ssize_t ret;
1862
1863	if (sscanf(buf, "%u", &target_cpu) != 1)
1864		return -EIO;
1865
1866	cpus_read_lock();
1867	mutex_lock(&vmbus_connection.channel_mutex);
1868	ret = vmbus_channel_set_cpu(channel, target_cpu);
1869	mutex_unlock(&vmbus_connection.channel_mutex);
1870	cpus_read_unlock();
1871
1872	return ret ?: count;
1873}
1874static VMBUS_CHAN_ATTR(cpu, 0644, target_cpu_show, target_cpu_store);
1875
1876static ssize_t channel_pending_show(struct vmbus_channel *channel,
1877				    char *buf)
1878{
1879	return sprintf(buf, "%d\n",
1880		       channel_pending(channel,
1881				       vmbus_connection.monitor_pages[1]));
1882}
1883static VMBUS_CHAN_ATTR(pending, 0444, channel_pending_show, NULL);
1884
1885static ssize_t channel_latency_show(struct vmbus_channel *channel,
1886				    char *buf)
1887{
1888	return sprintf(buf, "%d\n",
1889		       channel_latency(channel,
1890				       vmbus_connection.monitor_pages[1]));
1891}
1892static VMBUS_CHAN_ATTR(latency, 0444, channel_latency_show, NULL);
1893
1894static ssize_t channel_interrupts_show(struct vmbus_channel *channel, char *buf)
1895{
1896	return sprintf(buf, "%llu\n", channel->interrupts);
1897}
1898static VMBUS_CHAN_ATTR(interrupts, 0444, channel_interrupts_show, NULL);
1899
1900static ssize_t channel_events_show(struct vmbus_channel *channel, char *buf)
1901{
1902	return sprintf(buf, "%llu\n", channel->sig_events);
1903}
1904static VMBUS_CHAN_ATTR(events, 0444, channel_events_show, NULL);
1905
1906static ssize_t channel_intr_in_full_show(struct vmbus_channel *channel,
1907					 char *buf)
1908{
1909	return sprintf(buf, "%llu\n",
1910		       (unsigned long long)channel->intr_in_full);
1911}
1912static VMBUS_CHAN_ATTR(intr_in_full, 0444, channel_intr_in_full_show, NULL);
1913
1914static ssize_t channel_intr_out_empty_show(struct vmbus_channel *channel,
1915					   char *buf)
1916{
1917	return sprintf(buf, "%llu\n",
1918		       (unsigned long long)channel->intr_out_empty);
1919}
1920static VMBUS_CHAN_ATTR(intr_out_empty, 0444, channel_intr_out_empty_show, NULL);
1921
1922static ssize_t channel_out_full_first_show(struct vmbus_channel *channel,
1923					   char *buf)
1924{
1925	return sprintf(buf, "%llu\n",
1926		       (unsigned long long)channel->out_full_first);
1927}
1928static VMBUS_CHAN_ATTR(out_full_first, 0444, channel_out_full_first_show, NULL);
1929
1930static ssize_t channel_out_full_total_show(struct vmbus_channel *channel,
1931					   char *buf)
1932{
1933	return sprintf(buf, "%llu\n",
1934		       (unsigned long long)channel->out_full_total);
1935}
1936static VMBUS_CHAN_ATTR(out_full_total, 0444, channel_out_full_total_show, NULL);
1937
1938static ssize_t subchannel_monitor_id_show(struct vmbus_channel *channel,
1939					  char *buf)
1940{
1941	return sprintf(buf, "%u\n", channel->offermsg.monitorid);
1942}
1943static VMBUS_CHAN_ATTR(monitor_id, 0444, subchannel_monitor_id_show, NULL);
1944
1945static ssize_t subchannel_id_show(struct vmbus_channel *channel,
1946				  char *buf)
1947{
1948	return sprintf(buf, "%u\n",
1949		       channel->offermsg.offer.sub_channel_index);
1950}
1951static VMBUS_CHAN_ATTR_RO(subchannel_id);
1952
1953static int hv_mmap_ring_buffer_wrapper(struct file *filp, struct kobject *kobj,
1954				       const struct bin_attribute *attr,
1955				       struct vm_area_struct *vma)
1956{
1957	struct vmbus_channel *channel = container_of(kobj, struct vmbus_channel, kobj);
1958
1959	/*
1960	 * hv_(create|remove)_ring_sysfs implementation ensures that mmap_ring_buffer
1961	 * is not NULL.
1962	 */
1963	return channel->mmap_ring_buffer(channel, vma);
1964}
1965
1966static struct bin_attribute chan_attr_ring_buffer = {
1967	.attr = {
1968		.name = "ring",
1969		.mode = 0600,
1970	},
1971	.mmap = hv_mmap_ring_buffer_wrapper,
1972};
1973static struct attribute *vmbus_chan_attrs[] = {
1974	&chan_attr_out_mask.attr,
1975	&chan_attr_in_mask.attr,
1976	&chan_attr_read_avail.attr,
1977	&chan_attr_write_avail.attr,
1978	&chan_attr_cpu.attr,
1979	&chan_attr_pending.attr,
1980	&chan_attr_latency.attr,
1981	&chan_attr_interrupts.attr,
1982	&chan_attr_events.attr,
1983	&chan_attr_intr_in_full.attr,
1984	&chan_attr_intr_out_empty.attr,
1985	&chan_attr_out_full_first.attr,
1986	&chan_attr_out_full_total.attr,
1987	&chan_attr_monitor_id.attr,
1988	&chan_attr_subchannel_id.attr,
1989	NULL
1990};
1991
1992static const struct bin_attribute *vmbus_chan_bin_attrs[] = {
1993	&chan_attr_ring_buffer,
1994	NULL
1995};
1996
1997/*
1998 * Channel-level attribute_group callback function. Returns the permission for
1999 * each attribute, and returns 0 if an attribute is not visible.
2000 */
2001static umode_t vmbus_chan_attr_is_visible(struct kobject *kobj,
2002					  struct attribute *attr, int idx)
2003{
2004	const struct vmbus_channel *channel =
2005		container_of(kobj, struct vmbus_channel, kobj);
2006
2007	/* Hide the monitor attributes if the monitor mechanism is not used. */
2008	if (!channel->offermsg.monitor_allocated &&
2009	    (attr == &chan_attr_pending.attr ||
2010	     attr == &chan_attr_latency.attr ||
2011	     attr == &chan_attr_monitor_id.attr))
2012		return 0;
2013
2014	return attr->mode;
2015}
2016
2017static umode_t vmbus_chan_bin_attr_is_visible(struct kobject *kobj,
2018					      const struct bin_attribute *attr, int idx)
2019{
2020	const struct vmbus_channel *channel =
2021		container_of(kobj, struct vmbus_channel, kobj);
2022
2023	/* Hide ring attribute if channel's ring_sysfs_visible is set to false */
2024	if (attr ==  &chan_attr_ring_buffer && !channel->ring_sysfs_visible)
2025		return 0;
2026
2027	return attr->attr.mode;
2028}
2029
2030static size_t vmbus_chan_bin_size(struct kobject *kobj,
2031				  const struct bin_attribute *bin_attr, int a)
2032{
2033	const struct vmbus_channel *channel =
2034		container_of(kobj, struct vmbus_channel, kobj);
2035
2036	return channel->ringbuffer_pagecount << PAGE_SHIFT;
2037}
2038
2039static const struct attribute_group vmbus_chan_group = {
2040	.attrs = vmbus_chan_attrs,
2041	.bin_attrs = vmbus_chan_bin_attrs,
2042	.is_visible = vmbus_chan_attr_is_visible,
2043	.is_bin_visible = vmbus_chan_bin_attr_is_visible,
2044	.bin_size = vmbus_chan_bin_size,
2045};
2046
2047static const struct kobj_type vmbus_chan_ktype = {
2048	.sysfs_ops = &vmbus_chan_sysfs_ops,
2049	.release = vmbus_chan_release,
2050};
2051
2052/**
2053 * hv_create_ring_sysfs() - create "ring" sysfs entry corresponding to ring buffers for a channel.
2054 * @channel: Pointer to vmbus_channel structure
2055 * @hv_mmap_ring_buffer: function pointer for initializing the function to be called on mmap of
2056 *                       channel's "ring" sysfs node, which is for the ring buffer of that channel.
2057 *                       Function pointer is of below type:
2058 *                       int (*hv_mmap_ring_buffer)(struct vmbus_channel *channel,
2059 *                                                  struct vm_area_struct *vma))
2060 *                       This has a pointer to the channel and a pointer to vm_area_struct,
2061 *                       used for mmap, as arguments.
2062 *
2063 * Sysfs node for ring buffer of a channel is created along with other fields, however its
2064 * visibility is disabled by default. Sysfs creation needs to be controlled when the use-case
2065 * is running.
2066 * For example, HV_NIC device is used either by uio_hv_generic or hv_netvsc at any given point of
2067 * time, and "ring" sysfs is needed only when uio_hv_generic is bound to that device. To avoid
2068 * exposing the ring buffer by default, this function is responsible to enable visibility of
2069 * ring for userspace to use.
2070 * Note: Race conditions can happen with userspace and it is not encouraged to create new
2071 * use-cases for this. This was added to maintain backward compatibility, while solving
2072 * one of the race conditions in uio_hv_generic while creating sysfs. See comments with
2073 * vmbus_add_dynid() and vmbus_device_register().
2074 *
2075 * Returns 0 on success or error code on failure.
2076 */
2077int hv_create_ring_sysfs(struct vmbus_channel *channel,
2078			 int (*hv_mmap_ring_buffer)(struct vmbus_channel *channel,
2079						    struct vm_area_struct *vma))
2080{
2081	struct kobject *kobj = &channel->kobj;
2082
2083	channel->mmap_ring_buffer = hv_mmap_ring_buffer;
2084	channel->ring_sysfs_visible = true;
2085
2086	return sysfs_update_group(kobj, &vmbus_chan_group);
2087}
2088EXPORT_SYMBOL_GPL(hv_create_ring_sysfs);
2089
2090/**
2091 * hv_remove_ring_sysfs() - remove ring sysfs entry corresponding to ring buffers for a channel.
2092 * @channel: Pointer to vmbus_channel structure
2093 *
2094 * Hide "ring" sysfs for a channel by changing its is_visible attribute and updating sysfs group.
2095 *
2096 * Returns 0 on success or error code on failure.
2097 */
2098int hv_remove_ring_sysfs(struct vmbus_channel *channel)
2099{
2100	struct kobject *kobj = &channel->kobj;
2101	int ret;
2102
2103	channel->ring_sysfs_visible = false;
2104	ret = sysfs_update_group(kobj, &vmbus_chan_group);
2105	channel->mmap_ring_buffer = NULL;
2106	return ret;
2107}
2108EXPORT_SYMBOL_GPL(hv_remove_ring_sysfs);
2109
2110/*
2111 * vmbus_add_channel_kobj - setup a sub-directory under device/channels
2112 */
2113int vmbus_add_channel_kobj(struct hv_device *dev, struct vmbus_channel *channel)
2114{
2115	const struct device *device = &dev->device;
2116	struct kobject *kobj = &channel->kobj;
2117	u32 relid = channel->offermsg.child_relid;
2118	int ret;
2119
2120	kobj->kset = dev->channels_kset;
2121	ret = kobject_init_and_add(kobj, &vmbus_chan_ktype, NULL,
2122				   "%u", relid);
2123	if (ret) {
2124		kobject_put(kobj);
2125		return ret;
2126	}
2127
2128	ret = sysfs_create_group(kobj, &vmbus_chan_group);
2129
2130	if (ret) {
2131		/*
2132		 * The calling functions' error handling paths will cleanup the
2133		 * empty channel directory.
2134		 */
2135		kobject_put(kobj);
2136		dev_err(device, "Unable to set up channel sysfs files\n");
2137		return ret;
2138	}
2139
2140	kobject_uevent(kobj, KOBJ_ADD);
2141
2142	return 0;
2143}
2144
2145/*
2146 * vmbus_remove_channel_attr_group - remove the channel's attribute group
2147 */
2148void vmbus_remove_channel_attr_group(struct vmbus_channel *channel)
2149{
2150	sysfs_remove_group(&channel->kobj, &vmbus_chan_group);
2151}
2152
2153/*
2154 * vmbus_device_create - Creates and registers a new child device
2155 * on the vmbus.
2156 */
2157struct hv_device *vmbus_device_create(const guid_t *type,
2158				      const guid_t *instance,
2159				      struct vmbus_channel *channel)
2160{
2161	struct hv_device *child_device_obj;
2162
2163	child_device_obj = kzalloc(sizeof(struct hv_device), GFP_KERNEL);
2164	if (!child_device_obj) {
2165		pr_err("Unable to allocate device object for child device\n");
2166		return NULL;
2167	}
2168
2169	child_device_obj->channel = channel;
2170	guid_copy(&child_device_obj->dev_type, type);
2171	guid_copy(&child_device_obj->dev_instance, instance);
2172	child_device_obj->vendor_id = PCI_VENDOR_ID_MICROSOFT;
2173
2174	return child_device_obj;
2175}
2176
2177/*
2178 * vmbus_device_register - Register the child device
2179 */
2180int vmbus_device_register(struct hv_device *child_device_obj)
2181{
2182	struct kobject *kobj = &child_device_obj->device.kobj;
2183	int ret;
2184
2185	dev_set_name(&child_device_obj->device, "%pUl",
2186		     &child_device_obj->channel->offermsg.offer.if_instance);
2187
2188	child_device_obj->device.bus = &hv_bus;
2189	child_device_obj->device.parent = vmbus_root_device;
2190	child_device_obj->device.release = vmbus_device_release;
2191
2192	child_device_obj->device.dma_parms = &child_device_obj->dma_parms;
2193	child_device_obj->device.dma_mask = &child_device_obj->dma_mask;
2194	dma_set_mask(&child_device_obj->device, DMA_BIT_MASK(64));
2195
2196	/*
2197	 * Register with the LDM. This will kick off the driver/device
2198	 * binding...which will eventually call vmbus_match() and vmbus_probe()
2199	 */
2200	ret = device_register(&child_device_obj->device);
2201	if (ret) {
2202		pr_err("Unable to register child device\n");
2203		put_device(&child_device_obj->device);
2204		return ret;
2205	}
2206
2207	/*
2208	 * If device_register() found a driver to assign to the device, the
2209	 * driver's probe function has already run at this point. If that
2210	 * probe function accesses or operates on the "channels" subdirectory
2211	 * in sysfs, those operations will have failed because the "channels"
2212	 * subdirectory doesn't exist until the code below runs. Or if the
2213	 * probe function creates a /dev entry, a user space program could
2214	 * find and open the /dev entry, and then create a race by accessing
2215	 * the "channels" subdirectory while the creation steps are in progress
2216	 * here. The race can't result in a kernel failure, but the user space
2217	 * program may get an error in accessing "channels" or its
2218	 * subdirectories. See also comments with vmbus_add_dynid() about a
2219	 * related race condition.
2220	 */
2221	child_device_obj->channels_kset = kset_create_and_add("channels",
2222							      NULL, kobj);
2223	if (!child_device_obj->channels_kset) {
2224		ret = -ENOMEM;
2225		goto err_dev_unregister;
2226	}
2227
2228	ret = vmbus_add_channel_kobj(child_device_obj,
2229				     child_device_obj->channel);
2230	if (ret) {
2231		pr_err("Unable to register primary channel\n");
2232		goto err_kset_unregister;
2233	}
2234	hv_debug_add_dev_dir(child_device_obj);
2235
2236	return 0;
2237
2238err_kset_unregister:
2239	kset_unregister(child_device_obj->channels_kset);
2240
2241err_dev_unregister:
2242	device_unregister(&child_device_obj->device);
2243	return ret;
2244}
2245
2246/*
2247 * vmbus_device_unregister - Remove the specified child device
2248 * from the vmbus.
2249 */
2250void vmbus_device_unregister(struct hv_device *device_obj)
2251{
2252	pr_debug("child device %s unregistered\n",
2253		dev_name(&device_obj->device));
2254
2255	kset_unregister(device_obj->channels_kset);
2256
2257	/*
2258	 * Kick off the process of unregistering the device.
2259	 * This will call vmbus_remove() and eventually vmbus_device_release()
2260	 */
2261	device_unregister(&device_obj->device);
2262}
2263EXPORT_SYMBOL_GPL(vmbus_device_unregister);
2264
2265#ifdef CONFIG_ACPI
2266/*
2267 * VMBUS is an acpi enumerated device. Get the information we
2268 * need from DSDT.
2269 */
2270static acpi_status vmbus_walk_resources(struct acpi_resource *res, void *ctx)
2271{
2272	resource_size_t start = 0;
2273	resource_size_t end = 0;
2274	struct resource *new_res;
2275	struct resource **old_res = &hyperv_mmio;
2276	struct resource **prev_res = NULL;
2277	struct resource r;
2278
2279	switch (res->type) {
2280
2281	/*
2282	 * "Address" descriptors are for bus windows. Ignore
2283	 * "memory" descriptors, which are for registers on
2284	 * devices.
2285	 */
2286	case ACPI_RESOURCE_TYPE_ADDRESS32:
2287		start = res->data.address32.address.minimum;
2288		end = res->data.address32.address.maximum;
2289		break;
2290
2291	case ACPI_RESOURCE_TYPE_ADDRESS64:
2292		start = res->data.address64.address.minimum;
2293		end = res->data.address64.address.maximum;
2294		break;
2295
2296	/*
2297	 * The IRQ information is needed only on ARM64, which Hyper-V
2298	 * sets up in the extended format. IRQ information is present
2299	 * on x86/x64 in the non-extended format but it is not used by
2300	 * Linux. So don't bother checking for the non-extended format.
2301	 */
2302	case ACPI_RESOURCE_TYPE_EXTENDED_IRQ:
2303		if (!acpi_dev_resource_interrupt(res, 0, &r)) {
2304			pr_err("Unable to parse Hyper-V ACPI interrupt\n");
2305			return AE_ERROR;
2306		}
2307		/* ARM64 INTID for VMbus */
2308		vmbus_interrupt = res->data.extended_irq.interrupts[0];
2309		/* Linux IRQ number */
2310		vmbus_irq = r.start;
2311		return AE_OK;
2312
2313	default:
2314		/* Unused resource type */
2315		return AE_OK;
2316
2317	}
2318	/*
2319	 * Ignore ranges that are below 1MB, as they're not
2320	 * necessary or useful here.
2321	 */
2322	if (end < 0x100000)
2323		return AE_OK;
2324
2325	new_res = kzalloc(sizeof(*new_res), GFP_ATOMIC);
2326	if (!new_res)
2327		return AE_NO_MEMORY;
2328
2329	/* If this range overlaps the virtual TPM, truncate it. */
2330	if (end > VTPM_BASE_ADDRESS && start < VTPM_BASE_ADDRESS)
2331		end = VTPM_BASE_ADDRESS;
2332
2333	new_res->name = "hyperv mmio";
2334	new_res->flags = IORESOURCE_MEM;
2335	new_res->start = start;
2336	new_res->end = end;
2337
2338	/*
2339	 * If two ranges are adjacent, merge them.
2340	 */
2341	do {
2342		if (!*old_res) {
2343			*old_res = new_res;
2344			break;
2345		}
2346
2347		if (((*old_res)->end + 1) == new_res->start) {
2348			(*old_res)->end = new_res->end;
2349			kfree(new_res);
2350			break;
2351		}
2352
2353		if ((*old_res)->start == new_res->end + 1) {
2354			(*old_res)->start = new_res->start;
2355			kfree(new_res);
2356			break;
2357		}
2358
2359		if ((*old_res)->start > new_res->end) {
2360			new_res->sibling = *old_res;
2361			if (prev_res)
2362				(*prev_res)->sibling = new_res;
2363			*old_res = new_res;
2364			break;
2365		}
2366
2367		prev_res = old_res;
2368		old_res = &(*old_res)->sibling;
2369
2370	} while (1);
2371
2372	return AE_OK;
2373}
2374#endif
2375
2376static void vmbus_mmio_remove(void)
2377{
2378	struct resource *cur_res;
2379	struct resource *next_res;
2380
2381	if (hyperv_mmio) {
2382		if (fb_mmio) {
2383			__release_region(hyperv_mmio, fb_mmio->start,
2384					 resource_size(fb_mmio));
2385			fb_mmio = NULL;
2386		}
2387
2388		for (cur_res = hyperv_mmio; cur_res; cur_res = next_res) {
2389			next_res = cur_res->sibling;
2390			kfree(cur_res);
2391		}
2392	}
2393}
2394
2395static void __maybe_unused vmbus_reserve_fb(void)
2396{
2397	resource_size_t start = 0, size;
2398	struct pci_dev *pdev;
2399
2400	if (efi_enabled(EFI_BOOT)) {
2401		/* Gen2 VM: get FB base from EFI framebuffer */
2402		if (IS_ENABLED(CONFIG_SYSFB)) {
2403			start = screen_info.lfb_base;
2404			size = max_t(__u32, screen_info.lfb_size, 0x800000);
2405		}
2406	} else {
2407		/* Gen1 VM: get FB base from PCI */
2408		pdev = pci_get_device(PCI_VENDOR_ID_MICROSOFT,
2409				      PCI_DEVICE_ID_HYPERV_VIDEO, NULL);
2410		if (!pdev)
2411			return;
2412
2413		if (pdev->resource[0].flags & IORESOURCE_MEM) {
2414			start = pci_resource_start(pdev, 0);
2415			size = pci_resource_len(pdev, 0);
2416		}
2417
2418		/*
2419		 * Release the PCI device so hyperv_drm or hyperv_fb driver can
2420		 * grab it later.
2421		 */
2422		pci_dev_put(pdev);
2423	}
2424
2425	if (!start)
2426		return;
2427
2428	/*
2429	 * Make a claim for the frame buffer in the resource tree under the
2430	 * first node, which will be the one below 4GB.  The length seems to
2431	 * be underreported, particularly in a Generation 1 VM.  So start out
2432	 * reserving a larger area and make it smaller until it succeeds.
2433	 */
2434	for (; !fb_mmio && (size >= 0x100000); size >>= 1)
2435		fb_mmio = __request_region(hyperv_mmio, start, size, fb_mmio_name, 0);
2436}
2437
2438/**
2439 * vmbus_allocate_mmio() - Pick a memory-mapped I/O range.
2440 * @new:		If successful, supplied a pointer to the
2441 *			allocated MMIO space.
2442 * @device_obj:		Identifies the caller
2443 * @min:		Minimum guest physical address of the
2444 *			allocation
2445 * @max:		Maximum guest physical address
2446 * @size:		Size of the range to be allocated
2447 * @align:		Alignment of the range to be allocated
2448 * @fb_overlap_ok:	Whether this allocation can be allowed
2449 *			to overlap the video frame buffer.
2450 *
2451 * This function walks the resources granted to VMBus by the
2452 * _CRS object in the ACPI namespace underneath the parent
2453 * "bridge" whether that's a root PCI bus in the Generation 1
2454 * case or a Module Device in the Generation 2 case.  It then
2455 * attempts to allocate from the global MMIO pool in a way that
2456 * matches the constraints supplied in these parameters and by
2457 * that _CRS.
2458 *
2459 * Return: 0 on success, -errno on failure
2460 */
2461int vmbus_allocate_mmio(struct resource **new, struct hv_device *device_obj,
2462			resource_size_t min, resource_size_t max,
2463			resource_size_t size, resource_size_t align,
2464			bool fb_overlap_ok)
2465{
2466	struct resource *iter, *shadow;
2467	resource_size_t range_min, range_max, start, end;
2468	const char *dev_n = dev_name(&device_obj->device);
2469	int retval;
2470
2471	retval = -ENXIO;
2472	mutex_lock(&hyperv_mmio_lock);
2473
2474	/*
2475	 * If overlaps with frame buffers are allowed, then first attempt to
2476	 * make the allocation from within the reserved region.  Because it
2477	 * is already reserved, no shadow allocation is necessary.
2478	 */
2479	if (fb_overlap_ok && fb_mmio && !(min > fb_mmio->end) &&
2480	    !(max < fb_mmio->start)) {
2481
2482		range_min = fb_mmio->start;
2483		range_max = fb_mmio->end;
2484		start = (range_min + align - 1) & ~(align - 1);
2485		for (; start + size - 1 <= range_max; start += align) {
2486			*new = request_mem_region_exclusive(start, size, dev_n);
2487			if (*new) {
2488				retval = 0;
2489				goto exit;
2490			}
2491		}
2492	}
2493
2494	for (iter = hyperv_mmio; iter; iter = iter->sibling) {
2495		if ((iter->start >= max) || (iter->end <= min))
2496			continue;
2497
2498		range_min = iter->start;
2499		range_max = iter->end;
2500		start = (range_min + align - 1) & ~(align - 1);
2501		for (; start + size - 1 <= range_max; start += align) {
2502			end = start + size - 1;
2503
2504			/* Skip the whole fb_mmio region if not fb_overlap_ok */
2505			if (!fb_overlap_ok && fb_mmio &&
2506			    (((start >= fb_mmio->start) && (start <= fb_mmio->end)) ||
2507			     ((end >= fb_mmio->start) && (end <= fb_mmio->end))))
2508				continue;
2509
2510			shadow = __request_region(iter, start, size, NULL,
2511						  IORESOURCE_BUSY);
2512			if (!shadow)
2513				continue;
2514
2515			*new = request_mem_region_exclusive(start, size, dev_n);
2516			if (*new) {
2517				shadow->name = (char *)*new;
2518				retval = 0;
2519				goto exit;
2520			}
2521
2522			__release_region(iter, start, size);
2523		}
2524	}
2525
2526exit:
2527	mutex_unlock(&hyperv_mmio_lock);
2528	return retval;
2529}
2530EXPORT_SYMBOL_GPL(vmbus_allocate_mmio);
2531
2532/**
2533 * vmbus_free_mmio() - Free a memory-mapped I/O range.
2534 * @start:		Base address of region to release.
2535 * @size:		Size of the range to be allocated
2536 *
2537 * This function releases anything requested by
2538 * vmbus_mmio_allocate().
2539 */
2540void vmbus_free_mmio(resource_size_t start, resource_size_t size)
2541{
2542	struct resource *iter;
2543
2544	mutex_lock(&hyperv_mmio_lock);
2545
2546	/*
2547	 * If all bytes of the MMIO range to be released are within the
2548	 * special case fb_mmio shadow region, skip releasing the shadow
2549	 * region since no corresponding __request_region() was done
2550	 * in vmbus_allocate_mmio().
2551	 */
2552	if (fb_mmio && start >= fb_mmio->start &&
2553	    (start + size - 1 <= fb_mmio->end))
2554		goto skip_shadow_release;
2555
2556	for (iter = hyperv_mmio; iter; iter = iter->sibling) {
2557		if ((iter->start >= start + size) || (iter->end <= start))
2558			continue;
2559
2560		__release_region(iter, start, size);
2561	}
2562
2563skip_shadow_release:
2564	release_mem_region(start, size);
2565	mutex_unlock(&hyperv_mmio_lock);
2566
2567}
2568EXPORT_SYMBOL_GPL(vmbus_free_mmio);
2569
2570#ifdef CONFIG_ACPI
2571static int vmbus_acpi_add(struct platform_device *pdev)
2572{
2573	acpi_status result;
2574	int ret_val = -ENODEV;
2575	struct acpi_device *ancestor;
2576	struct acpi_device *device = ACPI_COMPANION(&pdev->dev);
2577
2578	vmbus_root_device = &device->dev;
2579
2580	/*
2581	 * Older versions of Hyper-V for ARM64 fail to include the _CCA
2582	 * method on the top level VMbus device in the DSDT. But devices
2583	 * are hardware coherent in all current Hyper-V use cases, so fix
2584	 * up the ACPI device to behave as if _CCA is present and indicates
2585	 * hardware coherence.
2586	 */
2587	ACPI_COMPANION_SET(&device->dev, device);
2588	if (IS_ENABLED(CONFIG_ACPI_CCA_REQUIRED) &&
2589	    device_get_dma_attr(&device->dev) == DEV_DMA_NOT_SUPPORTED) {
2590		pr_info("No ACPI _CCA found; assuming coherent device I/O\n");
2591		device->flags.cca_seen = true;
2592		device->flags.coherent_dma = true;
2593	}
2594
2595	result = acpi_walk_resources(device->handle, METHOD_NAME__CRS,
2596					vmbus_walk_resources, NULL);
2597
2598	if (ACPI_FAILURE(result))
2599		goto acpi_walk_err;
2600	/*
2601	 * Some ancestor of the vmbus acpi device (Gen1 or Gen2
2602	 * firmware) is the VMOD that has the mmio ranges. Get that.
2603	 */
2604	for (ancestor = acpi_dev_parent(device);
2605	     ancestor && ancestor->handle != ACPI_ROOT_OBJECT;
2606	     ancestor = acpi_dev_parent(ancestor)) {
2607		result = acpi_walk_resources(ancestor->handle, METHOD_NAME__CRS,
2608					     vmbus_walk_resources, NULL);
2609
2610		if (ACPI_FAILURE(result))
2611			continue;
2612		if (hyperv_mmio) {
2613			vmbus_reserve_fb();
2614			break;
2615		}
2616	}
2617	ret_val = 0;
2618
2619acpi_walk_err:
2620	if (ret_val)
2621		vmbus_mmio_remove();
2622	return ret_val;
2623}
2624#else
2625static int vmbus_acpi_add(struct platform_device *pdev)
2626{
2627	return 0;
2628}
2629#endif
2630#ifndef HYPERVISOR_CALLBACK_VECTOR
2631static int vmbus_set_irq(struct platform_device *pdev)
2632{
2633	struct irq_data *data;
2634	int irq;
2635	irq_hw_number_t hwirq;
2636
2637	irq = platform_get_irq(pdev, 0);
2638	/* platform_get_irq() may not return 0. */
2639	if (irq < 0)
2640		return irq;
2641
2642	data = irq_get_irq_data(irq);
2643	if (!data) {
2644		pr_err("No interrupt data for VMBus virq %d\n", irq);
2645		return -ENODEV;
2646	}
2647	hwirq = irqd_to_hwirq(data);
2648
2649	vmbus_irq = irq;
2650	vmbus_interrupt = hwirq;
2651	pr_debug("VMBus virq %d, hwirq %d\n", vmbus_irq, vmbus_interrupt);
2652
2653	return 0;
2654}
2655#endif
2656
2657static int vmbus_device_add(struct platform_device *pdev)
2658{
2659	struct resource **cur_res = &hyperv_mmio;
2660	struct of_range range;
2661	struct of_range_parser parser;
2662	struct device_node *np = pdev->dev.of_node;
2663	int ret;
2664
2665	vmbus_root_device = &pdev->dev;
2666
2667	ret = of_range_parser_init(&parser, np);
2668	if (ret)
2669		return ret;
2670
2671#ifndef HYPERVISOR_CALLBACK_VECTOR
2672	ret = vmbus_set_irq(pdev);
2673	if (ret)
2674		return ret;
2675#endif
2676	for_each_of_range(&parser, &range) {
2677		struct resource *res;
2678
2679		res = kzalloc(sizeof(*res), GFP_KERNEL);
2680		if (!res) {
2681			vmbus_mmio_remove();
2682			return -ENOMEM;
2683		}
2684
2685		res->name = "hyperv mmio";
2686		res->flags = range.flags;
2687		res->start = range.cpu_addr;
2688		res->end = range.cpu_addr + range.size;
2689
2690		*cur_res = res;
2691		cur_res = &res->sibling;
2692	}
2693
2694	return ret;
2695}
2696
2697static int vmbus_platform_driver_probe(struct platform_device *pdev)
2698{
2699	if (acpi_disabled)
2700		return vmbus_device_add(pdev);
2701	else
2702		return vmbus_acpi_add(pdev);
2703}
2704
2705static void vmbus_platform_driver_remove(struct platform_device *pdev)
2706{
2707	vmbus_mmio_remove();
2708}
2709
2710#ifdef CONFIG_PM_SLEEP
2711static int vmbus_bus_suspend(struct device *dev)
2712{
2713	struct hv_per_cpu_context *hv_cpu = per_cpu_ptr(
2714			hv_context.cpu_context, VMBUS_CONNECT_CPU);
2715	struct vmbus_channel *channel, *sc;
2716
2717	tasklet_disable(&hv_cpu->msg_dpc);
2718	vmbus_connection.ignore_any_offer_msg = true;
2719	/* The tasklet_enable() takes care of providing a memory barrier */
2720	tasklet_enable(&hv_cpu->msg_dpc);
2721
2722	/* Drain all the workqueues as we are in suspend */
2723	drain_workqueue(vmbus_connection.rescind_work_queue);
2724	drain_workqueue(vmbus_connection.work_queue);
2725	drain_workqueue(vmbus_connection.handle_primary_chan_wq);
2726	drain_workqueue(vmbus_connection.handle_sub_chan_wq);
2727
2728	mutex_lock(&vmbus_connection.channel_mutex);
2729	list_for_each_entry(channel, &vmbus_connection.chn_list, listentry) {
2730		if (!is_hvsock_channel(channel))
2731			continue;
2732
2733		vmbus_force_channel_rescinded(channel);
2734	}
2735	mutex_unlock(&vmbus_connection.channel_mutex);
2736
2737	/*
2738	 * Wait until all the sub-channels and hv_sock channels have been
2739	 * cleaned up. Sub-channels should be destroyed upon suspend, otherwise
2740	 * they would conflict with the new sub-channels that will be created
2741	 * in the resume path. hv_sock channels should also be destroyed, but
2742	 * a hv_sock channel of an established hv_sock connection can not be
2743	 * really destroyed since it may still be referenced by the userspace
2744	 * application, so we just force the hv_sock channel to be rescinded
2745	 * by vmbus_force_channel_rescinded(), and the userspace application
2746	 * will thoroughly destroy the channel after hibernation.
2747	 *
2748	 * Note: the counter nr_chan_close_on_suspend may never go above 0 if
2749	 * the VM has no sub-channel and hv_sock channel, e.g. a 1-vCPU VM.
2750	 */
2751	if (atomic_read(&vmbus_connection.nr_chan_close_on_suspend) > 0)
2752		wait_for_completion(&vmbus_connection.ready_for_suspend_event);
2753
2754	mutex_lock(&vmbus_connection.channel_mutex);
2755
2756	list_for_each_entry(channel, &vmbus_connection.chn_list, listentry) {
2757		/*
2758		 * Remove the channel from the array of channels and invalidate
2759		 * the channel's relid.  Upon resume, vmbus_onoffer() will fix
2760		 * up the relid (and other fields, if necessary) and add the
2761		 * channel back to the array.
2762		 */
2763		vmbus_channel_unmap_relid(channel);
2764		channel->offermsg.child_relid = INVALID_RELID;
2765
2766		if (is_hvsock_channel(channel)) {
2767			if (!channel->rescind) {
2768				pr_err("hv_sock channel not rescinded!\n");
2769				WARN_ON_ONCE(1);
2770			}
2771			continue;
2772		}
2773
2774		list_for_each_entry(sc, &channel->sc_list, sc_list) {
2775			pr_err("Sub-channel not deleted!\n");
2776			WARN_ON_ONCE(1);
2777		}
2778	}
2779
2780	mutex_unlock(&vmbus_connection.channel_mutex);
2781
2782	vmbus_initiate_unload(false);
2783
2784	return 0;
2785}
2786
2787static int vmbus_bus_resume(struct device *dev)
2788{
2789	struct vmbus_channel *channel;
2790	struct vmbus_channel_msginfo *msginfo;
2791	size_t msgsize;
2792	int ret;
2793
2794	vmbus_connection.ignore_any_offer_msg = false;
2795
2796	/*
2797	 * We only use the 'vmbus_proto_version', which was in use before
2798	 * hibernation, to re-negotiate with the host.
2799	 */
2800	if (!vmbus_proto_version) {
2801		pr_err("Invalid proto version = 0x%x\n", vmbus_proto_version);
2802		return -EINVAL;
2803	}
2804
2805	msgsize = sizeof(*msginfo) +
2806		  sizeof(struct vmbus_channel_initiate_contact);
2807
2808	msginfo = kzalloc(msgsize, GFP_KERNEL);
2809
2810	if (msginfo == NULL)
2811		return -ENOMEM;
2812
2813	ret = vmbus_negotiate_version(msginfo, vmbus_proto_version);
2814
2815	kfree(msginfo);
2816
2817	if (ret != 0)
2818		return ret;
2819
2820	vmbus_request_offers();
2821
2822	mutex_lock(&vmbus_connection.channel_mutex);
2823	list_for_each_entry(channel, &vmbus_connection.chn_list, listentry) {
2824		if (channel->offermsg.child_relid != INVALID_RELID)
2825			continue;
2826
2827		/* hvsock channels are not expected to be present. */
2828		if (is_hvsock_channel(channel))
2829			continue;
2830
2831		pr_err("channel %pUl/%pUl not present after resume.\n",
2832		       &channel->offermsg.offer.if_type,
2833		       &channel->offermsg.offer.if_instance);
2834		/* ToDo: Cleanup these channels here */
2835	}
2836	mutex_unlock(&vmbus_connection.channel_mutex);
2837
2838	/* Reset the event for the next suspend. */
2839	reinit_completion(&vmbus_connection.ready_for_suspend_event);
2840
2841	return 0;
2842}
2843#else
2844#define vmbus_bus_suspend NULL
2845#define vmbus_bus_resume NULL
2846#endif /* CONFIG_PM_SLEEP */
2847
2848static const __maybe_unused struct of_device_id vmbus_of_match[] = {
2849	{
2850		.compatible = "microsoft,vmbus",
2851	},
2852	{
2853		/* sentinel */
2854	},
2855};
2856MODULE_DEVICE_TABLE(of, vmbus_of_match);
2857
2858static const __maybe_unused struct acpi_device_id vmbus_acpi_device_ids[] = {
2859	{"VMBUS", 0},
2860	{"VMBus", 0},
2861	{"", 0},
2862};
2863MODULE_DEVICE_TABLE(acpi, vmbus_acpi_device_ids);
2864
2865/*
2866 * Note: we must use the "no_irq" ops, otherwise hibernation can not work with
2867 * PCI device assignment, because "pci_dev_pm_ops" uses the "noirq" ops: in
2868 * the resume path, the pci "noirq" restore op runs before "non-noirq" op (see
2869 * resume_target_kernel() -> dpm_resume_start(), and hibernation_restore() ->
2870 * dpm_resume_end()). This means vmbus_bus_resume() and the pci-hyperv's
2871 * resume callback must also run via the "noirq" ops.
2872 *
2873 * Set suspend_noirq/resume_noirq to NULL for Suspend-to-Idle: see the comment
2874 * earlier in this file before vmbus_pm.
2875 */
2876
2877static const struct dev_pm_ops vmbus_bus_pm = {
2878	.suspend_noirq	= NULL,
2879	.resume_noirq	= NULL,
2880	.freeze_noirq	= vmbus_bus_suspend,
2881	.thaw_noirq	= vmbus_bus_resume,
2882	.poweroff_noirq	= vmbus_bus_suspend,
2883	.restore_noirq	= vmbus_bus_resume
2884};
2885
2886static struct platform_driver vmbus_platform_driver = {
2887	.probe = vmbus_platform_driver_probe,
2888	.remove = vmbus_platform_driver_remove,
2889	.driver = {
2890		.name = "vmbus",
2891		.acpi_match_table = ACPI_PTR(vmbus_acpi_device_ids),
2892		.of_match_table = of_match_ptr(vmbus_of_match),
2893		.pm = &vmbus_bus_pm,
2894		.probe_type = PROBE_FORCE_SYNCHRONOUS,
2895	}
2896};
2897
2898static void hv_kexec_handler(void)
2899{
2900	hv_stimer_global_cleanup();
2901	vmbus_initiate_unload(false);
2902	/* Make sure conn_state is set as hv_synic_cleanup checks for it */
2903	mb();
2904	cpuhp_remove_state(hyperv_cpuhp_online);
2905};
2906
2907static void hv_crash_handler(struct pt_regs *regs)
2908{
2909	int cpu;
2910
2911	vmbus_initiate_unload(true);
2912	/*
2913	 * In crash handler we can't schedule synic cleanup for all CPUs,
2914	 * doing the cleanup for current CPU only. This should be sufficient
2915	 * for kdump.
2916	 */
2917	cpu = smp_processor_id();
2918	hv_stimer_cleanup(cpu);
2919	hv_hyp_synic_disable_regs(cpu);
2920};
2921
2922static int hv_synic_suspend(void *data)
2923{
2924	/*
2925	 * When we reach here, all the non-boot CPUs have been offlined.
2926	 * If we're in a legacy configuration where stimer Direct Mode is
2927	 * not enabled, the stimers on the non-boot CPUs have been unbound
2928	 * in hv_synic_cleanup() -> hv_stimer_legacy_cleanup() ->
2929	 * hv_stimer_cleanup() -> clockevents_unbind_device().
2930	 *
2931	 * hv_synic_suspend() only runs on CPU0 with interrupts disabled.
2932	 * Here we do not call hv_stimer_legacy_cleanup() on CPU0 because:
2933	 * 1) it's unnecessary as interrupts remain disabled between
2934	 * syscore_suspend() and syscore_resume(): see create_image() and
2935	 * resume_target_kernel()
2936	 * 2) the stimer on CPU0 is automatically disabled later by
2937	 * syscore_suspend() -> timekeeping_suspend() -> tick_suspend() -> ...
2938	 * -> clockevents_shutdown() -> ... -> hv_ce_shutdown()
2939	 * 3) a warning would be triggered if we call
2940	 * clockevents_unbind_device(), which may sleep, in an
2941	 * interrupts-disabled context.
2942	 */
2943
2944	hv_hyp_synic_disable_regs(0);
2945
2946	return 0;
2947}
2948
2949static void hv_synic_resume(void *data)
2950{
2951	hv_hyp_synic_enable_regs(0);
2952
2953	/*
2954	 * Note: we don't need to call hv_stimer_init(0), because the timer
2955	 * on CPU0 is not unbound in hv_synic_suspend(), and the timer is
2956	 * automatically re-enabled in timekeeping_resume().
2957	 */
2958}
2959
2960/* The callbacks run only on CPU0, with irqs_disabled. */
2961static const struct syscore_ops hv_synic_syscore_ops = {
2962	.suspend = hv_synic_suspend,
2963	.resume = hv_synic_resume,
2964};
2965
2966static struct syscore hv_synic_syscore = {
2967	.ops = &hv_synic_syscore_ops,
2968};
2969
2970static int __init hv_acpi_init(void)
2971{
2972	int ret;
2973
2974	if (!hv_is_hyperv_initialized())
2975		return -ENODEV;
2976
2977	if (hv_root_partition() && !hv_nested)
2978		return 0;
2979
2980	/*
2981	 * Get ACPI resources first.
2982	 */
2983	ret = platform_driver_register(&vmbus_platform_driver);
2984	if (ret)
2985		return ret;
2986
2987	if (!vmbus_root_device) {
2988		ret = -ENODEV;
2989		goto cleanup;
2990	}
2991
2992	/*
2993	 * If we're on an architecture with a hardcoded hypervisor
2994	 * vector (i.e. x86/x64), override the VMbus interrupt found
2995	 * in the ACPI tables. Ensure vmbus_irq is not set since the
2996	 * normal Linux IRQ mechanism is not used in this case.
2997	 */
2998#ifdef HYPERVISOR_CALLBACK_VECTOR
2999	vmbus_interrupt = HYPERVISOR_CALLBACK_VECTOR;
3000	vmbus_irq = -1;
3001#endif
3002
3003	hv_debug_init();
3004
3005	ret = vmbus_bus_init();
3006	if (ret)
3007		goto cleanup;
3008
3009	hv_setup_kexec_handler(hv_kexec_handler);
3010	hv_setup_crash_handler(hv_crash_handler);
3011
3012	register_syscore(&hv_synic_syscore);
3013
3014	return 0;
3015
3016cleanup:
3017	platform_driver_unregister(&vmbus_platform_driver);
3018	vmbus_root_device = NULL;
3019	return ret;
3020}
3021
3022static void __exit vmbus_exit(void)
3023{
3024	int cpu;
3025
3026	unregister_syscore(&hv_synic_syscore);
3027
3028	hv_remove_kexec_handler();
3029	hv_remove_crash_handler();
3030	vmbus_connection.conn_state = DISCONNECTED;
3031	hv_stimer_global_cleanup();
3032	vmbus_disconnect();
3033	if (vmbus_irq == -1) {
3034		hv_remove_vmbus_handler();
3035	} else {
3036		free_percpu_irq(vmbus_irq, vmbus_evt);
3037		free_percpu(vmbus_evt);
3038	}
3039	if (IS_ENABLED(CONFIG_PREEMPT_RT) && vmbus_irq_initialized) {
3040		smpboot_unregister_percpu_thread(&vmbus_irq_threads);
3041		vmbus_irq_initialized = false;
3042	}
3043	for_each_online_cpu(cpu) {
3044		struct hv_per_cpu_context *hv_cpu
3045			= per_cpu_ptr(hv_context.cpu_context, cpu);
3046
3047		tasklet_kill(&hv_cpu->msg_dpc);
3048	}
3049	hv_debug_rm_all_dir();
3050
3051	vmbus_free_channels();
3052	kfree(vmbus_connection.channels);
3053
3054	/*
3055	 * The vmbus panic notifier is always registered, hence we should
3056	 * also unconditionally unregister it here as well.
3057	 */
3058	atomic_notifier_chain_unregister(&panic_notifier_list,
3059					&hyperv_panic_vmbus_unload_block);
3060
3061	bus_unregister(&hv_bus);
3062
3063	cpuhp_remove_state(hyperv_cpuhp_online);
3064	hv_synic_free();
3065	platform_driver_unregister(&vmbus_platform_driver);
3066}
3067
3068
3069MODULE_LICENSE("GPL");
3070MODULE_DESCRIPTION("Microsoft Hyper-V VMBus Driver");
3071
3072subsys_initcall(hv_acpi_init);
3073module_exit(vmbus_exit);
~/ Read-only file preview.