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