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