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