xref: /linux/drivers/hv/channel_mgmt.c (revision 0be3ff0c)
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  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/kernel.h>
12 #include <linux/interrupt.h>
13 #include <linux/sched.h>
14 #include <linux/wait.h>
15 #include <linux/mm.h>
16 #include <linux/slab.h>
17 #include <linux/list.h>
18 #include <linux/module.h>
19 #include <linux/completion.h>
20 #include <linux/delay.h>
21 #include <linux/cpu.h>
22 #include <linux/hyperv.h>
23 #include <asm/mshyperv.h>
24 
25 #include "hyperv_vmbus.h"
26 
27 static void init_vp_index(struct vmbus_channel *channel);
28 
29 const struct vmbus_device vmbus_devs[] = {
30 	/* IDE */
31 	{ .dev_type = HV_IDE,
32 	  HV_IDE_GUID,
33 	  .perf_device = true,
34 	  .allowed_in_isolated = false,
35 	},
36 
37 	/* SCSI */
38 	{ .dev_type = HV_SCSI,
39 	  HV_SCSI_GUID,
40 	  .perf_device = true,
41 	  .allowed_in_isolated = true,
42 	},
43 
44 	/* Fibre Channel */
45 	{ .dev_type = HV_FC,
46 	  HV_SYNTHFC_GUID,
47 	  .perf_device = true,
48 	  .allowed_in_isolated = false,
49 	},
50 
51 	/* Synthetic NIC */
52 	{ .dev_type = HV_NIC,
53 	  HV_NIC_GUID,
54 	  .perf_device = true,
55 	  .allowed_in_isolated = true,
56 	},
57 
58 	/* Network Direct */
59 	{ .dev_type = HV_ND,
60 	  HV_ND_GUID,
61 	  .perf_device = true,
62 	  .allowed_in_isolated = false,
63 	},
64 
65 	/* PCIE */
66 	{ .dev_type = HV_PCIE,
67 	  HV_PCIE_GUID,
68 	  .perf_device = false,
69 	  .allowed_in_isolated = false,
70 	},
71 
72 	/* Synthetic Frame Buffer */
73 	{ .dev_type = HV_FB,
74 	  HV_SYNTHVID_GUID,
75 	  .perf_device = false,
76 	  .allowed_in_isolated = false,
77 	},
78 
79 	/* Synthetic Keyboard */
80 	{ .dev_type = HV_KBD,
81 	  HV_KBD_GUID,
82 	  .perf_device = false,
83 	  .allowed_in_isolated = false,
84 	},
85 
86 	/* Synthetic MOUSE */
87 	{ .dev_type = HV_MOUSE,
88 	  HV_MOUSE_GUID,
89 	  .perf_device = false,
90 	  .allowed_in_isolated = false,
91 	},
92 
93 	/* KVP */
94 	{ .dev_type = HV_KVP,
95 	  HV_KVP_GUID,
96 	  .perf_device = false,
97 	  .allowed_in_isolated = false,
98 	},
99 
100 	/* Time Synch */
101 	{ .dev_type = HV_TS,
102 	  HV_TS_GUID,
103 	  .perf_device = false,
104 	  .allowed_in_isolated = true,
105 	},
106 
107 	/* Heartbeat */
108 	{ .dev_type = HV_HB,
109 	  HV_HEART_BEAT_GUID,
110 	  .perf_device = false,
111 	  .allowed_in_isolated = true,
112 	},
113 
114 	/* Shutdown */
115 	{ .dev_type = HV_SHUTDOWN,
116 	  HV_SHUTDOWN_GUID,
117 	  .perf_device = false,
118 	  .allowed_in_isolated = true,
119 	},
120 
121 	/* File copy */
122 	{ .dev_type = HV_FCOPY,
123 	  HV_FCOPY_GUID,
124 	  .perf_device = false,
125 	  .allowed_in_isolated = false,
126 	},
127 
128 	/* Backup */
129 	{ .dev_type = HV_BACKUP,
130 	  HV_VSS_GUID,
131 	  .perf_device = false,
132 	  .allowed_in_isolated = false,
133 	},
134 
135 	/* Dynamic Memory */
136 	{ .dev_type = HV_DM,
137 	  HV_DM_GUID,
138 	  .perf_device = false,
139 	  .allowed_in_isolated = false,
140 	},
141 
142 	/* Unknown GUID */
143 	{ .dev_type = HV_UNKNOWN,
144 	  .perf_device = false,
145 	  .allowed_in_isolated = false,
146 	},
147 };
148 
149 static const struct {
150 	guid_t guid;
151 } vmbus_unsupported_devs[] = {
152 	{ HV_AVMA1_GUID },
153 	{ HV_AVMA2_GUID },
154 	{ HV_RDV_GUID	},
155 };
156 
157 /*
158  * The rescinded channel may be blocked waiting for a response from the host;
159  * take care of that.
160  */
161 static void vmbus_rescind_cleanup(struct vmbus_channel *channel)
162 {
163 	struct vmbus_channel_msginfo *msginfo;
164 	unsigned long flags;
165 
166 
167 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
168 	channel->rescind = true;
169 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
170 				msglistentry) {
171 
172 		if (msginfo->waiting_channel == channel) {
173 			complete(&msginfo->waitevent);
174 			break;
175 		}
176 	}
177 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
178 }
179 
180 static bool is_unsupported_vmbus_devs(const guid_t *guid)
181 {
182 	int i;
183 
184 	for (i = 0; i < ARRAY_SIZE(vmbus_unsupported_devs); i++)
185 		if (guid_equal(guid, &vmbus_unsupported_devs[i].guid))
186 			return true;
187 	return false;
188 }
189 
190 static u16 hv_get_dev_type(const struct vmbus_channel *channel)
191 {
192 	const guid_t *guid = &channel->offermsg.offer.if_type;
193 	u16 i;
194 
195 	if (is_hvsock_channel(channel) || is_unsupported_vmbus_devs(guid))
196 		return HV_UNKNOWN;
197 
198 	for (i = HV_IDE; i < HV_UNKNOWN; i++) {
199 		if (guid_equal(guid, &vmbus_devs[i].guid))
200 			return i;
201 	}
202 	pr_info("Unknown GUID: %pUl\n", guid);
203 	return i;
204 }
205 
206 /**
207  * vmbus_prep_negotiate_resp() - Create default response for Negotiate message
208  * @icmsghdrp: Pointer to msg header structure
209  * @buf: Raw buffer channel data
210  * @buflen: Length of the raw buffer channel data.
211  * @fw_version: The framework versions we can support.
212  * @fw_vercnt: The size of @fw_version.
213  * @srv_version: The service versions we can support.
214  * @srv_vercnt: The size of @srv_version.
215  * @nego_fw_version: The selected framework version.
216  * @nego_srv_version: The selected service version.
217  *
218  * Note: Versions are given in decreasing order.
219  *
220  * Set up and fill in default negotiate response message.
221  * Mainly used by Hyper-V drivers.
222  */
223 bool vmbus_prep_negotiate_resp(struct icmsg_hdr *icmsghdrp, u8 *buf,
224 				u32 buflen, const int *fw_version, int fw_vercnt,
225 				const int *srv_version, int srv_vercnt,
226 				int *nego_fw_version, int *nego_srv_version)
227 {
228 	int icframe_major, icframe_minor;
229 	int icmsg_major, icmsg_minor;
230 	int fw_major, fw_minor;
231 	int srv_major, srv_minor;
232 	int i, j;
233 	bool found_match = false;
234 	struct icmsg_negotiate *negop;
235 
236 	/* Check that there's enough space for icframe_vercnt, icmsg_vercnt */
237 	if (buflen < ICMSG_HDR + offsetof(struct icmsg_negotiate, reserved)) {
238 		pr_err_ratelimited("Invalid icmsg negotiate\n");
239 		return false;
240 	}
241 
242 	icmsghdrp->icmsgsize = 0x10;
243 	negop = (struct icmsg_negotiate *)&buf[ICMSG_HDR];
244 
245 	icframe_major = negop->icframe_vercnt;
246 	icframe_minor = 0;
247 
248 	icmsg_major = negop->icmsg_vercnt;
249 	icmsg_minor = 0;
250 
251 	/* Validate negop packet */
252 	if (icframe_major > IC_VERSION_NEGOTIATION_MAX_VER_COUNT ||
253 	    icmsg_major > IC_VERSION_NEGOTIATION_MAX_VER_COUNT ||
254 	    ICMSG_NEGOTIATE_PKT_SIZE(icframe_major, icmsg_major) > buflen) {
255 		pr_err_ratelimited("Invalid icmsg negotiate - icframe_major: %u, icmsg_major: %u\n",
256 				   icframe_major, icmsg_major);
257 		goto fw_error;
258 	}
259 
260 	/*
261 	 * Select the framework version number we will
262 	 * support.
263 	 */
264 
265 	for (i = 0; i < fw_vercnt; i++) {
266 		fw_major = (fw_version[i] >> 16);
267 		fw_minor = (fw_version[i] & 0xFFFF);
268 
269 		for (j = 0; j < negop->icframe_vercnt; j++) {
270 			if ((negop->icversion_data[j].major == fw_major) &&
271 			    (negop->icversion_data[j].minor == fw_minor)) {
272 				icframe_major = negop->icversion_data[j].major;
273 				icframe_minor = negop->icversion_data[j].minor;
274 				found_match = true;
275 				break;
276 			}
277 		}
278 
279 		if (found_match)
280 			break;
281 	}
282 
283 	if (!found_match)
284 		goto fw_error;
285 
286 	found_match = false;
287 
288 	for (i = 0; i < srv_vercnt; i++) {
289 		srv_major = (srv_version[i] >> 16);
290 		srv_minor = (srv_version[i] & 0xFFFF);
291 
292 		for (j = negop->icframe_vercnt;
293 			(j < negop->icframe_vercnt + negop->icmsg_vercnt);
294 			j++) {
295 
296 			if ((negop->icversion_data[j].major == srv_major) &&
297 				(negop->icversion_data[j].minor == srv_minor)) {
298 
299 				icmsg_major = negop->icversion_data[j].major;
300 				icmsg_minor = negop->icversion_data[j].minor;
301 				found_match = true;
302 				break;
303 			}
304 		}
305 
306 		if (found_match)
307 			break;
308 	}
309 
310 	/*
311 	 * Respond with the framework and service
312 	 * version numbers we can support.
313 	 */
314 
315 fw_error:
316 	if (!found_match) {
317 		negop->icframe_vercnt = 0;
318 		negop->icmsg_vercnt = 0;
319 	} else {
320 		negop->icframe_vercnt = 1;
321 		negop->icmsg_vercnt = 1;
322 	}
323 
324 	if (nego_fw_version)
325 		*nego_fw_version = (icframe_major << 16) | icframe_minor;
326 
327 	if (nego_srv_version)
328 		*nego_srv_version = (icmsg_major << 16) | icmsg_minor;
329 
330 	negop->icversion_data[0].major = icframe_major;
331 	negop->icversion_data[0].minor = icframe_minor;
332 	negop->icversion_data[1].major = icmsg_major;
333 	negop->icversion_data[1].minor = icmsg_minor;
334 	return found_match;
335 }
336 EXPORT_SYMBOL_GPL(vmbus_prep_negotiate_resp);
337 
338 /*
339  * alloc_channel - Allocate and initialize a vmbus channel object
340  */
341 static struct vmbus_channel *alloc_channel(void)
342 {
343 	struct vmbus_channel *channel;
344 
345 	channel = kzalloc(sizeof(*channel), GFP_ATOMIC);
346 	if (!channel)
347 		return NULL;
348 
349 	spin_lock_init(&channel->sched_lock);
350 	init_completion(&channel->rescind_event);
351 
352 	INIT_LIST_HEAD(&channel->sc_list);
353 
354 	tasklet_init(&channel->callback_event,
355 		     vmbus_on_event, (unsigned long)channel);
356 
357 	hv_ringbuffer_pre_init(channel);
358 
359 	return channel;
360 }
361 
362 /*
363  * free_channel - Release the resources used by the vmbus channel object
364  */
365 static void free_channel(struct vmbus_channel *channel)
366 {
367 	tasklet_kill(&channel->callback_event);
368 	vmbus_remove_channel_attr_group(channel);
369 
370 	kobject_put(&channel->kobj);
371 }
372 
373 void vmbus_channel_map_relid(struct vmbus_channel *channel)
374 {
375 	if (WARN_ON(channel->offermsg.child_relid >= MAX_CHANNEL_RELIDS))
376 		return;
377 	/*
378 	 * The mapping of the channel's relid is visible from the CPUs that
379 	 * execute vmbus_chan_sched() by the time that vmbus_chan_sched() will
380 	 * execute:
381 	 *
382 	 *  (a) In the "normal (i.e., not resuming from hibernation)" path,
383 	 *      the full barrier in virt_store_mb() guarantees that the store
384 	 *      is propagated to all CPUs before the add_channel_work work
385 	 *      is queued.  In turn, add_channel_work is queued before the
386 	 *      channel's ring buffer is allocated/initialized and the
387 	 *      OPENCHANNEL message for the channel is sent in vmbus_open().
388 	 *      Hyper-V won't start sending the interrupts for the channel
389 	 *      before the OPENCHANNEL message is acked.  The memory barrier
390 	 *      in vmbus_chan_sched() -> sync_test_and_clear_bit() ensures
391 	 *      that vmbus_chan_sched() must find the channel's relid in
392 	 *      recv_int_page before retrieving the channel pointer from the
393 	 *      array of channels.
394 	 *
395 	 *  (b) In the "resuming from hibernation" path, the virt_store_mb()
396 	 *      guarantees that the store is propagated to all CPUs before
397 	 *      the VMBus connection is marked as ready for the resume event
398 	 *      (cf. check_ready_for_resume_event()).  The interrupt handler
399 	 *      of the VMBus driver and vmbus_chan_sched() can not run before
400 	 *      vmbus_bus_resume() has completed execution (cf. resume_noirq).
401 	 */
402 	virt_store_mb(
403 		vmbus_connection.channels[channel->offermsg.child_relid],
404 		channel);
405 }
406 
407 void vmbus_channel_unmap_relid(struct vmbus_channel *channel)
408 {
409 	if (WARN_ON(channel->offermsg.child_relid >= MAX_CHANNEL_RELIDS))
410 		return;
411 	WRITE_ONCE(
412 		vmbus_connection.channels[channel->offermsg.child_relid],
413 		NULL);
414 }
415 
416 static void vmbus_release_relid(u32 relid)
417 {
418 	struct vmbus_channel_relid_released msg;
419 	int ret;
420 
421 	memset(&msg, 0, sizeof(struct vmbus_channel_relid_released));
422 	msg.child_relid = relid;
423 	msg.header.msgtype = CHANNELMSG_RELID_RELEASED;
424 	ret = vmbus_post_msg(&msg, sizeof(struct vmbus_channel_relid_released),
425 			     true);
426 
427 	trace_vmbus_release_relid(&msg, ret);
428 }
429 
430 void hv_process_channel_removal(struct vmbus_channel *channel)
431 {
432 	lockdep_assert_held(&vmbus_connection.channel_mutex);
433 	BUG_ON(!channel->rescind);
434 
435 	/*
436 	 * hv_process_channel_removal() could find INVALID_RELID only for
437 	 * hv_sock channels.  See the inline comments in vmbus_onoffer().
438 	 */
439 	WARN_ON(channel->offermsg.child_relid == INVALID_RELID &&
440 		!is_hvsock_channel(channel));
441 
442 	/*
443 	 * Upon suspend, an in-use hv_sock channel is removed from the array of
444 	 * channels and the relid is invalidated.  After hibernation, when the
445 	 * user-space appplication destroys the channel, it's unnecessary and
446 	 * unsafe to remove the channel from the array of channels.  See also
447 	 * the inline comments before the call of vmbus_release_relid() below.
448 	 */
449 	if (channel->offermsg.child_relid != INVALID_RELID)
450 		vmbus_channel_unmap_relid(channel);
451 
452 	if (channel->primary_channel == NULL)
453 		list_del(&channel->listentry);
454 	else
455 		list_del(&channel->sc_list);
456 
457 	/*
458 	 * If this is a "perf" channel, updates the hv_numa_map[] masks so that
459 	 * init_vp_index() can (re-)use the CPU.
460 	 */
461 	if (hv_is_perf_channel(channel))
462 		hv_clear_allocated_cpu(channel->target_cpu);
463 
464 	/*
465 	 * Upon suspend, an in-use hv_sock channel is marked as "rescinded" and
466 	 * the relid is invalidated; after hibernation, when the user-space app
467 	 * destroys the channel, the relid is INVALID_RELID, and in this case
468 	 * it's unnecessary and unsafe to release the old relid, since the same
469 	 * relid can refer to a completely different channel now.
470 	 */
471 	if (channel->offermsg.child_relid != INVALID_RELID)
472 		vmbus_release_relid(channel->offermsg.child_relid);
473 
474 	free_channel(channel);
475 }
476 
477 void vmbus_free_channels(void)
478 {
479 	struct vmbus_channel *channel, *tmp;
480 
481 	list_for_each_entry_safe(channel, tmp, &vmbus_connection.chn_list,
482 		listentry) {
483 		/* hv_process_channel_removal() needs this */
484 		channel->rescind = true;
485 
486 		vmbus_device_unregister(channel->device_obj);
487 	}
488 }
489 
490 /* Note: the function can run concurrently for primary/sub channels. */
491 static void vmbus_add_channel_work(struct work_struct *work)
492 {
493 	struct vmbus_channel *newchannel =
494 		container_of(work, struct vmbus_channel, add_channel_work);
495 	struct vmbus_channel *primary_channel = newchannel->primary_channel;
496 	int ret;
497 
498 	/*
499 	 * This state is used to indicate a successful open
500 	 * so that when we do close the channel normally, we
501 	 * can cleanup properly.
502 	 */
503 	newchannel->state = CHANNEL_OPEN_STATE;
504 
505 	if (primary_channel != NULL) {
506 		/* newchannel is a sub-channel. */
507 		struct hv_device *dev = primary_channel->device_obj;
508 
509 		if (vmbus_add_channel_kobj(dev, newchannel))
510 			goto err_deq_chan;
511 
512 		if (primary_channel->sc_creation_callback != NULL)
513 			primary_channel->sc_creation_callback(newchannel);
514 
515 		newchannel->probe_done = true;
516 		return;
517 	}
518 
519 	/*
520 	 * Start the process of binding the primary channel to the driver
521 	 */
522 	newchannel->device_obj = vmbus_device_create(
523 		&newchannel->offermsg.offer.if_type,
524 		&newchannel->offermsg.offer.if_instance,
525 		newchannel);
526 	if (!newchannel->device_obj)
527 		goto err_deq_chan;
528 
529 	newchannel->device_obj->device_id = newchannel->device_id;
530 	/*
531 	 * Add the new device to the bus. This will kick off device-driver
532 	 * binding which eventually invokes the device driver's AddDevice()
533 	 * method.
534 	 */
535 	ret = vmbus_device_register(newchannel->device_obj);
536 
537 	if (ret != 0) {
538 		pr_err("unable to add child device object (relid %d)\n",
539 			newchannel->offermsg.child_relid);
540 		kfree(newchannel->device_obj);
541 		goto err_deq_chan;
542 	}
543 
544 	newchannel->probe_done = true;
545 	return;
546 
547 err_deq_chan:
548 	mutex_lock(&vmbus_connection.channel_mutex);
549 
550 	/*
551 	 * We need to set the flag, otherwise
552 	 * vmbus_onoffer_rescind() can be blocked.
553 	 */
554 	newchannel->probe_done = true;
555 
556 	if (primary_channel == NULL)
557 		list_del(&newchannel->listentry);
558 	else
559 		list_del(&newchannel->sc_list);
560 
561 	/* vmbus_process_offer() has mapped the channel. */
562 	vmbus_channel_unmap_relid(newchannel);
563 
564 	mutex_unlock(&vmbus_connection.channel_mutex);
565 
566 	vmbus_release_relid(newchannel->offermsg.child_relid);
567 
568 	free_channel(newchannel);
569 }
570 
571 /*
572  * vmbus_process_offer - Process the offer by creating a channel/device
573  * associated with this offer
574  */
575 static void vmbus_process_offer(struct vmbus_channel *newchannel)
576 {
577 	struct vmbus_channel *channel;
578 	struct workqueue_struct *wq;
579 	bool fnew = true;
580 
581 	/*
582 	 * Synchronize vmbus_process_offer() and CPU hotplugging:
583 	 *
584 	 * CPU1				CPU2
585 	 *
586 	 * [vmbus_process_offer()]	[Hot removal of the CPU]
587 	 *
588 	 * CPU_READ_LOCK		CPUS_WRITE_LOCK
589 	 * LOAD cpu_online_mask		SEARCH chn_list
590 	 * STORE target_cpu		LOAD target_cpu
591 	 * INSERT chn_list		STORE cpu_online_mask
592 	 * CPUS_READ_UNLOCK		CPUS_WRITE_UNLOCK
593 	 *
594 	 * Forbids: CPU1's LOAD from *not* seing CPU2's STORE &&
595 	 *              CPU2's SEARCH from *not* seeing CPU1's INSERT
596 	 *
597 	 * Forbids: CPU2's SEARCH from seeing CPU1's INSERT &&
598 	 *              CPU2's LOAD from *not* seing CPU1's STORE
599 	 */
600 	cpus_read_lock();
601 
602 	/*
603 	 * Serializes the modifications of the chn_list list as well as
604 	 * the accesses to next_numa_node_id in init_vp_index().
605 	 */
606 	mutex_lock(&vmbus_connection.channel_mutex);
607 
608 	list_for_each_entry(channel, &vmbus_connection.chn_list, listentry) {
609 		if (guid_equal(&channel->offermsg.offer.if_type,
610 			       &newchannel->offermsg.offer.if_type) &&
611 		    guid_equal(&channel->offermsg.offer.if_instance,
612 			       &newchannel->offermsg.offer.if_instance)) {
613 			fnew = false;
614 			newchannel->primary_channel = channel;
615 			break;
616 		}
617 	}
618 
619 	init_vp_index(newchannel);
620 
621 	/* Remember the channels that should be cleaned up upon suspend. */
622 	if (is_hvsock_channel(newchannel) || is_sub_channel(newchannel))
623 		atomic_inc(&vmbus_connection.nr_chan_close_on_suspend);
624 
625 	/*
626 	 * Now that we have acquired the channel_mutex,
627 	 * we can release the potentially racing rescind thread.
628 	 */
629 	atomic_dec(&vmbus_connection.offer_in_progress);
630 
631 	if (fnew) {
632 		list_add_tail(&newchannel->listentry,
633 			      &vmbus_connection.chn_list);
634 	} else {
635 		/*
636 		 * Check to see if this is a valid sub-channel.
637 		 */
638 		if (newchannel->offermsg.offer.sub_channel_index == 0) {
639 			mutex_unlock(&vmbus_connection.channel_mutex);
640 			/*
641 			 * Don't call free_channel(), because newchannel->kobj
642 			 * is not initialized yet.
643 			 */
644 			kfree(newchannel);
645 			WARN_ON_ONCE(1);
646 			return;
647 		}
648 		/*
649 		 * Process the sub-channel.
650 		 */
651 		list_add_tail(&newchannel->sc_list, &channel->sc_list);
652 	}
653 
654 	vmbus_channel_map_relid(newchannel);
655 
656 	mutex_unlock(&vmbus_connection.channel_mutex);
657 	cpus_read_unlock();
658 
659 	/*
660 	 * vmbus_process_offer() mustn't call channel->sc_creation_callback()
661 	 * directly for sub-channels, because sc_creation_callback() ->
662 	 * vmbus_open() may never get the host's response to the
663 	 * OPEN_CHANNEL message (the host may rescind a channel at any time,
664 	 * e.g. in the case of hot removing a NIC), and vmbus_onoffer_rescind()
665 	 * may not wake up the vmbus_open() as it's blocked due to a non-zero
666 	 * vmbus_connection.offer_in_progress, and finally we have a deadlock.
667 	 *
668 	 * The above is also true for primary channels, if the related device
669 	 * drivers use sync probing mode by default.
670 	 *
671 	 * And, usually the handling of primary channels and sub-channels can
672 	 * depend on each other, so we should offload them to different
673 	 * workqueues to avoid possible deadlock, e.g. in sync-probing mode,
674 	 * NIC1's netvsc_subchan_work() can race with NIC2's netvsc_probe() ->
675 	 * rtnl_lock(), and causes deadlock: the former gets the rtnl_lock
676 	 * and waits for all the sub-channels to appear, but the latter
677 	 * can't get the rtnl_lock and this blocks the handling of
678 	 * sub-channels.
679 	 */
680 	INIT_WORK(&newchannel->add_channel_work, vmbus_add_channel_work);
681 	wq = fnew ? vmbus_connection.handle_primary_chan_wq :
682 		    vmbus_connection.handle_sub_chan_wq;
683 	queue_work(wq, &newchannel->add_channel_work);
684 }
685 
686 /*
687  * Check if CPUs used by other channels of the same device.
688  * It should only be called by init_vp_index().
689  */
690 static bool hv_cpuself_used(u32 cpu, struct vmbus_channel *chn)
691 {
692 	struct vmbus_channel *primary = chn->primary_channel;
693 	struct vmbus_channel *sc;
694 
695 	lockdep_assert_held(&vmbus_connection.channel_mutex);
696 
697 	if (!primary)
698 		return false;
699 
700 	if (primary->target_cpu == cpu)
701 		return true;
702 
703 	list_for_each_entry(sc, &primary->sc_list, sc_list)
704 		if (sc != chn && sc->target_cpu == cpu)
705 			return true;
706 
707 	return false;
708 }
709 
710 /*
711  * We use this state to statically distribute the channel interrupt load.
712  */
713 static int next_numa_node_id;
714 
715 /*
716  * Starting with Win8, we can statically distribute the incoming
717  * channel interrupt load by binding a channel to VCPU.
718  *
719  * For pre-win8 hosts or non-performance critical channels we assign the
720  * VMBUS_CONNECT_CPU.
721  *
722  * Starting with win8, performance critical channels will be distributed
723  * evenly among all the available NUMA nodes.  Once the node is assigned,
724  * we will assign the CPU based on a simple round robin scheme.
725  */
726 static void init_vp_index(struct vmbus_channel *channel)
727 {
728 	bool perf_chn = hv_is_perf_channel(channel);
729 	u32 i, ncpu = num_online_cpus();
730 	cpumask_var_t available_mask;
731 	struct cpumask *allocated_mask;
732 	u32 target_cpu;
733 	int numa_node;
734 
735 	if ((vmbus_proto_version == VERSION_WS2008) ||
736 	    (vmbus_proto_version == VERSION_WIN7) || (!perf_chn) ||
737 	    !alloc_cpumask_var(&available_mask, GFP_KERNEL)) {
738 		/*
739 		 * Prior to win8, all channel interrupts are
740 		 * delivered on VMBUS_CONNECT_CPU.
741 		 * Also if the channel is not a performance critical
742 		 * channel, bind it to VMBUS_CONNECT_CPU.
743 		 * In case alloc_cpumask_var() fails, bind it to
744 		 * VMBUS_CONNECT_CPU.
745 		 */
746 		channel->target_cpu = VMBUS_CONNECT_CPU;
747 		if (perf_chn)
748 			hv_set_allocated_cpu(VMBUS_CONNECT_CPU);
749 		return;
750 	}
751 
752 	for (i = 1; i <= ncpu + 1; i++) {
753 		while (true) {
754 			numa_node = next_numa_node_id++;
755 			if (numa_node == nr_node_ids) {
756 				next_numa_node_id = 0;
757 				continue;
758 			}
759 			if (cpumask_empty(cpumask_of_node(numa_node)))
760 				continue;
761 			break;
762 		}
763 		allocated_mask = &hv_context.hv_numa_map[numa_node];
764 
765 		if (cpumask_equal(allocated_mask, cpumask_of_node(numa_node))) {
766 			/*
767 			 * We have cycled through all the CPUs in the node;
768 			 * reset the allocated map.
769 			 */
770 			cpumask_clear(allocated_mask);
771 		}
772 
773 		cpumask_xor(available_mask, allocated_mask,
774 			    cpumask_of_node(numa_node));
775 
776 		target_cpu = cpumask_first(available_mask);
777 		cpumask_set_cpu(target_cpu, allocated_mask);
778 
779 		if (channel->offermsg.offer.sub_channel_index >= ncpu ||
780 		    i > ncpu || !hv_cpuself_used(target_cpu, channel))
781 			break;
782 	}
783 
784 	channel->target_cpu = target_cpu;
785 
786 	free_cpumask_var(available_mask);
787 }
788 
789 #define UNLOAD_DELAY_UNIT_MS	10		/* 10 milliseconds */
790 #define UNLOAD_WAIT_MS		(100*1000)	/* 100 seconds */
791 #define UNLOAD_WAIT_LOOPS	(UNLOAD_WAIT_MS/UNLOAD_DELAY_UNIT_MS)
792 #define UNLOAD_MSG_MS		(5*1000)	/* Every 5 seconds */
793 #define UNLOAD_MSG_LOOPS	(UNLOAD_MSG_MS/UNLOAD_DELAY_UNIT_MS)
794 
795 static void vmbus_wait_for_unload(void)
796 {
797 	int cpu;
798 	void *page_addr;
799 	struct hv_message *msg;
800 	struct vmbus_channel_message_header *hdr;
801 	u32 message_type, i;
802 
803 	/*
804 	 * CHANNELMSG_UNLOAD_RESPONSE is always delivered to the CPU which was
805 	 * used for initial contact or to CPU0 depending on host version. When
806 	 * we're crashing on a different CPU let's hope that IRQ handler on
807 	 * the cpu which receives CHANNELMSG_UNLOAD_RESPONSE is still
808 	 * functional and vmbus_unload_response() will complete
809 	 * vmbus_connection.unload_event. If not, the last thing we can do is
810 	 * read message pages for all CPUs directly.
811 	 *
812 	 * Wait up to 100 seconds since an Azure host must writeback any dirty
813 	 * data in its disk cache before the VMbus UNLOAD request will
814 	 * complete. This flushing has been empirically observed to take up
815 	 * to 50 seconds in cases with a lot of dirty data, so allow additional
816 	 * leeway and for inaccuracies in mdelay(). But eventually time out so
817 	 * that the panic path can't get hung forever in case the response
818 	 * message isn't seen.
819 	 */
820 	for (i = 1; i <= UNLOAD_WAIT_LOOPS; i++) {
821 		if (completion_done(&vmbus_connection.unload_event))
822 			goto completed;
823 
824 		for_each_online_cpu(cpu) {
825 			struct hv_per_cpu_context *hv_cpu
826 				= per_cpu_ptr(hv_context.cpu_context, cpu);
827 
828 			page_addr = hv_cpu->synic_message_page;
829 			msg = (struct hv_message *)page_addr
830 				+ VMBUS_MESSAGE_SINT;
831 
832 			message_type = READ_ONCE(msg->header.message_type);
833 			if (message_type == HVMSG_NONE)
834 				continue;
835 
836 			hdr = (struct vmbus_channel_message_header *)
837 				msg->u.payload;
838 
839 			if (hdr->msgtype == CHANNELMSG_UNLOAD_RESPONSE)
840 				complete(&vmbus_connection.unload_event);
841 
842 			vmbus_signal_eom(msg, message_type);
843 		}
844 
845 		/*
846 		 * Give a notice periodically so someone watching the
847 		 * serial output won't think it is completely hung.
848 		 */
849 		if (!(i % UNLOAD_MSG_LOOPS))
850 			pr_notice("Waiting for VMBus UNLOAD to complete\n");
851 
852 		mdelay(UNLOAD_DELAY_UNIT_MS);
853 	}
854 	pr_err("Continuing even though VMBus UNLOAD did not complete\n");
855 
856 completed:
857 	/*
858 	 * We're crashing and already got the UNLOAD_RESPONSE, cleanup all
859 	 * maybe-pending messages on all CPUs to be able to receive new
860 	 * messages after we reconnect.
861 	 */
862 	for_each_online_cpu(cpu) {
863 		struct hv_per_cpu_context *hv_cpu
864 			= per_cpu_ptr(hv_context.cpu_context, cpu);
865 
866 		page_addr = hv_cpu->synic_message_page;
867 		msg = (struct hv_message *)page_addr + VMBUS_MESSAGE_SINT;
868 		msg->header.message_type = HVMSG_NONE;
869 	}
870 }
871 
872 /*
873  * vmbus_unload_response - Handler for the unload response.
874  */
875 static void vmbus_unload_response(struct vmbus_channel_message_header *hdr)
876 {
877 	/*
878 	 * This is a global event; just wakeup the waiting thread.
879 	 * Once we successfully unload, we can cleanup the monitor state.
880 	 *
881 	 * NB.  A malicious or compromised Hyper-V could send a spurious
882 	 * message of type CHANNELMSG_UNLOAD_RESPONSE, and trigger a call
883 	 * of the complete() below.  Make sure that unload_event has been
884 	 * initialized by the time this complete() is executed.
885 	 */
886 	complete(&vmbus_connection.unload_event);
887 }
888 
889 void vmbus_initiate_unload(bool crash)
890 {
891 	struct vmbus_channel_message_header hdr;
892 
893 	if (xchg(&vmbus_connection.conn_state, DISCONNECTED) == DISCONNECTED)
894 		return;
895 
896 	/* Pre-Win2012R2 hosts don't support reconnect */
897 	if (vmbus_proto_version < VERSION_WIN8_1)
898 		return;
899 
900 	reinit_completion(&vmbus_connection.unload_event);
901 	memset(&hdr, 0, sizeof(struct vmbus_channel_message_header));
902 	hdr.msgtype = CHANNELMSG_UNLOAD;
903 	vmbus_post_msg(&hdr, sizeof(struct vmbus_channel_message_header),
904 		       !crash);
905 
906 	/*
907 	 * vmbus_initiate_unload() is also called on crash and the crash can be
908 	 * happening in an interrupt context, where scheduling is impossible.
909 	 */
910 	if (!crash)
911 		wait_for_completion(&vmbus_connection.unload_event);
912 	else
913 		vmbus_wait_for_unload();
914 }
915 
916 static void check_ready_for_resume_event(void)
917 {
918 	/*
919 	 * If all the old primary channels have been fixed up, then it's safe
920 	 * to resume.
921 	 */
922 	if (atomic_dec_and_test(&vmbus_connection.nr_chan_fixup_on_resume))
923 		complete(&vmbus_connection.ready_for_resume_event);
924 }
925 
926 static void vmbus_setup_channel_state(struct vmbus_channel *channel,
927 				      struct vmbus_channel_offer_channel *offer)
928 {
929 	/*
930 	 * Setup state for signalling the host.
931 	 */
932 	channel->sig_event = VMBUS_EVENT_CONNECTION_ID;
933 
934 	if (vmbus_proto_version != VERSION_WS2008) {
935 		channel->is_dedicated_interrupt =
936 				(offer->is_dedicated_interrupt != 0);
937 		channel->sig_event = offer->connection_id;
938 	}
939 
940 	memcpy(&channel->offermsg, offer,
941 	       sizeof(struct vmbus_channel_offer_channel));
942 	channel->monitor_grp = (u8)offer->monitorid / 32;
943 	channel->monitor_bit = (u8)offer->monitorid % 32;
944 	channel->device_id = hv_get_dev_type(channel);
945 }
946 
947 /*
948  * find_primary_channel_by_offer - Get the channel object given the new offer.
949  * This is only used in the resume path of hibernation.
950  */
951 static struct vmbus_channel *
952 find_primary_channel_by_offer(const struct vmbus_channel_offer_channel *offer)
953 {
954 	struct vmbus_channel *channel = NULL, *iter;
955 	const guid_t *inst1, *inst2;
956 
957 	/* Ignore sub-channel offers. */
958 	if (offer->offer.sub_channel_index != 0)
959 		return NULL;
960 
961 	mutex_lock(&vmbus_connection.channel_mutex);
962 
963 	list_for_each_entry(iter, &vmbus_connection.chn_list, listentry) {
964 		inst1 = &iter->offermsg.offer.if_instance;
965 		inst2 = &offer->offer.if_instance;
966 
967 		if (guid_equal(inst1, inst2)) {
968 			channel = iter;
969 			break;
970 		}
971 	}
972 
973 	mutex_unlock(&vmbus_connection.channel_mutex);
974 
975 	return channel;
976 }
977 
978 static bool vmbus_is_valid_device(const guid_t *guid)
979 {
980 	u16 i;
981 
982 	if (!hv_is_isolation_supported())
983 		return true;
984 
985 	for (i = 0; i < ARRAY_SIZE(vmbus_devs); i++) {
986 		if (guid_equal(guid, &vmbus_devs[i].guid))
987 			return vmbus_devs[i].allowed_in_isolated;
988 	}
989 	return false;
990 }
991 
992 /*
993  * vmbus_onoffer - Handler for channel offers from vmbus in parent partition.
994  *
995  */
996 static void vmbus_onoffer(struct vmbus_channel_message_header *hdr)
997 {
998 	struct vmbus_channel_offer_channel *offer;
999 	struct vmbus_channel *oldchannel, *newchannel;
1000 	size_t offer_sz;
1001 
1002 	offer = (struct vmbus_channel_offer_channel *)hdr;
1003 
1004 	trace_vmbus_onoffer(offer);
1005 
1006 	if (!vmbus_is_valid_device(&offer->offer.if_type)) {
1007 		pr_err_ratelimited("Invalid offer %d from the host supporting isolation\n",
1008 				   offer->child_relid);
1009 		atomic_dec(&vmbus_connection.offer_in_progress);
1010 		return;
1011 	}
1012 
1013 	oldchannel = find_primary_channel_by_offer(offer);
1014 
1015 	if (oldchannel != NULL) {
1016 		/*
1017 		 * We're resuming from hibernation: all the sub-channel and
1018 		 * hv_sock channels we had before the hibernation should have
1019 		 * been cleaned up, and now we must be seeing a re-offered
1020 		 * primary channel that we had before the hibernation.
1021 		 */
1022 
1023 		/*
1024 		 * { Initially: channel relid = INVALID_RELID,
1025 		 *		channels[valid_relid] = NULL }
1026 		 *
1027 		 * CPU1					CPU2
1028 		 *
1029 		 * [vmbus_onoffer()]			[vmbus_device_release()]
1030 		 *
1031 		 * LOCK channel_mutex			LOCK channel_mutex
1032 		 * STORE channel relid = valid_relid	LOAD r1 = channel relid
1033 		 * MAP_RELID channel			if (r1 != INVALID_RELID)
1034 		 * UNLOCK channel_mutex			  UNMAP_RELID channel
1035 		 *					UNLOCK channel_mutex
1036 		 *
1037 		 * Forbids: r1 == valid_relid &&
1038 		 *              channels[valid_relid] == channel
1039 		 *
1040 		 * Note.  r1 can be INVALID_RELID only for an hv_sock channel.
1041 		 * None of the hv_sock channels which were present before the
1042 		 * suspend are re-offered upon the resume.  See the WARN_ON()
1043 		 * in hv_process_channel_removal().
1044 		 */
1045 		mutex_lock(&vmbus_connection.channel_mutex);
1046 
1047 		atomic_dec(&vmbus_connection.offer_in_progress);
1048 
1049 		WARN_ON(oldchannel->offermsg.child_relid != INVALID_RELID);
1050 		/* Fix up the relid. */
1051 		oldchannel->offermsg.child_relid = offer->child_relid;
1052 
1053 		offer_sz = sizeof(*offer);
1054 		if (memcmp(offer, &oldchannel->offermsg, offer_sz) != 0) {
1055 			/*
1056 			 * This is not an error, since the host can also change
1057 			 * the other field(s) of the offer, e.g. on WS RS5
1058 			 * (Build 17763), the offer->connection_id of the
1059 			 * Mellanox VF vmbus device can change when the host
1060 			 * reoffers the device upon resume.
1061 			 */
1062 			pr_debug("vmbus offer changed: relid=%d\n",
1063 				 offer->child_relid);
1064 
1065 			print_hex_dump_debug("Old vmbus offer: ",
1066 					     DUMP_PREFIX_OFFSET, 16, 4,
1067 					     &oldchannel->offermsg, offer_sz,
1068 					     false);
1069 			print_hex_dump_debug("New vmbus offer: ",
1070 					     DUMP_PREFIX_OFFSET, 16, 4,
1071 					     offer, offer_sz, false);
1072 
1073 			/* Fix up the old channel. */
1074 			vmbus_setup_channel_state(oldchannel, offer);
1075 		}
1076 
1077 		/* Add the channel back to the array of channels. */
1078 		vmbus_channel_map_relid(oldchannel);
1079 		check_ready_for_resume_event();
1080 
1081 		mutex_unlock(&vmbus_connection.channel_mutex);
1082 		return;
1083 	}
1084 
1085 	/* Allocate the channel object and save this offer. */
1086 	newchannel = alloc_channel();
1087 	if (!newchannel) {
1088 		vmbus_release_relid(offer->child_relid);
1089 		atomic_dec(&vmbus_connection.offer_in_progress);
1090 		pr_err("Unable to allocate channel object\n");
1091 		return;
1092 	}
1093 
1094 	vmbus_setup_channel_state(newchannel, offer);
1095 
1096 	vmbus_process_offer(newchannel);
1097 }
1098 
1099 static void check_ready_for_suspend_event(void)
1100 {
1101 	/*
1102 	 * If all the sub-channels or hv_sock channels have been cleaned up,
1103 	 * then it's safe to suspend.
1104 	 */
1105 	if (atomic_dec_and_test(&vmbus_connection.nr_chan_close_on_suspend))
1106 		complete(&vmbus_connection.ready_for_suspend_event);
1107 }
1108 
1109 /*
1110  * vmbus_onoffer_rescind - Rescind offer handler.
1111  *
1112  * We queue a work item to process this offer synchronously
1113  */
1114 static void vmbus_onoffer_rescind(struct vmbus_channel_message_header *hdr)
1115 {
1116 	struct vmbus_channel_rescind_offer *rescind;
1117 	struct vmbus_channel *channel;
1118 	struct device *dev;
1119 	bool clean_up_chan_for_suspend;
1120 
1121 	rescind = (struct vmbus_channel_rescind_offer *)hdr;
1122 
1123 	trace_vmbus_onoffer_rescind(rescind);
1124 
1125 	/*
1126 	 * The offer msg and the corresponding rescind msg
1127 	 * from the host are guranteed to be ordered -
1128 	 * offer comes in first and then the rescind.
1129 	 * Since we process these events in work elements,
1130 	 * and with preemption, we may end up processing
1131 	 * the events out of order.  We rely on the synchronization
1132 	 * provided by offer_in_progress and by channel_mutex for
1133 	 * ordering these events:
1134 	 *
1135 	 * { Initially: offer_in_progress = 1 }
1136 	 *
1137 	 * CPU1				CPU2
1138 	 *
1139 	 * [vmbus_onoffer()]		[vmbus_onoffer_rescind()]
1140 	 *
1141 	 * LOCK channel_mutex		WAIT_ON offer_in_progress == 0
1142 	 * DECREMENT offer_in_progress	LOCK channel_mutex
1143 	 * STORE channels[]		LOAD channels[]
1144 	 * UNLOCK channel_mutex		UNLOCK channel_mutex
1145 	 *
1146 	 * Forbids: CPU2's LOAD from *not* seeing CPU1's STORE
1147 	 */
1148 
1149 	while (atomic_read(&vmbus_connection.offer_in_progress) != 0) {
1150 		/*
1151 		 * We wait here until any channel offer is currently
1152 		 * being processed.
1153 		 */
1154 		msleep(1);
1155 	}
1156 
1157 	mutex_lock(&vmbus_connection.channel_mutex);
1158 	channel = relid2channel(rescind->child_relid);
1159 	if (channel != NULL) {
1160 		/*
1161 		 * Guarantee that no other instance of vmbus_onoffer_rescind()
1162 		 * has got a reference to the channel object.  Synchronize on
1163 		 * &vmbus_connection.channel_mutex.
1164 		 */
1165 		if (channel->rescind_ref) {
1166 			mutex_unlock(&vmbus_connection.channel_mutex);
1167 			return;
1168 		}
1169 		channel->rescind_ref = true;
1170 	}
1171 	mutex_unlock(&vmbus_connection.channel_mutex);
1172 
1173 	if (channel == NULL) {
1174 		/*
1175 		 * We failed in processing the offer message;
1176 		 * we would have cleaned up the relid in that
1177 		 * failure path.
1178 		 */
1179 		return;
1180 	}
1181 
1182 	clean_up_chan_for_suspend = is_hvsock_channel(channel) ||
1183 				    is_sub_channel(channel);
1184 	/*
1185 	 * Before setting channel->rescind in vmbus_rescind_cleanup(), we
1186 	 * should make sure the channel callback is not running any more.
1187 	 */
1188 	vmbus_reset_channel_cb(channel);
1189 
1190 	/*
1191 	 * Now wait for offer handling to complete.
1192 	 */
1193 	vmbus_rescind_cleanup(channel);
1194 	while (READ_ONCE(channel->probe_done) == false) {
1195 		/*
1196 		 * We wait here until any channel offer is currently
1197 		 * being processed.
1198 		 */
1199 		msleep(1);
1200 	}
1201 
1202 	/*
1203 	 * At this point, the rescind handling can proceed safely.
1204 	 */
1205 
1206 	if (channel->device_obj) {
1207 		if (channel->chn_rescind_callback) {
1208 			channel->chn_rescind_callback(channel);
1209 
1210 			if (clean_up_chan_for_suspend)
1211 				check_ready_for_suspend_event();
1212 
1213 			return;
1214 		}
1215 		/*
1216 		 * We will have to unregister this device from the
1217 		 * driver core.
1218 		 */
1219 		dev = get_device(&channel->device_obj->device);
1220 		if (dev) {
1221 			vmbus_device_unregister(channel->device_obj);
1222 			put_device(dev);
1223 		}
1224 	} else if (channel->primary_channel != NULL) {
1225 		/*
1226 		 * Sub-channel is being rescinded. Following is the channel
1227 		 * close sequence when initiated from the driveri (refer to
1228 		 * vmbus_close() for details):
1229 		 * 1. Close all sub-channels first
1230 		 * 2. Then close the primary channel.
1231 		 */
1232 		mutex_lock(&vmbus_connection.channel_mutex);
1233 		if (channel->state == CHANNEL_OPEN_STATE) {
1234 			/*
1235 			 * The channel is currently not open;
1236 			 * it is safe for us to cleanup the channel.
1237 			 */
1238 			hv_process_channel_removal(channel);
1239 		} else {
1240 			complete(&channel->rescind_event);
1241 		}
1242 		mutex_unlock(&vmbus_connection.channel_mutex);
1243 	}
1244 
1245 	/* The "channel" may have been freed. Do not access it any longer. */
1246 
1247 	if (clean_up_chan_for_suspend)
1248 		check_ready_for_suspend_event();
1249 }
1250 
1251 void vmbus_hvsock_device_unregister(struct vmbus_channel *channel)
1252 {
1253 	BUG_ON(!is_hvsock_channel(channel));
1254 
1255 	/* We always get a rescind msg when a connection is closed. */
1256 	while (!READ_ONCE(channel->probe_done) || !READ_ONCE(channel->rescind))
1257 		msleep(1);
1258 
1259 	vmbus_device_unregister(channel->device_obj);
1260 }
1261 EXPORT_SYMBOL_GPL(vmbus_hvsock_device_unregister);
1262 
1263 
1264 /*
1265  * vmbus_onoffers_delivered -
1266  * This is invoked when all offers have been delivered.
1267  *
1268  * Nothing to do here.
1269  */
1270 static void vmbus_onoffers_delivered(
1271 			struct vmbus_channel_message_header *hdr)
1272 {
1273 }
1274 
1275 /*
1276  * vmbus_onopen_result - Open result handler.
1277  *
1278  * This is invoked when we received a response to our channel open request.
1279  * Find the matching request, copy the response and signal the requesting
1280  * thread.
1281  */
1282 static void vmbus_onopen_result(struct vmbus_channel_message_header *hdr)
1283 {
1284 	struct vmbus_channel_open_result *result;
1285 	struct vmbus_channel_msginfo *msginfo;
1286 	struct vmbus_channel_message_header *requestheader;
1287 	struct vmbus_channel_open_channel *openmsg;
1288 	unsigned long flags;
1289 
1290 	result = (struct vmbus_channel_open_result *)hdr;
1291 
1292 	trace_vmbus_onopen_result(result);
1293 
1294 	/*
1295 	 * Find the open msg, copy the result and signal/unblock the wait event
1296 	 */
1297 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1298 
1299 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1300 				msglistentry) {
1301 		requestheader =
1302 			(struct vmbus_channel_message_header *)msginfo->msg;
1303 
1304 		if (requestheader->msgtype == CHANNELMSG_OPENCHANNEL) {
1305 			openmsg =
1306 			(struct vmbus_channel_open_channel *)msginfo->msg;
1307 			if (openmsg->child_relid == result->child_relid &&
1308 			    openmsg->openid == result->openid) {
1309 				memcpy(&msginfo->response.open_result,
1310 				       result,
1311 				       sizeof(
1312 					struct vmbus_channel_open_result));
1313 				complete(&msginfo->waitevent);
1314 				break;
1315 			}
1316 		}
1317 	}
1318 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1319 }
1320 
1321 /*
1322  * vmbus_ongpadl_created - GPADL created handler.
1323  *
1324  * This is invoked when we received a response to our gpadl create request.
1325  * Find the matching request, copy the response and signal the requesting
1326  * thread.
1327  */
1328 static void vmbus_ongpadl_created(struct vmbus_channel_message_header *hdr)
1329 {
1330 	struct vmbus_channel_gpadl_created *gpadlcreated;
1331 	struct vmbus_channel_msginfo *msginfo;
1332 	struct vmbus_channel_message_header *requestheader;
1333 	struct vmbus_channel_gpadl_header *gpadlheader;
1334 	unsigned long flags;
1335 
1336 	gpadlcreated = (struct vmbus_channel_gpadl_created *)hdr;
1337 
1338 	trace_vmbus_ongpadl_created(gpadlcreated);
1339 
1340 	/*
1341 	 * Find the establish msg, copy the result and signal/unblock the wait
1342 	 * event
1343 	 */
1344 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1345 
1346 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1347 				msglistentry) {
1348 		requestheader =
1349 			(struct vmbus_channel_message_header *)msginfo->msg;
1350 
1351 		if (requestheader->msgtype == CHANNELMSG_GPADL_HEADER) {
1352 			gpadlheader =
1353 			(struct vmbus_channel_gpadl_header *)requestheader;
1354 
1355 			if ((gpadlcreated->child_relid ==
1356 			     gpadlheader->child_relid) &&
1357 			    (gpadlcreated->gpadl == gpadlheader->gpadl)) {
1358 				memcpy(&msginfo->response.gpadl_created,
1359 				       gpadlcreated,
1360 				       sizeof(
1361 					struct vmbus_channel_gpadl_created));
1362 				complete(&msginfo->waitevent);
1363 				break;
1364 			}
1365 		}
1366 	}
1367 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1368 }
1369 
1370 /*
1371  * vmbus_onmodifychannel_response - Modify Channel response handler.
1372  *
1373  * This is invoked when we received a response to our channel modify request.
1374  * Find the matching request, copy the response and signal the requesting thread.
1375  */
1376 static void vmbus_onmodifychannel_response(struct vmbus_channel_message_header *hdr)
1377 {
1378 	struct vmbus_channel_modifychannel_response *response;
1379 	struct vmbus_channel_msginfo *msginfo;
1380 	unsigned long flags;
1381 
1382 	response = (struct vmbus_channel_modifychannel_response *)hdr;
1383 
1384 	trace_vmbus_onmodifychannel_response(response);
1385 
1386 	/*
1387 	 * Find the modify msg, copy the response and signal/unblock the wait event.
1388 	 */
1389 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1390 
1391 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list, msglistentry) {
1392 		struct vmbus_channel_message_header *responseheader =
1393 				(struct vmbus_channel_message_header *)msginfo->msg;
1394 
1395 		if (responseheader->msgtype == CHANNELMSG_MODIFYCHANNEL) {
1396 			struct vmbus_channel_modifychannel *modifymsg;
1397 
1398 			modifymsg = (struct vmbus_channel_modifychannel *)msginfo->msg;
1399 			if (modifymsg->child_relid == response->child_relid) {
1400 				memcpy(&msginfo->response.modify_response, response,
1401 				       sizeof(*response));
1402 				complete(&msginfo->waitevent);
1403 				break;
1404 			}
1405 		}
1406 	}
1407 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1408 }
1409 
1410 /*
1411  * vmbus_ongpadl_torndown - GPADL torndown handler.
1412  *
1413  * This is invoked when we received a response to our gpadl teardown request.
1414  * Find the matching request, copy the response and signal the requesting
1415  * thread.
1416  */
1417 static void vmbus_ongpadl_torndown(
1418 			struct vmbus_channel_message_header *hdr)
1419 {
1420 	struct vmbus_channel_gpadl_torndown *gpadl_torndown;
1421 	struct vmbus_channel_msginfo *msginfo;
1422 	struct vmbus_channel_message_header *requestheader;
1423 	struct vmbus_channel_gpadl_teardown *gpadl_teardown;
1424 	unsigned long flags;
1425 
1426 	gpadl_torndown = (struct vmbus_channel_gpadl_torndown *)hdr;
1427 
1428 	trace_vmbus_ongpadl_torndown(gpadl_torndown);
1429 
1430 	/*
1431 	 * Find the open msg, copy the result and signal/unblock the wait event
1432 	 */
1433 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1434 
1435 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1436 				msglistentry) {
1437 		requestheader =
1438 			(struct vmbus_channel_message_header *)msginfo->msg;
1439 
1440 		if (requestheader->msgtype == CHANNELMSG_GPADL_TEARDOWN) {
1441 			gpadl_teardown =
1442 			(struct vmbus_channel_gpadl_teardown *)requestheader;
1443 
1444 			if (gpadl_torndown->gpadl == gpadl_teardown->gpadl) {
1445 				memcpy(&msginfo->response.gpadl_torndown,
1446 				       gpadl_torndown,
1447 				       sizeof(
1448 					struct vmbus_channel_gpadl_torndown));
1449 				complete(&msginfo->waitevent);
1450 				break;
1451 			}
1452 		}
1453 	}
1454 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1455 }
1456 
1457 /*
1458  * vmbus_onversion_response - Version response handler
1459  *
1460  * This is invoked when we received a response to our initiate contact request.
1461  * Find the matching request, copy the response and signal the requesting
1462  * thread.
1463  */
1464 static void vmbus_onversion_response(
1465 		struct vmbus_channel_message_header *hdr)
1466 {
1467 	struct vmbus_channel_msginfo *msginfo;
1468 	struct vmbus_channel_message_header *requestheader;
1469 	struct vmbus_channel_version_response *version_response;
1470 	unsigned long flags;
1471 
1472 	version_response = (struct vmbus_channel_version_response *)hdr;
1473 
1474 	trace_vmbus_onversion_response(version_response);
1475 
1476 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1477 
1478 	list_for_each_entry(msginfo, &vmbus_connection.chn_msg_list,
1479 				msglistentry) {
1480 		requestheader =
1481 			(struct vmbus_channel_message_header *)msginfo->msg;
1482 
1483 		if (requestheader->msgtype ==
1484 		    CHANNELMSG_INITIATE_CONTACT) {
1485 			memcpy(&msginfo->response.version_response,
1486 			      version_response,
1487 			      sizeof(struct vmbus_channel_version_response));
1488 			complete(&msginfo->waitevent);
1489 		}
1490 	}
1491 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1492 }
1493 
1494 /* Channel message dispatch table */
1495 const struct vmbus_channel_message_table_entry
1496 channel_message_table[CHANNELMSG_COUNT] = {
1497 	{ CHANNELMSG_INVALID,			0, NULL, 0},
1498 	{ CHANNELMSG_OFFERCHANNEL,		0, vmbus_onoffer,
1499 		sizeof(struct vmbus_channel_offer_channel)},
1500 	{ CHANNELMSG_RESCIND_CHANNELOFFER,	0, vmbus_onoffer_rescind,
1501 		sizeof(struct vmbus_channel_rescind_offer) },
1502 	{ CHANNELMSG_REQUESTOFFERS,		0, NULL, 0},
1503 	{ CHANNELMSG_ALLOFFERS_DELIVERED,	1, vmbus_onoffers_delivered, 0},
1504 	{ CHANNELMSG_OPENCHANNEL,		0, NULL, 0},
1505 	{ CHANNELMSG_OPENCHANNEL_RESULT,	1, vmbus_onopen_result,
1506 		sizeof(struct vmbus_channel_open_result)},
1507 	{ CHANNELMSG_CLOSECHANNEL,		0, NULL, 0},
1508 	{ CHANNELMSG_GPADL_HEADER,		0, NULL, 0},
1509 	{ CHANNELMSG_GPADL_BODY,		0, NULL, 0},
1510 	{ CHANNELMSG_GPADL_CREATED,		1, vmbus_ongpadl_created,
1511 		sizeof(struct vmbus_channel_gpadl_created)},
1512 	{ CHANNELMSG_GPADL_TEARDOWN,		0, NULL, 0},
1513 	{ CHANNELMSG_GPADL_TORNDOWN,		1, vmbus_ongpadl_torndown,
1514 		sizeof(struct vmbus_channel_gpadl_torndown) },
1515 	{ CHANNELMSG_RELID_RELEASED,		0, NULL, 0},
1516 	{ CHANNELMSG_INITIATE_CONTACT,		0, NULL, 0},
1517 	{ CHANNELMSG_VERSION_RESPONSE,		1, vmbus_onversion_response,
1518 		sizeof(struct vmbus_channel_version_response)},
1519 	{ CHANNELMSG_UNLOAD,			0, NULL, 0},
1520 	{ CHANNELMSG_UNLOAD_RESPONSE,		1, vmbus_unload_response, 0},
1521 	{ CHANNELMSG_18,			0, NULL, 0},
1522 	{ CHANNELMSG_19,			0, NULL, 0},
1523 	{ CHANNELMSG_20,			0, NULL, 0},
1524 	{ CHANNELMSG_TL_CONNECT_REQUEST,	0, NULL, 0},
1525 	{ CHANNELMSG_MODIFYCHANNEL,		0, NULL, 0},
1526 	{ CHANNELMSG_TL_CONNECT_RESULT,		0, NULL, 0},
1527 	{ CHANNELMSG_MODIFYCHANNEL_RESPONSE,	1, vmbus_onmodifychannel_response,
1528 		sizeof(struct vmbus_channel_modifychannel_response)},
1529 };
1530 
1531 /*
1532  * vmbus_onmessage - Handler for channel protocol messages.
1533  *
1534  * This is invoked in the vmbus worker thread context.
1535  */
1536 void vmbus_onmessage(struct vmbus_channel_message_header *hdr)
1537 {
1538 	trace_vmbus_on_message(hdr);
1539 
1540 	/*
1541 	 * vmbus_on_msg_dpc() makes sure the hdr->msgtype here can not go
1542 	 * out of bound and the message_handler pointer can not be NULL.
1543 	 */
1544 	channel_message_table[hdr->msgtype].message_handler(hdr);
1545 }
1546 
1547 /*
1548  * vmbus_request_offers - Send a request to get all our pending offers.
1549  */
1550 int vmbus_request_offers(void)
1551 {
1552 	struct vmbus_channel_message_header *msg;
1553 	struct vmbus_channel_msginfo *msginfo;
1554 	int ret;
1555 
1556 	msginfo = kzalloc(sizeof(*msginfo) +
1557 			  sizeof(struct vmbus_channel_message_header),
1558 			  GFP_KERNEL);
1559 	if (!msginfo)
1560 		return -ENOMEM;
1561 
1562 	msg = (struct vmbus_channel_message_header *)msginfo->msg;
1563 
1564 	msg->msgtype = CHANNELMSG_REQUESTOFFERS;
1565 
1566 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_message_header),
1567 			     true);
1568 
1569 	trace_vmbus_request_offers(ret);
1570 
1571 	if (ret != 0) {
1572 		pr_err("Unable to request offers - %d\n", ret);
1573 
1574 		goto cleanup;
1575 	}
1576 
1577 cleanup:
1578 	kfree(msginfo);
1579 
1580 	return ret;
1581 }
1582 
1583 void vmbus_set_sc_create_callback(struct vmbus_channel *primary_channel,
1584 				void (*sc_cr_cb)(struct vmbus_channel *new_sc))
1585 {
1586 	primary_channel->sc_creation_callback = sc_cr_cb;
1587 }
1588 EXPORT_SYMBOL_GPL(vmbus_set_sc_create_callback);
1589 
1590 void vmbus_set_chn_rescind_callback(struct vmbus_channel *channel,
1591 		void (*chn_rescind_cb)(struct vmbus_channel *))
1592 {
1593 	channel->chn_rescind_callback = chn_rescind_cb;
1594 }
1595 EXPORT_SYMBOL_GPL(vmbus_set_chn_rescind_callback);
1596