xref: /linux/drivers/hv/channel.c (revision 90feea391c64fc43bf44184fcf2b243ab991ce47)
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_array(nr_pages, sizeof(*chunks),
698 				GFP_KERNEL | __GFP_ZERO);
699 	if (!chunks)
700 		goto err;
701 
702 	pages = kvmalloc_array(nr_pages, sizeof(*pages), GFP_KERNEL);
703 	if (!pages)
704 		goto err;
705 
706 	while (remaining) {
707 		struct page *page;
708 		gfp_t gfp;
709 
710 		order = min(order, ilog2(remaining));
711 
712 		/*
713 		 * Use __GFP_NORETRY | __GFP_NOWARN to avoid OOM-killing,
714 		 * but try harder at order 0 since that is the final
715 		 * fallback.
716 		 * __GFP_COMP stores order information in the page folio.
717 		 */
718 		gfp = GFP_KERNEL | __GFP_ZERO;
719 		if (order)
720 			gfp |= __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN;
721 
722 		page = alloc_pages_node(cpu_to_node(channel->target_cpu),
723 					gfp, order);
724 		if (!page) {
725 			if (!order--)
726 				goto err;
727 			continue;
728 		}
729 
730 		ret = set_memory_decrypted((unsigned long)page_address(page),
731 					   1U << order);
732 		if (ret) {
733 			/*
734 			 * set_memory_decrypted() failed; the page state is
735 			 * unknown so it must be leaked rather than freed.
736 			 */
737 			goto err;
738 		}
739 
740 		chunks[chunk_cnt++] = page;
741 
742 		for (i = 0; i < (1U << order); i++)
743 			pages[page_idx++] = page + i;
744 
745 		remaining -= 1U << order;
746 	}
747 
748 	addr = vmap(pages, nr_pages, VM_MAP, pgprot_decrypted(PAGE_KERNEL));
749 	if (!addr)
750 		goto err;
751 
752 	memset(addr, 0, nr_pages << PAGE_SHIFT);
753 
754 	kvfree(pages);
755 	*chunks_out = chunks;
756 	*chunk_cnt_out = chunk_cnt;
757 	return addr;
758 
759 err:
760 	kvfree(pages);
761 	vmbus_free_buffer(NULL, chunks, chunk_cnt);
762 	return NULL;
763 }
764 EXPORT_SYMBOL_GPL(vmbus_alloc_buffer);
765 
766 /**
767  * request_arr_init - Allocates memory for the requestor array. Each slot
768  * keeps track of the next available slot in the array. Initially, each
769  * slot points to the next one (as in a Linked List). The last slot
770  * does not point to anything, so its value is U64_MAX by default.
771  * @size: The size of the array
772  */
773 static u64 *request_arr_init(u32 size)
774 {
775 	int i;
776 	u64 *req_arr;
777 
778 	req_arr = kcalloc(size, sizeof(u64), GFP_KERNEL);
779 	if (!req_arr)
780 		return NULL;
781 
782 	for (i = 0; i < size - 1; i++)
783 		req_arr[i] = i + 1;
784 
785 	/* Last slot (no more available slots) */
786 	req_arr[i] = U64_MAX;
787 
788 	return req_arr;
789 }
790 
791 /*
792  * vmbus_alloc_requestor - Initializes @rqstor's fields.
793  * Index 0 is the first free slot
794  * @size: Size of the requestor array
795  */
796 static int vmbus_alloc_requestor(struct vmbus_requestor *rqstor, u32 size)
797 {
798 	u64 *rqst_arr;
799 	unsigned long *bitmap;
800 
801 	rqst_arr = request_arr_init(size);
802 	if (!rqst_arr)
803 		return -ENOMEM;
804 
805 	bitmap = bitmap_zalloc(size, GFP_KERNEL);
806 	if (!bitmap) {
807 		kfree(rqst_arr);
808 		return -ENOMEM;
809 	}
810 
811 	rqstor->req_arr = rqst_arr;
812 	rqstor->req_bitmap = bitmap;
813 	rqstor->size = size;
814 	rqstor->next_request_id = 0;
815 	spin_lock_init(&rqstor->req_lock);
816 
817 	return 0;
818 }
819 
820 /*
821  * vmbus_free_requestor - Frees memory allocated for @rqstor
822  * @rqstor: Pointer to the requestor struct
823  */
824 static void vmbus_free_requestor(struct vmbus_requestor *rqstor)
825 {
826 	kfree(rqstor->req_arr);
827 	bitmap_free(rqstor->req_bitmap);
828 }
829 
830 static int __vmbus_open(struct vmbus_channel *newchannel,
831 		       void *userdata, u32 userdatalen,
832 		       void (*onchannelcallback)(void *context), void *context)
833 {
834 	struct vmbus_channel_open_channel *open_msg;
835 	struct vmbus_channel_msginfo *open_info = NULL;
836 	struct page *page = newchannel->ringbuffer_page;
837 	u32 send_pages, recv_pages;
838 	unsigned long flags;
839 	int err;
840 
841 	if (userdatalen > MAX_USER_DEFINED_BYTES)
842 		return -EINVAL;
843 
844 	send_pages = newchannel->ringbuffer_send_offset;
845 	recv_pages = newchannel->ringbuffer_pagecount - send_pages;
846 
847 	if (newchannel->state != CHANNEL_OPEN_STATE)
848 		return -EINVAL;
849 
850 	/* Create and init requestor */
851 	if (newchannel->rqstor_size) {
852 		if (vmbus_alloc_requestor(&newchannel->requestor, newchannel->rqstor_size))
853 			return -ENOMEM;
854 	}
855 
856 	newchannel->state = CHANNEL_OPENING_STATE;
857 	newchannel->onchannel_callback = onchannelcallback;
858 	newchannel->channel_callback_context = context;
859 
860 	if (!newchannel->max_pkt_size)
861 		newchannel->max_pkt_size = VMBUS_DEFAULT_MAX_PKT_SIZE;
862 
863 	/* Establish the gpadl for the ring buffer */
864 	newchannel->ringbuffer_gpadlhandle.gpadl_handle = 0;
865 
866 	err = __vmbus_establish_gpadl(newchannel, HV_GPADL_RING,
867 				      page_address(newchannel->ringbuffer_page),
868 				      (send_pages + recv_pages) << PAGE_SHIFT,
869 				      newchannel->ringbuffer_send_offset << PAGE_SHIFT,
870 				      &newchannel->ringbuffer_gpadlhandle);
871 	if (err)
872 		goto error_clean_ring;
873 
874 	err = hv_ringbuffer_init(&newchannel->outbound,
875 				 page, send_pages, 0, newchannel->co_ring_buffer);
876 	if (err)
877 		goto error_free_gpadl;
878 
879 	err = hv_ringbuffer_init(&newchannel->inbound, &page[send_pages],
880 				 recv_pages, newchannel->max_pkt_size,
881 				 newchannel->co_ring_buffer);
882 	if (err)
883 		goto error_free_gpadl;
884 
885 	/* Create and init the channel open message */
886 	open_info = kzalloc(sizeof(*open_info) +
887 			   sizeof(struct vmbus_channel_open_channel),
888 			   GFP_KERNEL);
889 	if (!open_info) {
890 		err = -ENOMEM;
891 		goto error_free_gpadl;
892 	}
893 
894 	init_completion(&open_info->waitevent);
895 	open_info->waiting_channel = newchannel;
896 
897 	open_msg = (struct vmbus_channel_open_channel *)open_info->msg;
898 	open_msg->header.msgtype = CHANNELMSG_OPENCHANNEL;
899 	open_msg->openid = newchannel->offermsg.child_relid;
900 	open_msg->child_relid = newchannel->offermsg.child_relid;
901 	open_msg->ringbuffer_gpadlhandle
902 		= newchannel->ringbuffer_gpadlhandle.gpadl_handle;
903 	/*
904 	 * The unit of ->downstream_ringbuffer_pageoffset is HV_HYP_PAGE and
905 	 * the unit of ->ringbuffer_send_offset (i.e. send_pages) is PAGE, so
906 	 * here we calculate it into HV_HYP_PAGE.
907 	 */
908 	open_msg->downstream_ringbuffer_pageoffset =
909 		hv_ring_gpadl_send_hvpgoffset(send_pages << PAGE_SHIFT);
910 	open_msg->target_vp = hv_cpu_number_to_vp_number(newchannel->target_cpu);
911 
912 	if (userdatalen)
913 		memcpy(open_msg->userdata, userdata, userdatalen);
914 
915 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
916 	list_add_tail(&open_info->msglistentry,
917 		      &vmbus_connection.chn_msg_list);
918 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
919 
920 	if (newchannel->rescind) {
921 		err = -ENODEV;
922 		goto error_clean_msglist;
923 	}
924 
925 	err = vmbus_post_msg(open_msg,
926 			     sizeof(struct vmbus_channel_open_channel), true);
927 
928 	trace_vmbus_open(open_msg, err);
929 
930 	if (err != 0)
931 		goto error_clean_msglist;
932 
933 	wait_for_completion(&open_info->waitevent);
934 
935 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
936 	list_del(&open_info->msglistentry);
937 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
938 
939 	if (newchannel->rescind) {
940 		err = -ENODEV;
941 		goto error_free_info;
942 	}
943 
944 	if (open_info->response.open_result.status) {
945 		err = -EAGAIN;
946 		goto error_free_info;
947 	}
948 
949 	newchannel->state = CHANNEL_OPENED_STATE;
950 	kfree(open_info);
951 	return 0;
952 
953 error_clean_msglist:
954 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
955 	list_del(&open_info->msglistentry);
956 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
957 error_free_info:
958 	kfree(open_info);
959 error_free_gpadl:
960 	vmbus_teardown_gpadl(newchannel, &newchannel->ringbuffer_gpadlhandle);
961 error_clean_ring:
962 	hv_ringbuffer_cleanup(&newchannel->outbound);
963 	hv_ringbuffer_cleanup(&newchannel->inbound);
964 	vmbus_free_requestor(&newchannel->requestor);
965 	newchannel->state = CHANNEL_OPEN_STATE;
966 	return err;
967 }
968 
969 /*
970  * vmbus_connect_ring - Open the channel but reuse ring buffer
971  */
972 int vmbus_connect_ring(struct vmbus_channel *newchannel,
973 		       void (*onchannelcallback)(void *context), void *context)
974 {
975 	return  __vmbus_open(newchannel, NULL, 0, onchannelcallback, context);
976 }
977 EXPORT_SYMBOL_GPL(vmbus_connect_ring);
978 
979 /*
980  * vmbus_open - Open the specified channel.
981  */
982 int vmbus_open(struct vmbus_channel *newchannel,
983 	       u32 send_ringbuffer_size, u32 recv_ringbuffer_size,
984 	       void *userdata, u32 userdatalen,
985 	       void (*onchannelcallback)(void *context), void *context)
986 {
987 	int err;
988 
989 	err = vmbus_alloc_ring(newchannel, send_ringbuffer_size,
990 			       recv_ringbuffer_size);
991 	if (err)
992 		return err;
993 
994 	err = __vmbus_open(newchannel, userdata, userdatalen,
995 			   onchannelcallback, context);
996 	if (err)
997 		vmbus_free_ring(newchannel);
998 
999 	return err;
1000 }
1001 EXPORT_SYMBOL_GPL(vmbus_open);
1002 
1003 /*
1004  * vmbus_teardown_gpadl -Teardown the specified GPADL handle
1005  */
1006 int vmbus_teardown_gpadl(struct vmbus_channel *channel, struct vmbus_gpadl *gpadl)
1007 {
1008 	struct vmbus_channel_gpadl_teardown *msg;
1009 	struct vmbus_channel_msginfo *info;
1010 	unsigned long flags;
1011 	int ret;
1012 
1013 	info = kzalloc(sizeof(*info) +
1014 		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
1015 	if (!info)
1016 		return -ENOMEM;
1017 
1018 	init_completion(&info->waitevent);
1019 	info->waiting_channel = channel;
1020 
1021 	msg = (struct vmbus_channel_gpadl_teardown *)info->msg;
1022 
1023 	msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
1024 	msg->child_relid = channel->offermsg.child_relid;
1025 	msg->gpadl = gpadl->gpadl_handle;
1026 
1027 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1028 	list_add_tail(&info->msglistentry,
1029 		      &vmbus_connection.chn_msg_list);
1030 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1031 
1032 	if (channel->rescind)
1033 		goto post_msg_err;
1034 
1035 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),
1036 			     true);
1037 
1038 	trace_vmbus_teardown_gpadl(msg, ret);
1039 
1040 	if (ret)
1041 		goto post_msg_err;
1042 
1043 	wait_for_completion(&info->waitevent);
1044 
1045 	gpadl->gpadl_handle = 0;
1046 
1047 post_msg_err:
1048 	/*
1049 	 * If the channel has been rescinded;
1050 	 * we will be awakened by the rescind
1051 	 * handler; set the error code to zero so we don't leak memory.
1052 	 */
1053 	if (channel->rescind)
1054 		ret = 0;
1055 
1056 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
1057 	list_del(&info->msglistentry);
1058 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
1059 
1060 	kfree(info);
1061 
1062 	if (gpadl->decrypted)
1063 		ret = set_memory_encrypted((unsigned long)gpadl->buffer,
1064 					PFN_UP(gpadl->size));
1065 	else
1066 		ret = 0;
1067 	if (ret)
1068 		pr_warn("Fail to set mem host visibility in GPADL teardown %d.\n", ret);
1069 
1070 	gpadl->decrypted = ret;
1071 
1072 	return ret;
1073 }
1074 EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl);
1075 
1076 void vmbus_reset_channel_cb(struct vmbus_channel *channel)
1077 {
1078 	unsigned long flags;
1079 
1080 	/*
1081 	 * vmbus_on_event(), running in the per-channel tasklet, can race
1082 	 * with vmbus_close_internal() in the case of SMP guest, e.g., when
1083 	 * the former is accessing channel->inbound.ring_buffer, the latter
1084 	 * could be freeing the ring_buffer pages, so here we must stop it
1085 	 * first.
1086 	 *
1087 	 * vmbus_chan_sched() might call the netvsc driver callback function
1088 	 * that ends up scheduling NAPI work that accesses the ring buffer.
1089 	 * At this point, we have to ensure that any such work is completed
1090 	 * and that the channel ring buffer is no longer being accessed, cf.
1091 	 * the calls to napi_disable() in netvsc_device_remove().
1092 	 */
1093 	tasklet_disable(&channel->callback_event);
1094 
1095 	/* See the inline comments in vmbus_chan_sched(). */
1096 	spin_lock_irqsave(&channel->sched_lock, flags);
1097 	channel->onchannel_callback = NULL;
1098 	spin_unlock_irqrestore(&channel->sched_lock, flags);
1099 
1100 	channel->sc_creation_callback = NULL;
1101 
1102 	/* Re-enable tasklet for use on re-open */
1103 	tasklet_enable(&channel->callback_event);
1104 }
1105 
1106 static int vmbus_close_internal(struct vmbus_channel *channel)
1107 {
1108 	struct vmbus_channel_close_channel *msg;
1109 	int ret;
1110 
1111 	vmbus_reset_channel_cb(channel);
1112 
1113 	/*
1114 	 * In case a device driver's probe() fails (e.g.,
1115 	 * util_probe() -> vmbus_open() returns -ENOMEM) and the device is
1116 	 * rescinded later (e.g., we dynamically disable an Integrated Service
1117 	 * in Hyper-V Manager), the driver's remove() invokes vmbus_close():
1118 	 * here we should skip most of the below cleanup work.
1119 	 */
1120 	if (channel->state != CHANNEL_OPENED_STATE)
1121 		return -EINVAL;
1122 
1123 	channel->state = CHANNEL_OPEN_STATE;
1124 
1125 	/* Send a closing message */
1126 
1127 	msg = &channel->close_msg;
1128 
1129 	msg->header.msgtype = CHANNELMSG_CLOSECHANNEL;
1130 	msg->child_relid = channel->offermsg.child_relid;
1131 
1132 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_close_channel),
1133 			     true);
1134 
1135 	trace_vmbus_close_internal(msg, ret);
1136 
1137 	if (ret) {
1138 		pr_err("Close failed: close post msg return is %d\n", ret);
1139 		/*
1140 		 * If we failed to post the close msg,
1141 		 * it is perhaps better to leak memory.
1142 		 */
1143 	}
1144 
1145 	/* Tear down the gpadl for the channel's ring buffer */
1146 	else if (channel->ringbuffer_gpadlhandle.gpadl_handle) {
1147 		ret = vmbus_teardown_gpadl(channel, &channel->ringbuffer_gpadlhandle);
1148 		if (ret) {
1149 			pr_err("Close failed: teardown gpadl return %d\n", ret);
1150 			/*
1151 			 * If we failed to teardown gpadl,
1152 			 * it is perhaps better to leak memory.
1153 			 */
1154 		}
1155 	}
1156 
1157 	if (!ret)
1158 		vmbus_free_requestor(&channel->requestor);
1159 
1160 	return ret;
1161 }
1162 
1163 /* disconnect ring - close all channels */
1164 int vmbus_disconnect_ring(struct vmbus_channel *channel)
1165 {
1166 	struct vmbus_channel *cur_channel, *tmp;
1167 	int ret;
1168 
1169 	if (channel->primary_channel != NULL)
1170 		return -EINVAL;
1171 
1172 	list_for_each_entry_safe(cur_channel, tmp, &channel->sc_list, sc_list) {
1173 		if (cur_channel->rescind)
1174 			wait_for_completion(&cur_channel->rescind_event);
1175 
1176 		mutex_lock(&vmbus_connection.channel_mutex);
1177 		if (vmbus_close_internal(cur_channel) == 0) {
1178 			vmbus_free_ring(cur_channel);
1179 
1180 			if (cur_channel->rescind)
1181 				hv_process_channel_removal(cur_channel);
1182 		}
1183 		mutex_unlock(&vmbus_connection.channel_mutex);
1184 	}
1185 
1186 	/*
1187 	 * Now close the primary.
1188 	 */
1189 	mutex_lock(&vmbus_connection.channel_mutex);
1190 	ret = vmbus_close_internal(channel);
1191 	mutex_unlock(&vmbus_connection.channel_mutex);
1192 
1193 	return ret;
1194 }
1195 EXPORT_SYMBOL_GPL(vmbus_disconnect_ring);
1196 
1197 /*
1198  * vmbus_close - Close the specified channel
1199  */
1200 void vmbus_close(struct vmbus_channel *channel)
1201 {
1202 	if (vmbus_disconnect_ring(channel) == 0)
1203 		vmbus_free_ring(channel);
1204 }
1205 EXPORT_SYMBOL_GPL(vmbus_close);
1206 
1207 /**
1208  * vmbus_sendpacket_getid() - Send the specified buffer on the given channel
1209  * @channel: Pointer to vmbus_channel structure
1210  * @buffer: Pointer to the buffer you want to send the data from.
1211  * @bufferlen: Maximum size of what the buffer holds.
1212  * @requestid: Identifier of the request
1213  * @trans_id: Identifier of the transaction associated to this request, if
1214  *            the send is successful; undefined, otherwise.
1215  * @type: Type of packet that is being sent e.g. negotiate, time
1216  *	  packet etc.
1217  * @flags: 0 or VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED
1218  *
1219  * Sends data in @buffer directly to Hyper-V via the vmbus.
1220  * This will send the data unparsed to Hyper-V.
1221  *
1222  * Mainly used by Hyper-V drivers.
1223  */
1224 int vmbus_sendpacket_getid(struct vmbus_channel *channel, void *buffer,
1225 			   u32 bufferlen, u64 requestid, u64 *trans_id,
1226 			   enum vmbus_packet_type type, u32 flags)
1227 {
1228 	struct vmpacket_descriptor desc;
1229 	u32 packetlen = sizeof(struct vmpacket_descriptor) + bufferlen;
1230 	u32 packetlen_aligned = ALIGN(packetlen, sizeof(u64));
1231 	struct kvec bufferlist[3];
1232 	u64 aligned_data = 0;
1233 	int num_vecs = ((bufferlen != 0) ? 3 : 1);
1234 
1235 
1236 	/* Setup the descriptor */
1237 	desc.type = type; /* VmbusPacketTypeDataInBand; */
1238 	desc.flags = flags; /* VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED; */
1239 	/* in 8-bytes granularity */
1240 	desc.offset8 = sizeof(struct vmpacket_descriptor) >> 3;
1241 	desc.len8 = (u16)(packetlen_aligned >> 3);
1242 	desc.trans_id = VMBUS_RQST_ERROR; /* will be updated in hv_ringbuffer_write() */
1243 
1244 	bufferlist[0].iov_base = &desc;
1245 	bufferlist[0].iov_len = sizeof(struct vmpacket_descriptor);
1246 	bufferlist[1].iov_base = buffer;
1247 	bufferlist[1].iov_len = bufferlen;
1248 	bufferlist[2].iov_base = &aligned_data;
1249 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
1250 
1251 	return hv_ringbuffer_write(channel, bufferlist, num_vecs, requestid, trans_id);
1252 }
1253 EXPORT_SYMBOL(vmbus_sendpacket_getid);
1254 
1255 /**
1256  * vmbus_sendpacket() - Send the specified buffer on the given channel
1257  * @channel: Pointer to vmbus_channel structure
1258  * @buffer: Pointer to the buffer you want to send the data from.
1259  * @bufferlen: Maximum size of what the buffer holds.
1260  * @requestid: Identifier of the request
1261  * @type: Type of packet that is being sent e.g. negotiate, time
1262  *	  packet etc.
1263  * @flags: 0 or VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED
1264  *
1265  * Sends data in @buffer directly to Hyper-V via the vmbus.
1266  * This will send the data unparsed to Hyper-V.
1267  *
1268  * Mainly used by Hyper-V drivers.
1269  */
1270 int vmbus_sendpacket(struct vmbus_channel *channel, void *buffer,
1271 		     u32 bufferlen, u64 requestid,
1272 		     enum vmbus_packet_type type, u32 flags)
1273 {
1274 	return vmbus_sendpacket_getid(channel, buffer, bufferlen,
1275 				      requestid, NULL, type, flags);
1276 }
1277 EXPORT_SYMBOL(vmbus_sendpacket);
1278 
1279 /*
1280  * vmbus_sendpacket_mpb_desc - Send one or more multi-page buffer packets
1281  * using a GPADL Direct packet type.
1282  * The desc argument must include space for the VMBus descriptor. The
1283  * rangecount field must already be set.
1284  */
1285 int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,
1286 			      struct vmbus_packet_mpb_array *desc,
1287 			      u32 desc_size,
1288 			      void *buffer, u32 bufferlen, u64 requestid)
1289 {
1290 	u32 packetlen;
1291 	u32 packetlen_aligned;
1292 	struct kvec bufferlist[3];
1293 	u64 aligned_data = 0;
1294 
1295 	packetlen = desc_size + bufferlen;
1296 	packetlen_aligned = ALIGN(packetlen, sizeof(u64));
1297 
1298 	/* Setup the descriptor */
1299 	desc->type = VM_PKT_DATA_USING_GPA_DIRECT;
1300 	desc->flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
1301 	desc->dataoffset8 = desc_size >> 3; /* in 8-bytes granularity */
1302 	desc->length8 = (u16)(packetlen_aligned >> 3);
1303 	desc->transactionid = VMBUS_RQST_ERROR; /* will be updated in hv_ringbuffer_write() */
1304 	desc->reserved = 0;
1305 
1306 	bufferlist[0].iov_base = desc;
1307 	bufferlist[0].iov_len = desc_size;
1308 	bufferlist[1].iov_base = buffer;
1309 	bufferlist[1].iov_len = bufferlen;
1310 	bufferlist[2].iov_base = &aligned_data;
1311 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
1312 
1313 	return hv_ringbuffer_write(channel, bufferlist, 3, requestid, NULL);
1314 }
1315 EXPORT_SYMBOL_GPL(vmbus_sendpacket_mpb_desc);
1316 
1317 /**
1318  * __vmbus_recvpacket() - Retrieve the user packet on the specified channel
1319  * @channel: Pointer to vmbus_channel structure
1320  * @buffer: Pointer to the buffer you want to receive the data into.
1321  * @bufferlen: Maximum size of what the buffer can hold.
1322  * @buffer_actual_len: The actual size of the data after it was received.
1323  * @requestid: Identifier of the request
1324  * @raw: true means keep the vmpacket_descriptor header in the received data.
1325  *
1326  * Receives directly from the hyper-v vmbus and puts the data it received
1327  * into Buffer. This will receive the data unparsed from hyper-v.
1328  *
1329  * Mainly used by Hyper-V drivers.
1330  */
1331 static inline int
1332 __vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
1333 		   u32 bufferlen, u32 *buffer_actual_len, u64 *requestid,
1334 		   bool raw)
1335 {
1336 	return hv_ringbuffer_read(channel, buffer, bufferlen,
1337 				  buffer_actual_len, requestid, raw);
1338 
1339 }
1340 
1341 int vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
1342 		     u32 bufferlen, u32 *buffer_actual_len,
1343 		     u64 *requestid)
1344 {
1345 	return __vmbus_recvpacket(channel, buffer, bufferlen,
1346 				  buffer_actual_len, requestid, false);
1347 }
1348 EXPORT_SYMBOL(vmbus_recvpacket);
1349 
1350 /*
1351  * vmbus_recvpacket_raw - Retrieve the raw packet on the specified channel
1352  */
1353 int vmbus_recvpacket_raw(struct vmbus_channel *channel, void *buffer,
1354 			      u32 bufferlen, u32 *buffer_actual_len,
1355 			      u64 *requestid)
1356 {
1357 	return __vmbus_recvpacket(channel, buffer, bufferlen,
1358 				  buffer_actual_len, requestid, true);
1359 }
1360 EXPORT_SYMBOL_GPL(vmbus_recvpacket_raw);
1361 
1362 /*
1363  * vmbus_next_request_id - Returns a new request id. It is also
1364  * the index at which the guest memory address is stored.
1365  * Uses a spin lock to avoid race conditions.
1366  * @channel: Pointer to the VMbus channel struct
1367  * @rqst_add: Guest memory address to be stored in the array
1368  */
1369 u64 vmbus_next_request_id(struct vmbus_channel *channel, u64 rqst_addr)
1370 {
1371 	struct vmbus_requestor *rqstor = &channel->requestor;
1372 	unsigned long flags;
1373 	u64 current_id;
1374 
1375 	/* Check rqstor has been initialized */
1376 	if (!channel->rqstor_size)
1377 		return VMBUS_NO_RQSTOR;
1378 
1379 	lock_requestor(channel, flags);
1380 	current_id = rqstor->next_request_id;
1381 
1382 	/* Requestor array is full */
1383 	if (current_id >= rqstor->size) {
1384 		unlock_requestor(channel, flags);
1385 		return VMBUS_RQST_ERROR;
1386 	}
1387 
1388 	rqstor->next_request_id = rqstor->req_arr[current_id];
1389 	rqstor->req_arr[current_id] = rqst_addr;
1390 
1391 	/* The already held spin lock provides atomicity */
1392 	bitmap_set(rqstor->req_bitmap, current_id, 1);
1393 
1394 	unlock_requestor(channel, flags);
1395 
1396 	/*
1397 	 * Cannot return an ID of 0, which is reserved for an unsolicited
1398 	 * message from Hyper-V; Hyper-V does not acknowledge (respond to)
1399 	 * VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED requests with ID of
1400 	 * 0 sent by the guest.
1401 	 */
1402 	return current_id + 1;
1403 }
1404 EXPORT_SYMBOL_GPL(vmbus_next_request_id);
1405 
1406 /* As in vmbus_request_addr_match() but without the requestor lock */
1407 u64 __vmbus_request_addr_match(struct vmbus_channel *channel, u64 trans_id,
1408 			       u64 rqst_addr)
1409 {
1410 	struct vmbus_requestor *rqstor = &channel->requestor;
1411 	u64 req_addr;
1412 
1413 	/* Check rqstor has been initialized */
1414 	if (!channel->rqstor_size)
1415 		return VMBUS_NO_RQSTOR;
1416 
1417 	/* Hyper-V can send an unsolicited message with ID of 0 */
1418 	if (!trans_id)
1419 		return VMBUS_RQST_ERROR;
1420 
1421 	/* Data corresponding to trans_id is stored at trans_id - 1 */
1422 	trans_id--;
1423 
1424 	/* Invalid trans_id */
1425 	if (trans_id >= rqstor->size || !test_bit(trans_id, rqstor->req_bitmap))
1426 		return VMBUS_RQST_ERROR;
1427 
1428 	req_addr = rqstor->req_arr[trans_id];
1429 	if (rqst_addr == VMBUS_RQST_ADDR_ANY || req_addr == rqst_addr) {
1430 		rqstor->req_arr[trans_id] = rqstor->next_request_id;
1431 		rqstor->next_request_id = trans_id;
1432 
1433 		/* The already held spin lock provides atomicity */
1434 		bitmap_clear(rqstor->req_bitmap, trans_id, 1);
1435 	}
1436 
1437 	return req_addr;
1438 }
1439 EXPORT_SYMBOL_GPL(__vmbus_request_addr_match);
1440 
1441 /*
1442  * vmbus_request_addr_match - Clears/removes @trans_id from the @channel's
1443  * requestor, provided the memory address stored at @trans_id equals @rqst_addr
1444  * (or provided @rqst_addr matches the sentinel value VMBUS_RQST_ADDR_ANY).
1445  *
1446  * Returns the memory address stored at @trans_id, or VMBUS_RQST_ERROR if
1447  * @trans_id is not contained in the requestor.
1448  *
1449  * Acquires and releases the requestor spin lock.
1450  */
1451 u64 vmbus_request_addr_match(struct vmbus_channel *channel, u64 trans_id,
1452 			     u64 rqst_addr)
1453 {
1454 	unsigned long flags;
1455 	u64 req_addr;
1456 
1457 	lock_requestor(channel, flags);
1458 	req_addr = __vmbus_request_addr_match(channel, trans_id, rqst_addr);
1459 	unlock_requestor(channel, flags);
1460 
1461 	return req_addr;
1462 }
1463 EXPORT_SYMBOL_GPL(vmbus_request_addr_match);
1464 
1465 /*
1466  * vmbus_request_addr - Returns the memory address stored at @trans_id
1467  * in @rqstor. Uses a spin lock to avoid race conditions.
1468  * @channel: Pointer to the VMbus channel struct
1469  * @trans_id: Request id sent back from Hyper-V. Becomes the requestor's
1470  * next request id.
1471  */
1472 u64 vmbus_request_addr(struct vmbus_channel *channel, u64 trans_id)
1473 {
1474 	return vmbus_request_addr_match(channel, trans_id, VMBUS_RQST_ADDR_ANY);
1475 }
1476 EXPORT_SYMBOL_GPL(vmbus_request_addr);
1477