• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (c) 2009, Microsoft Corporation.
5  *
6  * Authors:
7  *   Haiyang Zhang <haiyangz@microsoft.com>
8  *   Hank Janssen  <hjanssen@microsoft.com>
9  */
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/kernel.h>
13 #include <linux/sched.h>
14 #include <linux/wait.h>
15 #include <linux/delay.h>
16 #include <linux/mm.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/vmalloc.h>
20 #include <linux/hyperv.h>
21 #include <linux/export.h>
22 #include <linux/io.h>
23 #include <linux/set_memory.h>
24 #include <asm/mem_encrypt.h>
25 #include <asm/mshyperv.h>
26 
27 #include "hyperv_vmbus.h"
28 
29 
30 struct vmbus_connection vmbus_connection = {
31 	.conn_state		= DISCONNECTED,
32 	.unload_event		= COMPLETION_INITIALIZER(
33 				  vmbus_connection.unload_event),
34 	.next_gpadl_handle	= ATOMIC_INIT(0xE1E10),
35 
36 	.ready_for_suspend_event = COMPLETION_INITIALIZER(
37 				  vmbus_connection.ready_for_suspend_event),
38 	.ready_for_resume_event	= COMPLETION_INITIALIZER(
39 				  vmbus_connection.ready_for_resume_event),
40 };
41 EXPORT_SYMBOL_GPL(vmbus_connection);
42 
43 /*
44  * Negotiated protocol version with the host.
45  */
46 __u32 vmbus_proto_version;
47 EXPORT_SYMBOL_GPL(vmbus_proto_version);
48 
49 /*
50  * Table of VMBus versions listed from newest to oldest.
51  * VERSION_WIN7 and VERSION_WS2008 are no longer supported in
52  * Linux guests and are not listed.
53  */
54 static __u32 vmbus_versions[] = {
55 	VERSION_WIN10_V5_3,
56 	VERSION_WIN10_V5_2,
57 	VERSION_WIN10_V5_1,
58 	VERSION_WIN10_V5,
59 	VERSION_WIN10_V4_1,
60 	VERSION_WIN10,
61 	VERSION_WIN8_1,
62 	VERSION_WIN8
63 };
64 
65 /*
66  * Maximal VMBus protocol version guests can negotiate.  Useful to cap the
67  * VMBus version for testing and debugging purpose.
68  */
69 static uint max_version = VERSION_WIN10_V5_3;
70 
71 module_param(max_version, uint, S_IRUGO);
72 MODULE_PARM_DESC(max_version,
73 		 "Maximal VMBus protocol version which can be negotiated");
74 
vmbus_negotiate_version(struct vmbus_channel_msginfo * msginfo,u32 version)75 int vmbus_negotiate_version(struct vmbus_channel_msginfo *msginfo, u32 version)
76 {
77 	int ret = 0;
78 	struct vmbus_channel_initiate_contact *msg;
79 	unsigned long flags;
80 
81 	init_completion(&msginfo->waitevent);
82 
83 	msg = (struct vmbus_channel_initiate_contact *)msginfo->msg;
84 
85 	memset(msg, 0, sizeof(*msg));
86 	msg->header.msgtype = CHANNELMSG_INITIATE_CONTACT;
87 	msg->vmbus_version_requested = version;
88 
89 	/*
90 	 * VMBus protocol 5.0 (VERSION_WIN10_V5) and higher require that we must
91 	 * use VMBUS_MESSAGE_CONNECTION_ID_4 for the Initiate Contact Message,
92 	 * and for subsequent messages, we must use the Message Connection ID
93 	 * field in the host-returned Version Response Message. And, with
94 	 * VERSION_WIN10_V5 and higher, we don't use msg->interrupt_page, but we
95 	 * tell the host explicitly that we still use VMBUS_MESSAGE_SINT(2) for
96 	 * compatibility.
97 	 *
98 	 * On old hosts, we should always use VMBUS_MESSAGE_CONNECTION_ID (1).
99 	 */
100 	if (version >= VERSION_WIN10_V5) {
101 		msg->msg_sint = VMBUS_MESSAGE_SINT;
102 		msg->msg_vtl = ms_hyperv.vtl;
103 		vmbus_connection.msg_conn_id = VMBUS_MESSAGE_CONNECTION_ID_4;
104 	} else {
105 		msg->interrupt_page = virt_to_phys(vmbus_connection.int_page);
106 		vmbus_connection.msg_conn_id = VMBUS_MESSAGE_CONNECTION_ID;
107 	}
108 
109 	/*
110 	 * shared_gpa_boundary is zero in non-SNP VMs, so it's safe to always
111 	 * bitwise OR it
112 	 */
113 	msg->monitor_page1 = virt_to_phys(vmbus_connection.monitor_pages[0]) |
114 				ms_hyperv.shared_gpa_boundary;
115 	msg->monitor_page2 = virt_to_phys(vmbus_connection.monitor_pages[1]) |
116 				ms_hyperv.shared_gpa_boundary;
117 
118 	msg->target_vcpu = hv_cpu_number_to_vp_number(VMBUS_CONNECT_CPU);
119 
120 	/*
121 	 * Add to list before we send the request since we may
122 	 * receive the response before returning from this routine
123 	 */
124 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
125 	list_add_tail(&msginfo->msglistentry,
126 		      &vmbus_connection.chn_msg_list);
127 
128 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
129 
130 	ret = vmbus_post_msg(msg,
131 			     sizeof(struct vmbus_channel_initiate_contact),
132 			     true);
133 
134 	trace_vmbus_negotiate_version(msg, ret);
135 
136 	if (ret != 0) {
137 		spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
138 		list_del(&msginfo->msglistentry);
139 		spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock,
140 					flags);
141 		return ret;
142 	}
143 
144 	/* Wait for the connection response */
145 	wait_for_completion(&msginfo->waitevent);
146 
147 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
148 	list_del(&msginfo->msglistentry);
149 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
150 
151 	/* Check if successful */
152 	if (msginfo->response.version_response.version_supported) {
153 		vmbus_connection.conn_state = CONNECTED;
154 
155 		if (version >= VERSION_WIN10_V5)
156 			vmbus_connection.msg_conn_id =
157 				msginfo->response.version_response.msg_conn_id;
158 	} else {
159 		return -ECONNREFUSED;
160 	}
161 
162 	return ret;
163 }
164 
165 /*
166  * vmbus_connect - Sends a connect request on the partition service connection
167  */
vmbus_connect(void)168 int vmbus_connect(void)
169 {
170 	struct vmbus_channel_msginfo *msginfo = NULL;
171 	int i, ret = 0;
172 	__u32 version;
173 
174 	/* Initialize the vmbus connection */
175 	vmbus_connection.conn_state = CONNECTING;
176 	vmbus_connection.work_queue = create_workqueue("hv_vmbus_con");
177 	if (!vmbus_connection.work_queue) {
178 		ret = -ENOMEM;
179 		goto cleanup;
180 	}
181 
182 	vmbus_connection.rescind_work_queue =
183 		create_workqueue("hv_vmbus_rescind");
184 	if (!vmbus_connection.rescind_work_queue) {
185 		ret = -ENOMEM;
186 		goto cleanup;
187 	}
188 	vmbus_connection.ignore_any_offer_msg = false;
189 
190 	vmbus_connection.handle_primary_chan_wq =
191 		create_workqueue("hv_pri_chan");
192 	if (!vmbus_connection.handle_primary_chan_wq) {
193 		ret = -ENOMEM;
194 		goto cleanup;
195 	}
196 
197 	vmbus_connection.handle_sub_chan_wq =
198 		create_workqueue("hv_sub_chan");
199 	if (!vmbus_connection.handle_sub_chan_wq) {
200 		ret = -ENOMEM;
201 		goto cleanup;
202 	}
203 
204 	INIT_LIST_HEAD(&vmbus_connection.chn_msg_list);
205 	spin_lock_init(&vmbus_connection.channelmsg_lock);
206 
207 	INIT_LIST_HEAD(&vmbus_connection.chn_list);
208 	mutex_init(&vmbus_connection.channel_mutex);
209 
210 	/*
211 	 * Setup the vmbus event connection for channel interrupt
212 	 * abstraction stuff
213 	 */
214 	vmbus_connection.int_page = hv_alloc_hyperv_zeroed_page();
215 	if (vmbus_connection.int_page == NULL) {
216 		ret = -ENOMEM;
217 		goto cleanup;
218 	}
219 
220 	vmbus_connection.recv_int_page = vmbus_connection.int_page;
221 	vmbus_connection.send_int_page =
222 		(void *)((unsigned long)vmbus_connection.int_page +
223 			(HV_HYP_PAGE_SIZE >> 1));
224 
225 	/*
226 	 * Setup the monitor notification facility. The 1st page for
227 	 * parent->child and the 2nd page for child->parent
228 	 */
229 	vmbus_connection.monitor_pages[0] = hv_alloc_hyperv_page();
230 	vmbus_connection.monitor_pages[1] = hv_alloc_hyperv_page();
231 	if ((vmbus_connection.monitor_pages[0] == NULL) ||
232 	    (vmbus_connection.monitor_pages[1] == NULL)) {
233 		ret = -ENOMEM;
234 		goto cleanup;
235 	}
236 
237 	ret = set_memory_decrypted((unsigned long)
238 				vmbus_connection.monitor_pages[0], 1);
239 	ret |= set_memory_decrypted((unsigned long)
240 				vmbus_connection.monitor_pages[1], 1);
241 	if (ret) {
242 		/*
243 		 * If set_memory_decrypted() fails, the encryption state
244 		 * of the memory is unknown. So leak the memory instead
245 		 * of risking returning decrypted memory to the free list.
246 		 * For simplicity, always handle both pages the same.
247 		 */
248 		vmbus_connection.monitor_pages[0] = NULL;
249 		vmbus_connection.monitor_pages[1] = NULL;
250 		goto cleanup;
251 	}
252 
253 	/*
254 	 * Set_memory_decrypted() will change the memory contents if
255 	 * decryption occurs, so zero monitor pages here.
256 	 */
257 	memset(vmbus_connection.monitor_pages[0], 0x00, HV_HYP_PAGE_SIZE);
258 	memset(vmbus_connection.monitor_pages[1], 0x00, HV_HYP_PAGE_SIZE);
259 
260 	msginfo = kzalloc(sizeof(*msginfo) +
261 			  sizeof(struct vmbus_channel_initiate_contact),
262 			  GFP_KERNEL);
263 	if (msginfo == NULL) {
264 		ret = -ENOMEM;
265 		goto cleanup;
266 	}
267 
268 	/*
269 	 * Negotiate a compatible VMBUS version number with the
270 	 * host. We start with the highest number we can support
271 	 * and work our way down until we negotiate a compatible
272 	 * version.
273 	 */
274 
275 	for (i = 0; ; i++) {
276 		if (i == ARRAY_SIZE(vmbus_versions)) {
277 			ret = -EDOM;
278 			goto cleanup;
279 		}
280 
281 		version = vmbus_versions[i];
282 		if (version > max_version)
283 			continue;
284 
285 		ret = vmbus_negotiate_version(msginfo, version);
286 		if (ret == -ETIMEDOUT)
287 			goto cleanup;
288 
289 		if (vmbus_connection.conn_state == CONNECTED)
290 			break;
291 	}
292 
293 	if (hv_is_isolation_supported() && version < VERSION_WIN10_V5_2) {
294 		pr_err("Invalid VMBus version %d.%d (expected >= %d.%d) from the host supporting isolation\n",
295 		       version >> 16, version & 0xFFFF, VERSION_WIN10_V5_2 >> 16, VERSION_WIN10_V5_2 & 0xFFFF);
296 		ret = -EINVAL;
297 		goto cleanup;
298 	}
299 
300 	vmbus_proto_version = version;
301 	pr_info("Vmbus version:%d.%d\n",
302 		version >> 16, version & 0xFFFF);
303 
304 	vmbus_connection.channels = kcalloc(MAX_CHANNEL_RELIDS,
305 					    sizeof(struct vmbus_channel *),
306 					    GFP_KERNEL);
307 	if (vmbus_connection.channels == NULL) {
308 		ret = -ENOMEM;
309 		goto cleanup;
310 	}
311 
312 	kfree(msginfo);
313 	return 0;
314 
315 cleanup:
316 	pr_err("Unable to connect to host\n");
317 
318 	vmbus_connection.conn_state = DISCONNECTED;
319 	vmbus_disconnect();
320 
321 	kfree(msginfo);
322 
323 	return ret;
324 }
325 
vmbus_disconnect(void)326 void vmbus_disconnect(void)
327 {
328 	/*
329 	 * First send the unload request to the host.
330 	 */
331 	vmbus_initiate_unload(false);
332 
333 	if (vmbus_connection.handle_sub_chan_wq)
334 		destroy_workqueue(vmbus_connection.handle_sub_chan_wq);
335 
336 	if (vmbus_connection.handle_primary_chan_wq)
337 		destroy_workqueue(vmbus_connection.handle_primary_chan_wq);
338 
339 	if (vmbus_connection.rescind_work_queue)
340 		destroy_workqueue(vmbus_connection.rescind_work_queue);
341 
342 	if (vmbus_connection.work_queue)
343 		destroy_workqueue(vmbus_connection.work_queue);
344 
345 	if (vmbus_connection.int_page) {
346 		hv_free_hyperv_page(vmbus_connection.int_page);
347 		vmbus_connection.int_page = NULL;
348 	}
349 
350 	if (vmbus_connection.monitor_pages[0]) {
351 		if (!set_memory_encrypted(
352 			(unsigned long)vmbus_connection.monitor_pages[0], 1))
353 			hv_free_hyperv_page(vmbus_connection.monitor_pages[0]);
354 		vmbus_connection.monitor_pages[0] = NULL;
355 	}
356 
357 	if (vmbus_connection.monitor_pages[1]) {
358 		if (!set_memory_encrypted(
359 			(unsigned long)vmbus_connection.monitor_pages[1], 1))
360 			hv_free_hyperv_page(vmbus_connection.monitor_pages[1]);
361 		vmbus_connection.monitor_pages[1] = NULL;
362 	}
363 }
364 
365 /*
366  * relid2channel - Get the channel object given its
367  * child relative id (ie channel id)
368  */
relid2channel(u32 relid)369 struct vmbus_channel *relid2channel(u32 relid)
370 {
371 	if (vmbus_connection.channels == NULL) {
372 		pr_warn_once("relid2channel: relid=%d: No channels mapped!\n", relid);
373 		return NULL;
374 	}
375 	if (WARN_ON(relid >= MAX_CHANNEL_RELIDS))
376 		return NULL;
377 	return READ_ONCE(vmbus_connection.channels[relid]);
378 }
379 
380 /*
381  * vmbus_on_event - Process a channel event notification
382  *
383  * For batched channels (default) optimize host to guest signaling
384  * by ensuring:
385  * 1. While reading the channel, we disable interrupts from host.
386  * 2. Ensure that we process all posted messages from the host
387  *    before returning from this callback.
388  * 3. Once we return, enable signaling from the host. Once this
389  *    state is set we check to see if additional packets are
390  *    available to read. In this case we repeat the process.
391  *    If this tasklet has been running for a long time
392  *    then reschedule ourselves.
393  */
vmbus_on_event(unsigned long data)394 void vmbus_on_event(unsigned long data)
395 {
396 	struct vmbus_channel *channel = (void *) data;
397 	void (*callback_fn)(void *context);
398 
399 	trace_vmbus_on_event(channel);
400 
401 	hv_debug_delay_test(channel, INTERRUPT_DELAY);
402 
403 	/* A channel once created is persistent even when
404 	 * there is no driver handling the device. An
405 	 * unloading driver sets the onchannel_callback to NULL.
406 	 */
407 	callback_fn = READ_ONCE(channel->onchannel_callback);
408 	if (unlikely(!callback_fn))
409 		return;
410 
411 	(*callback_fn)(channel->channel_callback_context);
412 
413 	if (channel->callback_mode != HV_CALL_BATCHED)
414 		return;
415 
416 	if (likely(hv_end_read(&channel->inbound) == 0))
417 		return;
418 
419 	hv_begin_read(&channel->inbound);
420 	tasklet_schedule(&channel->callback_event);
421 }
422 
423 /*
424  * vmbus_post_msg - Send a msg on the vmbus's message connection
425  */
vmbus_post_msg(void * buffer,size_t buflen,bool can_sleep)426 int vmbus_post_msg(void *buffer, size_t buflen, bool can_sleep)
427 {
428 	struct vmbus_channel_message_header *hdr;
429 	union hv_connection_id conn_id;
430 	int ret = 0;
431 	int retries = 0;
432 	u32 usec = 1;
433 
434 	conn_id.asu32 = 0;
435 	conn_id.u.id = vmbus_connection.msg_conn_id;
436 
437 	/*
438 	 * hv_post_message() can have transient failures because of
439 	 * insufficient resources. Retry the operation a couple of
440 	 * times before giving up.
441 	 */
442 	while (retries < 100) {
443 		ret = hv_post_message(conn_id, 1, buffer, buflen);
444 
445 		switch (ret) {
446 		case HV_STATUS_INVALID_CONNECTION_ID:
447 			/*
448 			 * See vmbus_negotiate_version(): VMBus protocol 5.0
449 			 * and higher require that we must use
450 			 * VMBUS_MESSAGE_CONNECTION_ID_4 for the Initiate
451 			 * Contact message, but on old hosts that only
452 			 * support VMBus protocol 4.0 or lower, here we get
453 			 * HV_STATUS_INVALID_CONNECTION_ID and we should
454 			 * return an error immediately without retrying.
455 			 */
456 			hdr = buffer;
457 			if (hdr->msgtype == CHANNELMSG_INITIATE_CONTACT)
458 				return -EINVAL;
459 			/*
460 			 * We could get this if we send messages too
461 			 * frequently.
462 			 */
463 			ret = -EAGAIN;
464 			break;
465 		case HV_STATUS_INSUFFICIENT_MEMORY:
466 		case HV_STATUS_INSUFFICIENT_BUFFERS:
467 			ret = -ENOBUFS;
468 			break;
469 		case HV_STATUS_SUCCESS:
470 			return ret;
471 		default:
472 			pr_err("hv_post_msg() failed; error code:%d\n", ret);
473 			return -EINVAL;
474 		}
475 
476 		retries++;
477 		if (can_sleep && usec > 1000)
478 			msleep(usec / 1000);
479 		else if (usec < MAX_UDELAY_MS * 1000)
480 			udelay(usec);
481 		else
482 			mdelay(usec / 1000);
483 
484 		if (retries < 22)
485 			usec *= 2;
486 	}
487 	return ret;
488 }
489 
490 /*
491  * vmbus_set_event - Send an event notification to the parent
492  */
vmbus_set_event(struct vmbus_channel * channel)493 void vmbus_set_event(struct vmbus_channel *channel)
494 {
495 	u32 child_relid = channel->offermsg.child_relid;
496 
497 	if (!channel->is_dedicated_interrupt)
498 		vmbus_send_interrupt(child_relid);
499 
500 	++channel->sig_events;
501 
502 	if (ms_hyperv.paravisor_present) {
503 		if (hv_isolation_type_snp())
504 			hv_ghcb_hypercall(HVCALL_SIGNAL_EVENT, &channel->sig_event,
505 					  NULL, sizeof(channel->sig_event));
506 		else if (hv_isolation_type_tdx())
507 			hv_tdx_hypercall(HVCALL_SIGNAL_EVENT | HV_HYPERCALL_FAST_BIT,
508 					 channel->sig_event, 0);
509 		else
510 			WARN_ON_ONCE(1);
511 	} else {
512 		hv_do_fast_hypercall8(HVCALL_SIGNAL_EVENT, channel->sig_event);
513 	}
514 }
515 EXPORT_SYMBOL_GPL(vmbus_set_event);
516