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