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