xref: /linux/drivers/hv/channel.c (revision 5f054ef2e0f1ca7d32ac48e275d08e2ac29d84f3)
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/sched.h>
13 #include <linux/wait.h>
14 #include <linux/mm.h>
15 #include <linux/slab.h>
16 #include <linux/module.h>
17 #include <linux/hyperv.h>
18 #include <linux/uio.h>
19 #include <linux/interrupt.h>
20 #include <linux/set_memory.h>
21 #include <linux/export.h>
22 #include <asm/page.h>
23 #include <asm/mshyperv.h>
24 
25 #include "hyperv_vmbus.h"
26 
27 /*
28  * hv_gpadl_size - Return the real size of a gpadl, the size that Hyper-V uses
29  *
30  * For BUFFER gpadl, Hyper-V uses the exact same size as the guest does.
31  *
32  * For RING gpadl, in each ring, the guest uses one PAGE_SIZE as the header
33  * (because of the alignment requirement), however, the hypervisor only
34  * uses the first HV_HYP_PAGE_SIZE as the header, therefore leaving a
35  * (PAGE_SIZE - HV_HYP_PAGE_SIZE) gap. And since there are two rings in a
36  * ringbuffer, the total size for a RING gpadl that Hyper-V uses is the
37  * total size that the guest uses minus twice of the gap size.
38  */
hv_gpadl_size(enum hv_gpadl_type type,u32 size)39 static inline u32 hv_gpadl_size(enum hv_gpadl_type type, u32 size)
40 {
41 	switch (type) {
42 	case HV_GPADL_BUFFER:
43 		return size;
44 	case HV_GPADL_RING:
45 		/* The size of a ringbuffer must be page-aligned */
46 		BUG_ON(size % PAGE_SIZE);
47 		/*
48 		 * Two things to notice here:
49 		 * 1) We're processing two ring buffers as a unit
50 		 * 2) We're skipping any space larger than HV_HYP_PAGE_SIZE in
51 		 * the first guest-size page of each of the two ring buffers.
52 		 * So we effectively subtract out two guest-size pages, and add
53 		 * back two Hyper-V size pages.
54 		 */
55 		return size - 2 * (PAGE_SIZE - HV_HYP_PAGE_SIZE);
56 	}
57 	BUG();
58 	return 0;
59 }
60 
61 /*
62  * hv_ring_gpadl_send_hvpgoffset - Calculate the send offset (in unit of
63  *                                 HV_HYP_PAGE) in a ring gpadl based on the
64  *                                 offset in the guest
65  *
66  * @offset: the offset (in bytes) where the send ringbuffer starts in the
67  *               virtual address space of the guest
68  */
hv_ring_gpadl_send_hvpgoffset(u32 offset)69 static inline u32 hv_ring_gpadl_send_hvpgoffset(u32 offset)
70 {
71 
72 	/*
73 	 * For RING gpadl, in each ring, the guest uses one PAGE_SIZE as the
74 	 * header (because of the alignment requirement), however, the
75 	 * hypervisor only uses the first HV_HYP_PAGE_SIZE as the header,
76 	 * therefore leaving a (PAGE_SIZE - HV_HYP_PAGE_SIZE) gap.
77 	 *
78 	 * And to calculate the effective send offset in gpadl, we need to
79 	 * substract this gap.
80 	 */
81 	return (offset - (PAGE_SIZE - HV_HYP_PAGE_SIZE)) >> HV_HYP_PAGE_SHIFT;
82 }
83 
84 /*
85  * hv_gpadl_hvpfn - Return the Hyper-V page PFN of the @i th Hyper-V page in
86  *                  the gpadl
87  *
88  * @type: the type of the gpadl
89  * @kbuffer: the pointer to the gpadl in the guest
90  * @size: the total size (in bytes) of the gpadl
91  * @send_offset: the offset (in bytes) where the send ringbuffer starts in the
92  *               virtual address space of the guest
93  * @i: the index
94  */
hv_gpadl_hvpfn(enum hv_gpadl_type type,void * kbuffer,u32 size,u32 send_offset,int i)95 static inline u64 hv_gpadl_hvpfn(enum hv_gpadl_type type, void *kbuffer,
96 				 u32 size, u32 send_offset, int i)
97 {
98 	int send_idx = hv_ring_gpadl_send_hvpgoffset(send_offset);
99 	unsigned long delta = 0UL;
100 
101 	switch (type) {
102 	case HV_GPADL_BUFFER:
103 		break;
104 	case HV_GPADL_RING:
105 		if (i == 0)
106 			delta = 0;
107 		else if (i <= send_idx)
108 			delta = PAGE_SIZE - HV_HYP_PAGE_SIZE;
109 		else
110 			delta = 2 * (PAGE_SIZE - HV_HYP_PAGE_SIZE);
111 		break;
112 	default:
113 		BUG();
114 		break;
115 	}
116 
117 	return virt_to_hvpfn(kbuffer + delta + (HV_HYP_PAGE_SIZE * i));
118 }
119 
120 /*
121  * vmbus_setevent- Trigger an event notification on the specified
122  * channel.
123  */
vmbus_setevent(struct vmbus_channel * channel)124 void vmbus_setevent(struct vmbus_channel *channel)
125 {
126 	struct hv_monitor_page *monitorpage;
127 
128 	trace_vmbus_setevent(channel);
129 
130 	/*
131 	 * For channels marked as in "low latency" mode
132 	 * bypass the monitor page mechanism.
133 	 */
134 	if (channel->offermsg.monitor_allocated && !channel->low_latency) {
135 		vmbus_send_interrupt(channel->offermsg.child_relid);
136 
137 		/* Get the child to parent monitor page */
138 		monitorpage = vmbus_connection.monitor_pages[1];
139 
140 		sync_set_bit(channel->monitor_bit,
141 			(unsigned long *)&monitorpage->trigger_group
142 					[channel->monitor_grp].pending);
143 
144 	} else {
145 		vmbus_set_event(channel);
146 	}
147 }
148 EXPORT_SYMBOL_GPL(vmbus_setevent);
149 
150 /* vmbus_free_ring - drop mapping of ring buffer */
vmbus_free_ring(struct vmbus_channel * channel)151 void vmbus_free_ring(struct vmbus_channel *channel)
152 {
153 	hv_ringbuffer_cleanup(&channel->outbound);
154 	hv_ringbuffer_cleanup(&channel->inbound);
155 
156 	if (channel->ringbuffer_page) {
157 		/* In a CoCo VM leak the memory if it didn't get re-encrypted */
158 		if (!channel->ringbuffer_gpadlhandle.decrypted)
159 			__free_pages(channel->ringbuffer_page,
160 			     get_order(channel->ringbuffer_pagecount
161 				       << PAGE_SHIFT));
162 		channel->ringbuffer_page = NULL;
163 	}
164 }
165 EXPORT_SYMBOL_GPL(vmbus_free_ring);
166 
167 /* vmbus_alloc_ring - allocate and map pages for ring buffer */
vmbus_alloc_ring(struct vmbus_channel * newchannel,u32 send_size,u32 recv_size)168 int vmbus_alloc_ring(struct vmbus_channel *newchannel,
169 		     u32 send_size, u32 recv_size)
170 {
171 	struct page *page;
172 	int order;
173 
174 	if (send_size % PAGE_SIZE || recv_size % PAGE_SIZE)
175 		return -EINVAL;
176 
177 	/* Allocate the ring buffer */
178 	order = get_order(send_size + recv_size);
179 	page = alloc_pages_node(cpu_to_node(newchannel->target_cpu),
180 				GFP_KERNEL|__GFP_ZERO, order);
181 
182 	if (!page)
183 		page = alloc_pages(GFP_KERNEL|__GFP_ZERO, order);
184 
185 	if (!page)
186 		return -ENOMEM;
187 
188 	newchannel->ringbuffer_page = page;
189 	newchannel->ringbuffer_pagecount = (send_size + recv_size) >> PAGE_SHIFT;
190 	newchannel->ringbuffer_send_offset = send_size >> PAGE_SHIFT;
191 
192 	return 0;
193 }
194 EXPORT_SYMBOL_GPL(vmbus_alloc_ring);
195 
196 /* Used for Hyper-V Socket: a guest client's connect() to the host */
vmbus_send_tl_connect_request(const guid_t * shv_guest_servie_id,const guid_t * shv_host_servie_id)197 int vmbus_send_tl_connect_request(const guid_t *shv_guest_servie_id,
198 				  const guid_t *shv_host_servie_id)
199 {
200 	struct vmbus_channel_tl_connect_request conn_msg;
201 	int ret;
202 
203 	memset(&conn_msg, 0, sizeof(conn_msg));
204 	conn_msg.header.msgtype = CHANNELMSG_TL_CONNECT_REQUEST;
205 	conn_msg.guest_endpoint_id = *shv_guest_servie_id;
206 	conn_msg.host_service_id = *shv_host_servie_id;
207 
208 	ret = vmbus_post_msg(&conn_msg, sizeof(conn_msg), true);
209 
210 	trace_vmbus_send_tl_connect_request(&conn_msg, ret);
211 
212 	return ret;
213 }
214 EXPORT_SYMBOL_GPL(vmbus_send_tl_connect_request);
215 
send_modifychannel_without_ack(struct vmbus_channel * channel,u32 target_vp)216 static int send_modifychannel_without_ack(struct vmbus_channel *channel, u32 target_vp)
217 {
218 	struct vmbus_channel_modifychannel msg;
219 	int ret;
220 
221 	memset(&msg, 0, sizeof(msg));
222 	msg.header.msgtype = CHANNELMSG_MODIFYCHANNEL;
223 	msg.child_relid = channel->offermsg.child_relid;
224 	msg.target_vp = target_vp;
225 
226 	ret = vmbus_post_msg(&msg, sizeof(msg), true);
227 	trace_vmbus_send_modifychannel(&msg, ret);
228 
229 	return ret;
230 }
231 
send_modifychannel_with_ack(struct vmbus_channel * channel,u32 target_vp)232 static int send_modifychannel_with_ack(struct vmbus_channel *channel, u32 target_vp)
233 {
234 	struct vmbus_channel_modifychannel *msg;
235 	struct vmbus_channel_msginfo *info;
236 	unsigned long flags;
237 	int ret;
238 
239 	info = kzalloc(sizeof(struct vmbus_channel_msginfo) +
240 				sizeof(struct vmbus_channel_modifychannel),
241 		       GFP_KERNEL);
242 	if (!info)
243 		return -ENOMEM;
244 
245 	init_completion(&info->waitevent);
246 	info->waiting_channel = channel;
247 
248 	msg = (struct vmbus_channel_modifychannel *)info->msg;
249 	msg->header.msgtype = CHANNELMSG_MODIFYCHANNEL;
250 	msg->child_relid = channel->offermsg.child_relid;
251 	msg->target_vp = target_vp;
252 
253 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
254 	list_add_tail(&info->msglistentry, &vmbus_connection.chn_msg_list);
255 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
256 
257 	ret = vmbus_post_msg(msg, sizeof(*msg), true);
258 	trace_vmbus_send_modifychannel(msg, ret);
259 	if (ret != 0) {
260 		spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
261 		list_del(&info->msglistentry);
262 		spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
263 		goto free_info;
264 	}
265 
266 	/*
267 	 * Release channel_mutex; otherwise, vmbus_onoffer_rescind() could block on
268 	 * the mutex and be unable to signal the completion.
269 	 *
270 	 * See the caller target_cpu_store() for information about the usage of the
271 	 * mutex.
272 	 */
273 	mutex_unlock(&vmbus_connection.channel_mutex);
274 	wait_for_completion(&info->waitevent);
275 	mutex_lock(&vmbus_connection.channel_mutex);
276 
277 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
278 	list_del(&info->msglistentry);
279 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
280 
281 	if (info->response.modify_response.status)
282 		ret = -EAGAIN;
283 
284 free_info:
285 	kfree(info);
286 	return ret;
287 }
288 
289 /*
290  * Set/change the vCPU (@target_vp) the channel (@child_relid) will interrupt.
291  *
292  * CHANNELMSG_MODIFYCHANNEL messages are aynchronous.  When VMbus version 5.3
293  * or later is negotiated, Hyper-V always sends an ACK in response to such a
294  * message.  For VMbus version 5.2 and earlier, it never sends an ACK.  With-
295  * out an ACK, we can not know when the host will stop interrupting the "old"
296  * vCPU and start interrupting the "new" vCPU for the given channel.
297  *
298  * The CHANNELMSG_MODIFYCHANNEL message type is supported since VMBus version
299  * VERSION_WIN10_V4_1.
300  */
vmbus_send_modifychannel(struct vmbus_channel * channel,u32 target_vp)301 int vmbus_send_modifychannel(struct vmbus_channel *channel, u32 target_vp)
302 {
303 	if (vmbus_proto_version >= VERSION_WIN10_V5_3)
304 		return send_modifychannel_with_ack(channel, target_vp);
305 	return send_modifychannel_without_ack(channel, target_vp);
306 }
307 EXPORT_SYMBOL_GPL(vmbus_send_modifychannel);
308 
309 /*
310  * create_gpadl_header - Creates a gpadl for the specified buffer
311  */
create_gpadl_header(enum hv_gpadl_type type,void * kbuffer,u32 size,u32 send_offset,struct vmbus_channel_msginfo ** msginfo)312 static int create_gpadl_header(enum hv_gpadl_type type, void *kbuffer,
313 			       u32 size, u32 send_offset,
314 			       struct vmbus_channel_msginfo **msginfo)
315 {
316 	int i;
317 	int pagecount;
318 	struct vmbus_channel_gpadl_header *gpadl_header;
319 	struct vmbus_channel_gpadl_body *gpadl_body;
320 	struct vmbus_channel_msginfo *msgheader;
321 	struct vmbus_channel_msginfo *msgbody = NULL;
322 	u32 msgsize;
323 
324 	int pfnsum, pfncount, pfnleft, pfncurr, pfnsize;
325 
326 	pagecount = hv_gpadl_size(type, size) >> HV_HYP_PAGE_SHIFT;
327 
328 	pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
329 		  sizeof(struct vmbus_channel_gpadl_header) -
330 		  sizeof(struct gpa_range);
331 	pfncount = umin(pagecount, pfnsize / sizeof(u64));
332 
333 	msgsize = sizeof(struct vmbus_channel_msginfo) +
334 		  sizeof(struct vmbus_channel_gpadl_header) +
335 		  sizeof(struct gpa_range) + pfncount * sizeof(u64);
336 	msgheader =  kzalloc(msgsize, GFP_KERNEL);
337 	if (!msgheader)
338 		return -ENOMEM;
339 
340 	INIT_LIST_HEAD(&msgheader->submsglist);
341 	msgheader->msgsize = msgsize;
342 
343 	gpadl_header = (struct vmbus_channel_gpadl_header *)
344 		msgheader->msg;
345 	gpadl_header->rangecount = 1;
346 	gpadl_header->range_buflen = sizeof(struct gpa_range) +
347 				 pagecount * sizeof(u64);
348 	gpadl_header->range[0].byte_offset = 0;
349 	gpadl_header->range[0].byte_count = hv_gpadl_size(type, size);
350 	for (i = 0; i < pfncount; i++)
351 		gpadl_header->range[0].pfn_array[i] = hv_gpadl_hvpfn(
352 			type, kbuffer, size, send_offset, i);
353 	*msginfo = msgheader;
354 
355 	pfnsum = pfncount;
356 	pfnleft = pagecount - pfncount;
357 
358 	/* how many pfns can we fit in a body message */
359 	pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
360 		  sizeof(struct vmbus_channel_gpadl_body);
361 	pfncount = pfnsize / sizeof(u64);
362 
363 	/*
364 	 * If pfnleft is zero, everything fits in the header and no body
365 	 * messages are needed
366 	 */
367 	while (pfnleft) {
368 		pfncurr = umin(pfncount, pfnleft);
369 		msgsize = sizeof(struct vmbus_channel_msginfo) +
370 			  sizeof(struct vmbus_channel_gpadl_body) +
371 			  pfncurr * sizeof(u64);
372 		msgbody = kzalloc(msgsize, GFP_KERNEL);
373 
374 		if (!msgbody) {
375 			struct vmbus_channel_msginfo *pos = NULL;
376 			struct vmbus_channel_msginfo *tmp = NULL;
377 			/*
378 			 * Free up all the allocated messages.
379 			 */
380 			list_for_each_entry_safe(pos, tmp,
381 				&msgheader->submsglist,
382 				msglistentry) {
383 
384 				list_del(&pos->msglistentry);
385 				kfree(pos);
386 			}
387 			kfree(msgheader);
388 			return -ENOMEM;
389 		}
390 
391 		msgbody->msgsize = msgsize;
392 		gpadl_body = (struct vmbus_channel_gpadl_body *)msgbody->msg;
393 
394 		/*
395 		 * Gpadl is u32 and we are using a pointer which could
396 		 * be 64-bit
397 		 * This is governed by the guest/host protocol and
398 		 * so the hypervisor guarantees that this is ok.
399 		 */
400 		for (i = 0; i < pfncurr; i++)
401 			gpadl_body->pfn[i] = hv_gpadl_hvpfn(type,
402 				kbuffer, size, send_offset, pfnsum + i);
403 
404 		/* add to msg header */
405 		list_add_tail(&msgbody->msglistentry, &msgheader->submsglist);
406 		pfnsum += pfncurr;
407 		pfnleft -= pfncurr;
408 	}
409 
410 	return 0;
411 }
412 
413 /*
414  * __vmbus_establish_gpadl - Establish a GPADL for a buffer or ringbuffer
415  *
416  * @channel: a channel
417  * @type: the type of the corresponding GPADL, only meaningful for the guest.
418  * @kbuffer: from kmalloc or vmalloc
419  * @size: page-size multiple
420  * @send_offset: the offset (in bytes) where the send ring buffer starts,
421  *              should be 0 for BUFFER type gpadl
422  * @gpadl_handle: some funky thing
423  */
__vmbus_establish_gpadl(struct vmbus_channel * channel,enum hv_gpadl_type type,void * kbuffer,u32 size,u32 send_offset,struct vmbus_gpadl * gpadl)424 static int __vmbus_establish_gpadl(struct vmbus_channel *channel,
425 				   enum hv_gpadl_type type, void *kbuffer,
426 				   u32 size, u32 send_offset,
427 				   struct vmbus_gpadl *gpadl)
428 {
429 	struct vmbus_channel_gpadl_header *gpadlmsg;
430 	struct vmbus_channel_gpadl_body *gpadl_body;
431 	struct vmbus_channel_msginfo *msginfo = NULL;
432 	struct vmbus_channel_msginfo *submsginfo, *tmp;
433 	struct list_head *curr;
434 	u32 next_gpadl_handle;
435 	unsigned long flags;
436 	int ret = 0;
437 
438 	next_gpadl_handle =
439 		(atomic_inc_return(&vmbus_connection.next_gpadl_handle) - 1);
440 
441 	ret = create_gpadl_header(type, kbuffer, size, send_offset, &msginfo);
442 	if (ret) {
443 		gpadl->decrypted = false;
444 		return ret;
445 	}
446 
447 	/*
448 	 * Set the "decrypted" flag to true for the set_memory_decrypted()
449 	 * success case. In the failure case, the encryption state of the
450 	 * memory is unknown. Leave "decrypted" as true to ensure the
451 	 * memory will be leaked instead of going back on the free list.
452 	 */
453 	gpadl->decrypted = true;
454 	ret = set_memory_decrypted((unsigned long)kbuffer,
455 				   PFN_UP(size));
456 	if (ret) {
457 		dev_warn(&channel->device_obj->device,
458 			 "Failed to set host visibility for new GPADL %d.\n",
459 			 ret);
460 		return ret;
461 	}
462 
463 	init_completion(&msginfo->waitevent);
464 	msginfo->waiting_channel = channel;
465 
466 	gpadlmsg = (struct vmbus_channel_gpadl_header *)msginfo->msg;
467 	gpadlmsg->header.msgtype = CHANNELMSG_GPADL_HEADER;
468 	gpadlmsg->child_relid = channel->offermsg.child_relid;
469 	gpadlmsg->gpadl = next_gpadl_handle;
470 
471 
472 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
473 	list_add_tail(&msginfo->msglistentry,
474 		      &vmbus_connection.chn_msg_list);
475 
476 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
477 
478 	if (channel->rescind) {
479 		ret = -ENODEV;
480 		goto cleanup;
481 	}
482 
483 	ret = vmbus_post_msg(gpadlmsg, msginfo->msgsize -
484 			     sizeof(*msginfo), true);
485 
486 	trace_vmbus_establish_gpadl_header(gpadlmsg, ret);
487 
488 	if (ret != 0)
489 		goto cleanup;
490 
491 	list_for_each(curr, &msginfo->submsglist) {
492 		submsginfo = (struct vmbus_channel_msginfo *)curr;
493 		gpadl_body =
494 			(struct vmbus_channel_gpadl_body *)submsginfo->msg;
495 
496 		gpadl_body->header.msgtype =
497 			CHANNELMSG_GPADL_BODY;
498 		gpadl_body->gpadl = next_gpadl_handle;
499 
500 		ret = vmbus_post_msg(gpadl_body,
501 				     submsginfo->msgsize - sizeof(*submsginfo),
502 				     true);
503 
504 		trace_vmbus_establish_gpadl_body(gpadl_body, ret);
505 
506 		if (ret != 0)
507 			goto cleanup;
508 
509 	}
510 	wait_for_completion(&msginfo->waitevent);
511 
512 	if (msginfo->response.gpadl_created.creation_status != 0) {
513 		pr_err("Failed to establish GPADL: err = 0x%x\n",
514 		       msginfo->response.gpadl_created.creation_status);
515 
516 		ret = -EDQUOT;
517 		goto cleanup;
518 	}
519 
520 	if (channel->rescind) {
521 		ret = -ENODEV;
522 		goto cleanup;
523 	}
524 
525 	/* At this point, we received the gpadl created msg */
526 	gpadl->gpadl_handle = gpadlmsg->gpadl;
527 	gpadl->buffer = kbuffer;
528 	gpadl->size = size;
529 
530 
531 cleanup:
532 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
533 	list_del(&msginfo->msglistentry);
534 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
535 	list_for_each_entry_safe(submsginfo, tmp, &msginfo->submsglist,
536 				 msglistentry) {
537 		kfree(submsginfo);
538 	}
539 
540 	kfree(msginfo);
541 
542 	if (ret) {
543 		/*
544 		 * If set_memory_encrypted() fails, the decrypted flag is
545 		 * left as true so the memory is leaked instead of being
546 		 * put back on the free list.
547 		 */
548 		if (!set_memory_encrypted((unsigned long)kbuffer, PFN_UP(size)))
549 			gpadl->decrypted = false;
550 	}
551 
552 	return ret;
553 }
554 
555 /*
556  * vmbus_establish_gpadl - Establish a GPADL for the specified buffer
557  *
558  * @channel: a channel
559  * @kbuffer: from kmalloc or vmalloc
560  * @size: page-size multiple
561  * @gpadl_handle: some funky thing
562  */
vmbus_establish_gpadl(struct vmbus_channel * channel,void * kbuffer,u32 size,struct vmbus_gpadl * gpadl)563 int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,
564 			  u32 size, struct vmbus_gpadl *gpadl)
565 {
566 	return __vmbus_establish_gpadl(channel, HV_GPADL_BUFFER, kbuffer, size,
567 				       0U, gpadl);
568 }
569 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
570 
571 /**
572  * request_arr_init - Allocates memory for the requestor array. Each slot
573  * keeps track of the next available slot in the array. Initially, each
574  * slot points to the next one (as in a Linked List). The last slot
575  * does not point to anything, so its value is U64_MAX by default.
576  * @size The size of the array
577  */
request_arr_init(u32 size)578 static u64 *request_arr_init(u32 size)
579 {
580 	int i;
581 	u64 *req_arr;
582 
583 	req_arr = kcalloc(size, sizeof(u64), GFP_KERNEL);
584 	if (!req_arr)
585 		return NULL;
586 
587 	for (i = 0; i < size - 1; i++)
588 		req_arr[i] = i + 1;
589 
590 	/* Last slot (no more available slots) */
591 	req_arr[i] = U64_MAX;
592 
593 	return req_arr;
594 }
595 
596 /*
597  * vmbus_alloc_requestor - Initializes @rqstor's fields.
598  * Index 0 is the first free slot
599  * @size: Size of the requestor array
600  */
vmbus_alloc_requestor(struct vmbus_requestor * rqstor,u32 size)601 static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)
602 {
603 	u64 *rqst_arr;
604 	unsigned long *bitmap;
605 
606 	rqst_arr = request_arr_init(size);
607 	if (!rqst_arr)
608 		return -ENOMEM;
609 
610 	bitmap = bitmap_zalloc(size, GFP_KERNEL);
611 	if (!bitmap) {
612 		kfree(rqst_arr);
613 		return -ENOMEM;
614 	}
615 
616 	rqstor->req_arr = rqst_arr;
617 	rqstor->req_bitmap = bitmap;
618 	rqstor->size = size;
619 	rqstor->next_request_id = 0;
620 	spin_lock_init(&rqstor->req_lock);
621 
622 	return 0;
623 }
624 
625 /*
626  * vmbus_free_requestor - Frees memory allocated for @rqstor
627  * @rqstor: Pointer to the requestor struct
628  */
vmbus_free_requestor(struct vmbus_requestor * rqstor)629 static void vmbus_free_requestor(struct vmbus_requestor *rqstor)
630 {
631 	kfree(rqstor->req_arr);
632 	bitmap_free(rqstor->req_bitmap);
633 }
634 
__vmbus_open(struct vmbus_channel * newchannel,void * userdata,u32 userdatalen,void (* onchannelcallback)(void * context),void * context)635 static int __vmbus_open(struct vmbus_channel *newchannel,
636 		       void *userdata, u32 userdatalen,
637 		       void (*onchannelcallback)(void *context), void *context)
638 {
639 	struct vmbus_channel_open_channel *open_msg;
640 	struct vmbus_channel_msginfo *open_info = NULL;
641 	struct page *page = newchannel->ringbuffer_page;
642 	u32 send_pages, recv_pages;
643 	unsigned long flags;
644 	int err;
645 
646 	if (userdatalen > MAX_USER_DEFINED_BYTES)
647 		return -EINVAL;
648 
649 	send_pages = newchannel->ringbuffer_send_offset;
650 	recv_pages = newchannel->ringbuffer_pagecount - send_pages;
651 
652 	if (newchannel->state != CHANNEL_OPEN_STATE)
653 		return -EINVAL;
654 
655 	/* Create and init requestor */
656 	if (newchannel->rqstor_size) {
657 		if (vmbus_alloc_requestor(&newchannel->requestor, newchannel->rqstor_size))
658 			return -ENOMEM;
659 	}
660 
661 	newchannel->state = CHANNEL_OPENING_STATE;
662 	newchannel->onchannel_callback = onchannelcallback;
663 	newchannel->channel_callback_context = context;
664 
665 	if (!newchannel->max_pkt_size)
666 		newchannel->max_pkt_size = VMBUS_DEFAULT_MAX_PKT_SIZE;
667 
668 	/* Establish the gpadl for the ring buffer */
669 	newchannel->ringbuffer_gpadlhandle.gpadl_handle = 0;
670 
671 	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING,
672 				      page_address(newchannel->ringbuffer_page),
673 				      (send_pages + recv_pages) << PAGE_SHIFT,
674 				      newchannel->ringbuffer_send_offset << PAGE_SHIFT,
675 				      &newchannel->ringbuffer_gpadlhandle);
676 	if (err)
677 		goto error_clean_ring;
678 
679 	err = hv_ringbuffer_init(&newchannel->outbound,
680 				 page, send_pages, 0);
681 	if (err)
682 		goto error_free_gpadl;
683 
684 	err = hv_ringbuffer_init(&newchannel->inbound, &page[send_pages],
685 				 recv_pages, newchannel->max_pkt_size);
686 	if (err)
687 		goto error_free_gpadl;
688 
689 	/* Create and init the channel open message */
690 	open_info = kzalloc(sizeof(*open_info) +
691 			   sizeof(struct vmbus_channel_open_channel),
692 			   GFP_KERNEL);
693 	if (!open_info) {
694 		err = -ENOMEM;
695 		goto error_free_gpadl;
696 	}
697 
698 	init_completion(&open_info->waitevent);
699 	open_info->waiting_channel = newchannel;
700 
701 	open_msg = (struct vmbus_channel_open_channel *)open_info->msg;
702 	open_msg->header.msgtype = CHANNELMSG_OPENCHANNEL;
703 	open_msg->openid = newchannel->offermsg.child_relid;
704 	open_msg->child_relid = newchannel->offermsg.child_relid;
705 	open_msg->ringbuffer_gpadlhandle
706 		= newchannel->ringbuffer_gpadlhandle.gpadl_handle;
707 	/*
708 	 * The unit of ->downstream_ringbuffer_pageoffset is HV_HYP_PAGE and
709 	 * the unit of ->ringbuffer_send_offset (i.e. send_pages) is PAGE, so
710 	 * here we calculate it into HV_HYP_PAGE.
711 	 */
712 	open_msg->downstream_ringbuffer_pageoffset =
713 		hv_ring_gpadl_send_hvpgoffset(send_pages << PAGE_SHIFT);
714 	open_msg->target_vp = hv_cpu_number_to_vp_number(newchannel->target_cpu);
715 
716 	if (userdatalen)
717 		memcpy(open_msg->userdata, userdata, userdatalen);
718 
719 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
720 	list_add_tail(&open_info->msglistentry,
721 		      &vmbus_connection.chn_msg_list);
722 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
723 
724 	if (newchannel->rescind) {
725 		err = -ENODEV;
726 		goto error_clean_msglist;
727 	}
728 
729 	err = vmbus_post_msg(open_msg,
730 			     sizeof(struct vmbus_channel_open_channel), true);
731 
732 	trace_vmbus_open(open_msg, err);
733 
734 	if (err != 0)
735 		goto error_clean_msglist;
736 
737 	wait_for_completion(&open_info->waitevent);
738 
739 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
740 	list_del(&open_info->msglistentry);
741 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
742 
743 	if (newchannel->rescind) {
744 		err = -ENODEV;
745 		goto error_free_info;
746 	}
747 
748 	if (open_info->response.open_result.status) {
749 		err = -EAGAIN;
750 		goto error_free_info;
751 	}
752 
753 	newchannel->state = CHANNEL_OPENED_STATE;
754 	kfree(open_info);
755 	return 0;
756 
757 error_clean_msglist:
758 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
759 	list_del(&open_info->msglistentry);
760 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
761 error_free_info:
762 	kfree(open_info);
763 error_free_gpadl:
764 	vmbus_teardown_gpadl(newchannel, &newchannel->ringbuffer_gpadlhandle);
765 error_clean_ring:
766 	hv_ringbuffer_cleanup(&newchannel->outbound);
767 	hv_ringbuffer_cleanup(&newchannel->inbound);
768 	vmbus_free_requestor(&newchannel->requestor);
769 	newchannel->state = CHANNEL_OPEN_STATE;
770 	return err;
771 }
772 
773 /*
774  * vmbus_connect_ring - Open the channel but reuse ring buffer
775  */
vmbus_connect_ring(struct vmbus_channel * newchannel,void (* onchannelcallback)(void * context),void * context)776 int vmbus_connect_ring(struct vmbus_channel *newchannel,
777 		       void (*onchannelcallback)(void *context), void *context)
778 {
779 	return  __vmbus_open(newchannel, NULL, 0, onchannelcallback, context);
780 }
781 EXPORT_SYMBOL_GPL(vmbus_connect_ring);
782 
783 /*
784  * vmbus_open - Open the specified channel.
785  */
vmbus_open(struct vmbus_channel * newchannel,u32 send_ringbuffer_size,u32 recv_ringbuffer_size,void * userdata,u32 userdatalen,void (* onchannelcallback)(void * context),void * context)786 int vmbus_open(struct vmbus_channel *newchannel,
787 	       u32 send_ringbuffer_size, u32 recv_ringbuffer_size,
788 	       void *userdata, u32 userdatalen,
789 	       void (*onchannelcallback)(void *context), void *context)
790 {
791 	int err;
792 
793 	err = vmbus_alloc_ring(newchannel, send_ringbuffer_size,
794 			       recv_ringbuffer_size);
795 	if (err)
796 		return err;
797 
798 	err = __vmbus_open(newchannel, userdata, userdatalen,
799 			   onchannelcallback, context);
800 	if (err)
801 		vmbus_free_ring(newchannel);
802 
803 	return err;
804 }
805 EXPORT_SYMBOL_GPL(vmbus_open);
806 
807 /*
808  * vmbus_teardown_gpadl -Teardown the specified GPADL handle
809  */
vmbus_teardown_gpadl(struct vmbus_channel * channel,struct vmbus_gpadl * gpadl)810 int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpadl)
811 {
812 	struct vmbus_channel_gpadl_teardown *msg;
813 	struct vmbus_channel_msginfo *info;
814 	unsigned long flags;
815 	int ret;
816 
817 	info = kzalloc(sizeof(*info) +
818 		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
819 	if (!info)
820 		return -ENOMEM;
821 
822 	init_completion(&info->waitevent);
823 	info->waiting_channel = channel;
824 
825 	msg = (struct vmbus_channel_gpadl_teardown *)info->msg;
826 
827 	msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
828 	msg->child_relid = channel->offermsg.child_relid;
829 	msg->gpadl = gpadl->gpadl_handle;
830 
831 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
832 	list_add_tail(&info->msglistentry,
833 		      &vmbus_connection.chn_msg_list);
834 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
835 
836 	if (channel->rescind)
837 		goto post_msg_err;
838 
839 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),
840 			     true);
841 
842 	trace_vmbus_teardown_gpadl(msg, ret);
843 
844 	if (ret)
845 		goto post_msg_err;
846 
847 	wait_for_completion(&info->waitevent);
848 
849 	gpadl->gpadl_handle = 0;
850 
851 post_msg_err:
852 	/*
853 	 * If the channel has been rescinded;
854 	 * we will be awakened by the rescind
855 	 * handler; set the error code to zero so we don't leak memory.
856 	 */
857 	if (channel->rescind)
858 		ret = 0;
859 
860 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
861 	list_del(&info->msglistentry);
862 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
863 
864 	kfree(info);
865 
866 	ret = set_memory_encrypted((unsigned long)gpadl->buffer,
867 				   PFN_UP(gpadl->size));
868 	if (ret)
869 		pr_warn("Fail to set mem host visibility in GPADL teardown %d.\n", ret);
870 
871 	gpadl->decrypted = ret;
872 
873 	return ret;
874 }
875 EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl);
876 
vmbus_reset_channel_cb(struct vmbus_channel * channel)877 void vmbus_reset_channel_cb(struct vmbus_channel *channel)
878 {
879 	unsigned long flags;
880 
881 	/*
882 	 * vmbus_on_event(), running in the per-channel tasklet, can race
883 	 * with vmbus_close_internal() in the case of SMP guest, e.g., when
884 	 * the former is accessing channel->inbound.ring_buffer, the latter
885 	 * could be freeing the ring_buffer pages, so here we must stop it
886 	 * first.
887 	 *
888 	 * vmbus_chan_sched() might call the netvsc driver callback function
889 	 * that ends up scheduling NAPI work that accesses the ring buffer.
890 	 * At this point, we have to ensure that any such work is completed
891 	 * and that the channel ring buffer is no longer being accessed, cf.
892 	 * the calls to napi_disable() in netvsc_device_remove().
893 	 */
894 	tasklet_disable(&channel->callback_event);
895 
896 	/* See the inline comments in vmbus_chan_sched(). */
897 	spin_lock_irqsave(&channel->sched_lock, flags);
898 	channel->onchannel_callback = NULL;
899 	spin_unlock_irqrestore(&channel->sched_lock, flags);
900 
901 	channel->sc_creation_callback = NULL;
902 
903 	/* Re-enable tasklet for use on re-open */
904 	tasklet_enable(&channel->callback_event);
905 }
906 
vmbus_close_internal(struct vmbus_channel * channel)907 static int vmbus_close_internal(struct vmbus_channel *channel)
908 {
909 	struct vmbus_channel_close_channel *msg;
910 	int ret;
911 
912 	vmbus_reset_channel_cb(channel);
913 
914 	/*
915 	 * In case a device driver's probe() fails (e.g.,
916 	 * util_probe() -> vmbus_open() returns -ENOMEM) and the device is
917 	 * rescinded later (e.g., we dynamically disable an Integrated Service
918 	 * in Hyper-V Manager), the driver's remove() invokes vmbus_close():
919 	 * here we should skip most of the below cleanup work.
920 	 */
921 	if (channel->state != CHANNEL_OPENED_STATE)
922 		return -EINVAL;
923 
924 	channel->state = CHANNEL_OPEN_STATE;
925 
926 	/* Send a closing message */
927 
928 	msg = &channel->close_msg.msg;
929 
930 	msg->header.msgtype = CHANNELMSG_CLOSECHANNEL;
931 	msg->child_relid = channel->offermsg.child_relid;
932 
933 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_close_channel),
934 			     true);
935 
936 	trace_vmbus_close_internal(msg, ret);
937 
938 	if (ret) {
939 		pr_err("Close failed: close post msg return is %d\n", ret);
940 		/*
941 		 * If we failed to post the close msg,
942 		 * it is perhaps better to leak memory.
943 		 */
944 	}
945 
946 	/* Tear down the gpadl for the channel's ring buffer */
947 	else if (channel->ringbuffer_gpadlhandle.gpadl_handle) {
948 		ret = vmbus_teardown_gpadl(channel, &channel->ringbuffer_gpadlhandle);
949 		if (ret) {
950 			pr_err("Close failed: teardown gpadl return %d\n", ret);
951 			/*
952 			 * If we failed to teardown gpadl,
953 			 * it is perhaps better to leak memory.
954 			 */
955 		}
956 	}
957 
958 	if (!ret)
959 		vmbus_free_requestor(&channel->requestor);
960 
961 	return ret;
962 }
963 
964 /* disconnect ring - close all channels */
vmbus_disconnect_ring(struct vmbus_channel * channel)965 int vmbus_disconnect_ring(struct vmbus_channel *channel)
966 {
967 	struct vmbus_channel *cur_channel, *tmp;
968 	int ret;
969 
970 	if (channel->primary_channel != NULL)
971 		return -EINVAL;
972 
973 	list_for_each_entry_safe(cur_channel, tmp, &channel->sc_list, sc_list) {
974 		if (cur_channel->rescind)
975 			wait_for_completion(&cur_channel->rescind_event);
976 
977 		mutex_lock(&vmbus_connection.channel_mutex);
978 		if (vmbus_close_internal(cur_channel) == 0) {
979 			vmbus_free_ring(cur_channel);
980 
981 			if (cur_channel->rescind)
982 				hv_process_channel_removal(cur_channel);
983 		}
984 		mutex_unlock(&vmbus_connection.channel_mutex);
985 	}
986 
987 	/*
988 	 * Now close the primary.
989 	 */
990 	mutex_lock(&vmbus_connection.channel_mutex);
991 	ret = vmbus_close_internal(channel);
992 	mutex_unlock(&vmbus_connection.channel_mutex);
993 
994 	return ret;
995 }
996 EXPORT_SYMBOL_GPL(vmbus_disconnect_ring);
997 
998 /*
999  * vmbus_close - Close the specified channel
1000  */
vmbus_close(struct vmbus_channel * channel)1001 void vmbus_close(struct vmbus_channel *channel)
1002 {
1003 	if (vmbus_disconnect_ring(channel) == 0)
1004 		vmbus_free_ring(channel);
1005 }
1006 EXPORT_SYMBOL_GPL(vmbus_close);
1007 
1008 /**
1009  * vmbus_sendpacket_getid() - Send the specified buffer on the given channel
1010  * @channel: Pointer to vmbus_channel structure
1011  * @buffer: Pointer to the buffer you want to send the data from.
1012  * @bufferlen: Maximum size of what the buffer holds.
1013  * @requestid: Identifier of the request
1014  * @trans_id: Identifier of the transaction associated to this request, if
1015  *            the send is successful; undefined, otherwise.
1016  * @type: Type of packet that is being sent e.g. negotiate, time
1017  *	  packet etc.
1018  * @flags: 0 or VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED
1019  *
1020  * Sends data in @buffer directly to Hyper-V via the vmbus.
1021  * This will send the data unparsed to Hyper-V.
1022  *
1023  * Mainly used by Hyper-V drivers.
1024  */
vmbus_sendpacket_getid(struct vmbus_channel * channel,void * buffer,u32 bufferlen,u64 requestid,u64 * trans_id,enum vmbus_packet_type type,u32 flags)1025 int vmbus_sendpacket_getid(struct vmbus_channel *channel, void *buffer,
1026 			   u32 bufferlen, u64 requestid, u64 *trans_id,
1027 			   enum vmbus_packet_type type, u32 flags)
1028 {
1029 	struct vmpacket_descriptor desc;
1030 	u32 packetlen = sizeof(struct vmpacket_descriptor) + bufferlen;
1031 	u32 packetlen_aligned = ALIGN(packetlen, sizeof(u64));
1032 	struct kvec bufferlist[3];
1033 	u64 aligned_data = 0;
1034 	int num_vecs = ((bufferlen != 0) ? 3 : 1);
1035 
1036 
1037 	/* Setup the descriptor */
1038 	desc.type = type; /* VmbusPacketTypeDataInBand; */
1039 	desc.flags = flags; /* VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED; */
1040 	/* in 8-bytes granularity */
1041 	desc.offset8 = sizeof(struct vmpacket_descriptor) >> 3;
1042 	desc.len8 = (u16)(packetlen_aligned >> 3);
1043 	desc.trans_id = VMBUS_RQST_ERROR; /* will be updated in hv_ringbuffer_write() */
1044 
1045 	bufferlist[0].iov_base = &desc;
1046 	bufferlist[0].iov_len = sizeof(struct vmpacket_descriptor);
1047 	bufferlist[1].iov_base = buffer;
1048 	bufferlist[1].iov_len = bufferlen;
1049 	bufferlist[2].iov_base = &aligned_data;
1050 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
1051 
1052 	return hv_ringbuffer_write(channel, bufferlist, num_vecs, requestid, trans_id);
1053 }
1054 EXPORT_SYMBOL(vmbus_sendpacket_getid);
1055 
1056 /**
1057  * vmbus_sendpacket() - Send the specified buffer on the given channel
1058  * @channel: Pointer to vmbus_channel structure
1059  * @buffer: Pointer to the buffer you want to send the data from.
1060  * @bufferlen: Maximum size of what the buffer holds.
1061  * @requestid: Identifier of the request
1062  * @type: Type of packet that is being sent e.g. negotiate, time
1063  *	  packet etc.
1064  * @flags: 0 or VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED
1065  *
1066  * Sends data in @buffer directly to Hyper-V via the vmbus.
1067  * This will send the data unparsed to Hyper-V.
1068  *
1069  * Mainly used by Hyper-V drivers.
1070  */
vmbus_sendpacket(struct vmbus_channel * channel,void * buffer,u32 bufferlen,u64 requestid,enum vmbus_packet_type type,u32 flags)1071 int vmbus_sendpacket(struct vmbus_channel *channel, void *buffer,
1072 		     u32 bufferlen, u64 requestid,
1073 		     enum vmbus_packet_type type, u32 flags)
1074 {
1075 	return vmbus_sendpacket_getid(channel, buffer, bufferlen,
1076 				      requestid, NULL, type, flags);
1077 }
1078 EXPORT_SYMBOL(vmbus_sendpacket);
1079 
1080 /*
1081  * vmbus_sendpacket_mpb_desc - Send one or more multi-page buffer packets
1082  * using a GPADL Direct packet type.
1083  * The desc argument must include space for the VMBus descriptor. The
1084  * rangecount field must already be set.
1085  */
vmbus_sendpacket_mpb_desc(struct vmbus_channel * channel,struct vmbus_packet_mpb_array * desc,u32 desc_size,void * buffer,u32 bufferlen,u64 requestid)1086 int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,
1087 			      struct vmbus_packet_mpb_array *desc,
1088 			      u32 desc_size,
1089 			      void *buffer, u32 bufferlen, u64 requestid)
1090 {
1091 	u32 packetlen;
1092 	u32 packetlen_aligned;
1093 	struct kvec bufferlist[3];
1094 	u64 aligned_data = 0;
1095 
1096 	packetlen = desc_size + bufferlen;
1097 	packetlen_aligned = ALIGN(packetlen, sizeof(u64));
1098 
1099 	/* Setup the descriptor */
1100 	desc->type = VM_PKT_DATA_USING_GPA_DIRECT;
1101 	desc->flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
1102 	desc->dataoffset8 = desc_size >> 3; /* in 8-bytes granularity */
1103 	desc->length8 = (u16)(packetlen_aligned >> 3);
1104 	desc->transactionid = VMBUS_RQST_ERROR; /* will be updated in hv_ringbuffer_write() */
1105 	desc->reserved = 0;
1106 
1107 	bufferlist[0].iov_base = desc;
1108 	bufferlist[0].iov_len = desc_size;
1109 	bufferlist[1].iov_base = buffer;
1110 	bufferlist[1].iov_len = bufferlen;
1111 	bufferlist[2].iov_base = &aligned_data;
1112 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
1113 
1114 	return hv_ringbuffer_write(channel, bufferlist, 3, requestid, NULL);
1115 }
1116 EXPORT_SYMBOL_GPL(vmbus_sendpacket_mpb_desc);
1117 
1118 /**
1119  * __vmbus_recvpacket() - Retrieve the user packet on the specified channel
1120  * @channel: Pointer to vmbus_channel structure
1121  * @buffer: Pointer to the buffer you want to receive the data into.
1122  * @bufferlen: Maximum size of what the buffer can hold.
1123  * @buffer_actual_len: The actual size of the data after it was received.
1124  * @requestid: Identifier of the request
1125  * @raw: true means keep the vmpacket_descriptor header in the received data.
1126  *
1127  * Receives directly from the hyper-v vmbus and puts the data it received
1128  * into Buffer. This will receive the data unparsed from hyper-v.
1129  *
1130  * Mainly used by Hyper-V drivers.
1131  */
1132 static inline int
__vmbus_recvpacket(struct vmbus_channel * channel,void * buffer,u32 bufferlen,u32 * buffer_actual_len,u64 * requestid,bool raw)1133 __vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
1134 		   u32 bufferlen, u32 *buffer_actual_len, u64 *requestid,
1135 		   bool raw)
1136 {
1137 	return hv_ringbuffer_read(channel, buffer, bufferlen,
1138 				  buffer_actual_len, requestid, raw);
1139 
1140 }
1141 
vmbus_recvpacket(struct vmbus_channel * channel,void * buffer,u32 bufferlen,u32 * buffer_actual_len,u64 * requestid)1142 int vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
1143 		     u32 bufferlen, u32 *buffer_actual_len,
1144 		     u64 *requestid)
1145 {
1146 	return __vmbus_recvpacket(channel, buffer, bufferlen,
1147 				  buffer_actual_len, requestid, false);
1148 }
1149 EXPORT_SYMBOL(vmbus_recvpacket);
1150 
1151 /*
1152  * vmbus_recvpacket_raw - Retrieve the raw packet on the specified channel
1153  */
vmbus_recvpacket_raw(struct vmbus_channel * channel,void * buffer,u32 bufferlen,u32 * buffer_actual_len,u64 * requestid)1154 int vmbus_recvpacket_raw(struct vmbus_channel *channel, void *buffer,
1155 			      u32 bufferlen, u32 *buffer_actual_len,
1156 			      u64 *requestid)
1157 {
1158 	return __vmbus_recvpacket(channel, buffer, bufferlen,
1159 				  buffer_actual_len, requestid, true);
1160 }
1161 EXPORT_SYMBOL_GPL(vmbus_recvpacket_raw);
1162 
1163 /*
1164  * vmbus_next_request_id - Returns a new request id. It is also
1165  * the index at which the guest memory address is stored.
1166  * Uses a spin lock to avoid race conditions.
1167  * @channel: Pointer to the VMbus channel struct
1168  * @rqst_add: Guest memory address to be stored in the array
1169  */
vmbus_next_request_id(struct vmbus_channel * channel,u64 rqst_addr)1170 u64 vmbus_next_request_id(struct vmbus_channel *channel, u64 rqst_addr)
1171 {
1172 	struct vmbus_requestor *rqstor = &channel->requestor;
1173 	unsigned long flags;
1174 	u64 current_id;
1175 
1176 	/* Check rqstor has been initialized */
1177 	if (!channel->rqstor_size)
1178 		return VMBUS_NO_RQSTOR;
1179 
1180 	lock_requestor(channel, flags);
1181 	current_id = rqstor->next_request_id;
1182 
1183 	/* Requestor array is full */
1184 	if (current_id >= rqstor->size) {
1185 		unlock_requestor(channel, flags);
1186 		return VMBUS_RQST_ERROR;
1187 	}
1188 
1189 	rqstor->next_request_id = rqstor->req_arr[current_id];
1190 	rqstor->req_arr[current_id] = rqst_addr;
1191 
1192 	/* The already held spin lock provides atomicity */
1193 	bitmap_set(rqstor->req_bitmap, current_id, 1);
1194 
1195 	unlock_requestor(channel, flags);
1196 
1197 	/*
1198 	 * Cannot return an ID of 0, which is reserved for an unsolicited
1199 	 * message from Hyper-V; Hyper-V does not acknowledge (respond to)
1200 	 * VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED requests with ID of
1201 	 * 0 sent by the guest.
1202 	 */
1203 	return current_id + 1;
1204 }
1205 EXPORT_SYMBOL_GPL(vmbus_next_request_id);
1206 
1207 /* As in vmbus_request_addr_match() but without the requestor lock */
__vmbus_request_addr_match(struct vmbus_channel * channel,u64 trans_id,u64 rqst_addr)1208 u64 __vmbus_request_addr_match(struct vmbus_channel *channel, u64 trans_id,
1209 			       u64 rqst_addr)
1210 {
1211 	struct vmbus_requestor *rqstor = &channel->requestor;
1212 	u64 req_addr;
1213 
1214 	/* Check rqstor has been initialized */
1215 	if (!channel->rqstor_size)
1216 		return VMBUS_NO_RQSTOR;
1217 
1218 	/* Hyper-V can send an unsolicited message with ID of 0 */
1219 	if (!trans_id)
1220 		return VMBUS_RQST_ERROR;
1221 
1222 	/* Data corresponding to trans_id is stored at trans_id - 1 */
1223 	trans_id--;
1224 
1225 	/* Invalid trans_id */
1226 	if (trans_id >= rqstor->size || !test_bit(trans_id, rqstor->req_bitmap))
1227 		return VMBUS_RQST_ERROR;
1228 
1229 	req_addr = rqstor->req_arr[trans_id];
1230 	if (rqst_addr == VMBUS_RQST_ADDR_ANY || req_addr == rqst_addr) {
1231 		rqstor->req_arr[trans_id] = rqstor->next_request_id;
1232 		rqstor->next_request_id = trans_id;
1233 
1234 		/* The already held spin lock provides atomicity */
1235 		bitmap_clear(rqstor->req_bitmap, trans_id, 1);
1236 	}
1237 
1238 	return req_addr;
1239 }
1240 EXPORT_SYMBOL_GPL(__vmbus_request_addr_match);
1241 
1242 /*
1243  * vmbus_request_addr_match - Clears/removes @trans_id from the @channel's
1244  * requestor, provided the memory address stored at @trans_id equals @rqst_addr
1245  * (or provided @rqst_addr matches the sentinel value VMBUS_RQST_ADDR_ANY).
1246  *
1247  * Returns the memory address stored at @trans_id, or VMBUS_RQST_ERROR if
1248  * @trans_id is not contained in the requestor.
1249  *
1250  * Acquires and releases the requestor spin lock.
1251  */
vmbus_request_addr_match(struct vmbus_channel * channel,u64 trans_id,u64 rqst_addr)1252 u64 vmbus_request_addr_match(struct vmbus_channel *channel, u64 trans_id,
1253 			     u64 rqst_addr)
1254 {
1255 	unsigned long flags;
1256 	u64 req_addr;
1257 
1258 	lock_requestor(channel, flags);
1259 	req_addr = __vmbus_request_addr_match(channel, trans_id, rqst_addr);
1260 	unlock_requestor(channel, flags);
1261 
1262 	return req_addr;
1263 }
1264 EXPORT_SYMBOL_GPL(vmbus_request_addr_match);
1265 
1266 /*
1267  * vmbus_request_addr - Returns the memory address stored at @trans_id
1268  * in @rqstor. Uses a spin lock to avoid race conditions.
1269  * @channel: Pointer to the VMbus channel struct
1270  * @trans_id: Request id sent back from Hyper-V. Becomes the requestor's
1271  * next request id.
1272  */
vmbus_request_addr(struct vmbus_channel * channel,u64 trans_id)1273 u64 vmbus_request_addr(struct vmbus_channel *channel, u64 trans_id)
1274 {
1275 	return vmbus_request_addr_match(channel, trans_id, VMBUS_RQST_ADDR_ANY);
1276 }
1277 EXPORT_SYMBOL_GPL(vmbus_request_addr);
1278