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