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