xref: /openbmc/linux/drivers/hv/channel.c (revision 51f6b410)
1 /*
2  * Copyright (c) 2009, Microsoft Corporation.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Authors:
18  *   Haiyang Zhang <haiyangz@microsoft.com>
19  *   Hank Janssen  <hjanssen@microsoft.com>
20  */
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22 
23 #include <linux/kernel.h>
24 #include <linux/sched.h>
25 #include <linux/wait.h>
26 #include <linux/mm.h>
27 #include <linux/slab.h>
28 #include <linux/module.h>
29 #include <linux/hyperv.h>
30 #include <linux/uio.h>
31 #include <linux/interrupt.h>
32 #include <asm/page.h>
33 
34 #include "hyperv_vmbus.h"
35 
36 #define NUM_PAGES_SPANNED(addr, len) \
37 ((PAGE_ALIGN(addr + len) >> PAGE_SHIFT) - (addr >> PAGE_SHIFT))
38 
39 static unsigned long virt_to_hvpfn(void *addr)
40 {
41 	unsigned long paddr;
42 
43 	if (is_vmalloc_addr(addr))
44 		paddr = page_to_phys(vmalloc_to_page(addr)) +
45 					 offset_in_page(addr);
46 	else
47 		paddr = __pa(addr);
48 
49 	return  paddr >> PAGE_SHIFT;
50 }
51 
52 /*
53  * vmbus_setevent- Trigger an event notification on the specified
54  * channel.
55  */
56 void vmbus_setevent(struct vmbus_channel *channel)
57 {
58 	struct hv_monitor_page *monitorpage;
59 
60 	trace_vmbus_setevent(channel);
61 
62 	/*
63 	 * For channels marked as in "low latency" mode
64 	 * bypass the monitor page mechanism.
65 	 */
66 	if (channel->offermsg.monitor_allocated && !channel->low_latency) {
67 		vmbus_send_interrupt(channel->offermsg.child_relid);
68 
69 		/* Get the child to parent monitor page */
70 		monitorpage = vmbus_connection.monitor_pages[1];
71 
72 		sync_set_bit(channel->monitor_bit,
73 			(unsigned long *)&monitorpage->trigger_group
74 					[channel->monitor_grp].pending);
75 
76 	} else {
77 		vmbus_set_event(channel);
78 	}
79 }
80 EXPORT_SYMBOL_GPL(vmbus_setevent);
81 
82 /*
83  * vmbus_open - Open the specified channel.
84  */
85 int vmbus_open(struct vmbus_channel *newchannel, u32 send_ringbuffer_size,
86 		     u32 recv_ringbuffer_size, void *userdata, u32 userdatalen,
87 		     void (*onchannelcallback)(void *context), void *context)
88 {
89 	struct vmbus_channel_open_channel *open_msg;
90 	struct vmbus_channel_msginfo *open_info = NULL;
91 	unsigned long flags;
92 	int ret, err = 0;
93 	struct page *page;
94 
95 	if (send_ringbuffer_size % PAGE_SIZE ||
96 	    recv_ringbuffer_size % PAGE_SIZE)
97 		return -EINVAL;
98 
99 	spin_lock_irqsave(&newchannel->lock, flags);
100 	if (newchannel->state == CHANNEL_OPEN_STATE) {
101 		newchannel->state = CHANNEL_OPENING_STATE;
102 	} else {
103 		spin_unlock_irqrestore(&newchannel->lock, flags);
104 		return -EINVAL;
105 	}
106 	spin_unlock_irqrestore(&newchannel->lock, flags);
107 
108 	newchannel->onchannel_callback = onchannelcallback;
109 	newchannel->channel_callback_context = context;
110 
111 	/* Allocate the ring buffer */
112 	page = alloc_pages_node(cpu_to_node(newchannel->target_cpu),
113 				GFP_KERNEL|__GFP_ZERO,
114 				get_order(send_ringbuffer_size +
115 				recv_ringbuffer_size));
116 
117 	if (!page)
118 		page = alloc_pages(GFP_KERNEL|__GFP_ZERO,
119 				   get_order(send_ringbuffer_size +
120 					     recv_ringbuffer_size));
121 
122 	if (!page) {
123 		err = -ENOMEM;
124 		goto error_set_chnstate;
125 	}
126 
127 	newchannel->ringbuffer_pages = page_address(page);
128 	newchannel->ringbuffer_pagecount = (send_ringbuffer_size +
129 					   recv_ringbuffer_size) >> PAGE_SHIFT;
130 
131 	ret = hv_ringbuffer_init(&newchannel->outbound, page,
132 				 send_ringbuffer_size >> PAGE_SHIFT);
133 
134 	if (ret != 0) {
135 		err = ret;
136 		goto error_free_pages;
137 	}
138 
139 	ret = hv_ringbuffer_init(&newchannel->inbound,
140 				 &page[send_ringbuffer_size >> PAGE_SHIFT],
141 				 recv_ringbuffer_size >> PAGE_SHIFT);
142 	if (ret != 0) {
143 		err = ret;
144 		goto error_free_pages;
145 	}
146 
147 
148 	/* Establish the gpadl for the ring buffer */
149 	newchannel->ringbuffer_gpadlhandle = 0;
150 
151 	ret = vmbus_establish_gpadl(newchannel,
152 				    page_address(page),
153 				    send_ringbuffer_size +
154 				    recv_ringbuffer_size,
155 				    &newchannel->ringbuffer_gpadlhandle);
156 
157 	if (ret != 0) {
158 		err = ret;
159 		goto error_free_pages;
160 	}
161 
162 	/* Create and init the channel open message */
163 	open_info = kmalloc(sizeof(*open_info) +
164 			   sizeof(struct vmbus_channel_open_channel),
165 			   GFP_KERNEL);
166 	if (!open_info) {
167 		err = -ENOMEM;
168 		goto error_free_gpadl;
169 	}
170 
171 	init_completion(&open_info->waitevent);
172 	open_info->waiting_channel = newchannel;
173 
174 	open_msg = (struct vmbus_channel_open_channel *)open_info->msg;
175 	open_msg->header.msgtype = CHANNELMSG_OPENCHANNEL;
176 	open_msg->openid = newchannel->offermsg.child_relid;
177 	open_msg->child_relid = newchannel->offermsg.child_relid;
178 	open_msg->ringbuffer_gpadlhandle = newchannel->ringbuffer_gpadlhandle;
179 	open_msg->downstream_ringbuffer_pageoffset = send_ringbuffer_size >>
180 						  PAGE_SHIFT;
181 	open_msg->target_vp = newchannel->target_vp;
182 
183 	if (userdatalen > MAX_USER_DEFINED_BYTES) {
184 		err = -EINVAL;
185 		goto error_free_gpadl;
186 	}
187 
188 	if (userdatalen)
189 		memcpy(open_msg->userdata, userdata, userdatalen);
190 
191 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
192 	list_add_tail(&open_info->msglistentry,
193 		      &vmbus_connection.chn_msg_list);
194 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
195 
196 	if (newchannel->rescind) {
197 		err = -ENODEV;
198 		goto error_free_gpadl;
199 	}
200 
201 	ret = vmbus_post_msg(open_msg,
202 			     sizeof(struct vmbus_channel_open_channel), true);
203 
204 	trace_vmbus_open(open_msg, ret);
205 
206 	if (ret != 0) {
207 		err = ret;
208 		goto error_clean_msglist;
209 	}
210 
211 	wait_for_completion(&open_info->waitevent);
212 
213 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
214 	list_del(&open_info->msglistentry);
215 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
216 
217 	if (newchannel->rescind) {
218 		err = -ENODEV;
219 		goto error_free_gpadl;
220 	}
221 
222 	if (open_info->response.open_result.status) {
223 		err = -EAGAIN;
224 		goto error_free_gpadl;
225 	}
226 
227 	newchannel->state = CHANNEL_OPENED_STATE;
228 	kfree(open_info);
229 	return 0;
230 
231 error_clean_msglist:
232 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
233 	list_del(&open_info->msglistentry);
234 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
235 
236 error_free_gpadl:
237 	vmbus_teardown_gpadl(newchannel, newchannel->ringbuffer_gpadlhandle);
238 	kfree(open_info);
239 error_free_pages:
240 	hv_ringbuffer_cleanup(&newchannel->outbound);
241 	hv_ringbuffer_cleanup(&newchannel->inbound);
242 	__free_pages(page,
243 		     get_order(send_ringbuffer_size + recv_ringbuffer_size));
244 error_set_chnstate:
245 	newchannel->state = CHANNEL_OPEN_STATE;
246 	return err;
247 }
248 EXPORT_SYMBOL_GPL(vmbus_open);
249 
250 /* Used for Hyper-V Socket: a guest client's connect() to the host */
251 int vmbus_send_tl_connect_request(const uuid_le *shv_guest_servie_id,
252 				  const uuid_le *shv_host_servie_id)
253 {
254 	struct vmbus_channel_tl_connect_request conn_msg;
255 	int ret;
256 
257 	memset(&conn_msg, 0, sizeof(conn_msg));
258 	conn_msg.header.msgtype = CHANNELMSG_TL_CONNECT_REQUEST;
259 	conn_msg.guest_endpoint_id = *shv_guest_servie_id;
260 	conn_msg.host_service_id = *shv_host_servie_id;
261 
262 	ret = vmbus_post_msg(&conn_msg, sizeof(conn_msg), true);
263 
264 	trace_vmbus_send_tl_connect_request(&conn_msg, ret);
265 
266 	return ret;
267 }
268 EXPORT_SYMBOL_GPL(vmbus_send_tl_connect_request);
269 
270 /*
271  * create_gpadl_header - Creates a gpadl for the specified buffer
272  */
273 static int create_gpadl_header(void *kbuffer, u32 size,
274 			       struct vmbus_channel_msginfo **msginfo)
275 {
276 	int i;
277 	int pagecount;
278 	struct vmbus_channel_gpadl_header *gpadl_header;
279 	struct vmbus_channel_gpadl_body *gpadl_body;
280 	struct vmbus_channel_msginfo *msgheader;
281 	struct vmbus_channel_msginfo *msgbody = NULL;
282 	u32 msgsize;
283 
284 	int pfnsum, pfncount, pfnleft, pfncurr, pfnsize;
285 
286 	pagecount = size >> PAGE_SHIFT;
287 
288 	/* do we need a gpadl body msg */
289 	pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
290 		  sizeof(struct vmbus_channel_gpadl_header) -
291 		  sizeof(struct gpa_range);
292 	pfncount = pfnsize / sizeof(u64);
293 
294 	if (pagecount > pfncount) {
295 		/* we need a gpadl body */
296 		/* fill in the header */
297 		msgsize = sizeof(struct vmbus_channel_msginfo) +
298 			  sizeof(struct vmbus_channel_gpadl_header) +
299 			  sizeof(struct gpa_range) + pfncount * sizeof(u64);
300 		msgheader =  kzalloc(msgsize, GFP_KERNEL);
301 		if (!msgheader)
302 			goto nomem;
303 
304 		INIT_LIST_HEAD(&msgheader->submsglist);
305 		msgheader->msgsize = msgsize;
306 
307 		gpadl_header = (struct vmbus_channel_gpadl_header *)
308 			msgheader->msg;
309 		gpadl_header->rangecount = 1;
310 		gpadl_header->range_buflen = sizeof(struct gpa_range) +
311 					 pagecount * sizeof(u64);
312 		gpadl_header->range[0].byte_offset = 0;
313 		gpadl_header->range[0].byte_count = size;
314 		for (i = 0; i < pfncount; i++)
315 			gpadl_header->range[0].pfn_array[i] = virt_to_hvpfn(
316 				kbuffer + PAGE_SIZE * i);
317 		*msginfo = msgheader;
318 
319 		pfnsum = pfncount;
320 		pfnleft = pagecount - pfncount;
321 
322 		/* how many pfns can we fit */
323 		pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
324 			  sizeof(struct vmbus_channel_gpadl_body);
325 		pfncount = pfnsize / sizeof(u64);
326 
327 		/* fill in the body */
328 		while (pfnleft) {
329 			if (pfnleft > pfncount)
330 				pfncurr = pfncount;
331 			else
332 				pfncurr = pfnleft;
333 
334 			msgsize = sizeof(struct vmbus_channel_msginfo) +
335 				  sizeof(struct vmbus_channel_gpadl_body) +
336 				  pfncurr * sizeof(u64);
337 			msgbody = kzalloc(msgsize, GFP_KERNEL);
338 
339 			if (!msgbody) {
340 				struct vmbus_channel_msginfo *pos = NULL;
341 				struct vmbus_channel_msginfo *tmp = NULL;
342 				/*
343 				 * Free up all the allocated messages.
344 				 */
345 				list_for_each_entry_safe(pos, tmp,
346 					&msgheader->submsglist,
347 					msglistentry) {
348 
349 					list_del(&pos->msglistentry);
350 					kfree(pos);
351 				}
352 
353 				goto nomem;
354 			}
355 
356 			msgbody->msgsize = msgsize;
357 			gpadl_body =
358 				(struct vmbus_channel_gpadl_body *)msgbody->msg;
359 
360 			/*
361 			 * Gpadl is u32 and we are using a pointer which could
362 			 * be 64-bit
363 			 * This is governed by the guest/host protocol and
364 			 * so the hypervisor guarantees that this is ok.
365 			 */
366 			for (i = 0; i < pfncurr; i++)
367 				gpadl_body->pfn[i] = virt_to_hvpfn(
368 					kbuffer + PAGE_SIZE * (pfnsum + i));
369 
370 			/* add to msg header */
371 			list_add_tail(&msgbody->msglistentry,
372 				      &msgheader->submsglist);
373 			pfnsum += pfncurr;
374 			pfnleft -= pfncurr;
375 		}
376 	} else {
377 		/* everything fits in a header */
378 		msgsize = sizeof(struct vmbus_channel_msginfo) +
379 			  sizeof(struct vmbus_channel_gpadl_header) +
380 			  sizeof(struct gpa_range) + pagecount * sizeof(u64);
381 		msgheader = kzalloc(msgsize, GFP_KERNEL);
382 		if (msgheader == NULL)
383 			goto nomem;
384 
385 		INIT_LIST_HEAD(&msgheader->submsglist);
386 		msgheader->msgsize = msgsize;
387 
388 		gpadl_header = (struct vmbus_channel_gpadl_header *)
389 			msgheader->msg;
390 		gpadl_header->rangecount = 1;
391 		gpadl_header->range_buflen = sizeof(struct gpa_range) +
392 					 pagecount * sizeof(u64);
393 		gpadl_header->range[0].byte_offset = 0;
394 		gpadl_header->range[0].byte_count = size;
395 		for (i = 0; i < pagecount; i++)
396 			gpadl_header->range[0].pfn_array[i] = virt_to_hvpfn(
397 				kbuffer + PAGE_SIZE * i);
398 
399 		*msginfo = msgheader;
400 	}
401 
402 	return 0;
403 nomem:
404 	kfree(msgheader);
405 	kfree(msgbody);
406 	return -ENOMEM;
407 }
408 
409 /*
410  * vmbus_establish_gpadl - Establish a GPADL for the specified buffer
411  *
412  * @channel: a channel
413  * @kbuffer: from kmalloc or vmalloc
414  * @size: page-size multiple
415  * @gpadl_handle: some funky thing
416  */
417 int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,
418 			       u32 size, u32 *gpadl_handle)
419 {
420 	struct vmbus_channel_gpadl_header *gpadlmsg;
421 	struct vmbus_channel_gpadl_body *gpadl_body;
422 	struct vmbus_channel_msginfo *msginfo = NULL;
423 	struct vmbus_channel_msginfo *submsginfo, *tmp;
424 	struct list_head *curr;
425 	u32 next_gpadl_handle;
426 	unsigned long flags;
427 	int ret = 0;
428 
429 	next_gpadl_handle =
430 		(atomic_inc_return(&vmbus_connection.next_gpadl_handle) - 1);
431 
432 	ret = create_gpadl_header(kbuffer, size, &msginfo);
433 	if (ret)
434 		return ret;
435 
436 	init_completion(&msginfo->waitevent);
437 	msginfo->waiting_channel = channel;
438 
439 	gpadlmsg = (struct vmbus_channel_gpadl_header *)msginfo->msg;
440 	gpadlmsg->header.msgtype = CHANNELMSG_GPADL_HEADER;
441 	gpadlmsg->child_relid = channel->offermsg.child_relid;
442 	gpadlmsg->gpadl = next_gpadl_handle;
443 
444 
445 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
446 	list_add_tail(&msginfo->msglistentry,
447 		      &vmbus_connection.chn_msg_list);
448 
449 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
450 
451 	if (channel->rescind) {
452 		ret = -ENODEV;
453 		goto cleanup;
454 	}
455 
456 	ret = vmbus_post_msg(gpadlmsg, msginfo->msgsize -
457 			     sizeof(*msginfo), true);
458 
459 	trace_vmbus_establish_gpadl_header(gpadlmsg, ret);
460 
461 	if (ret != 0)
462 		goto cleanup;
463 
464 	list_for_each(curr, &msginfo->submsglist) {
465 		submsginfo = (struct vmbus_channel_msginfo *)curr;
466 		gpadl_body =
467 			(struct vmbus_channel_gpadl_body *)submsginfo->msg;
468 
469 		gpadl_body->header.msgtype =
470 			CHANNELMSG_GPADL_BODY;
471 		gpadl_body->gpadl = next_gpadl_handle;
472 
473 		ret = vmbus_post_msg(gpadl_body,
474 				     submsginfo->msgsize - sizeof(*submsginfo),
475 				     true);
476 
477 		trace_vmbus_establish_gpadl_body(gpadl_body, ret);
478 
479 		if (ret != 0)
480 			goto cleanup;
481 
482 	}
483 	wait_for_completion(&msginfo->waitevent);
484 
485 	if (channel->rescind) {
486 		ret = -ENODEV;
487 		goto cleanup;
488 	}
489 
490 	/* At this point, we received the gpadl created msg */
491 	*gpadl_handle = gpadlmsg->gpadl;
492 
493 cleanup:
494 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
495 	list_del(&msginfo->msglistentry);
496 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
497 	list_for_each_entry_safe(submsginfo, tmp, &msginfo->submsglist,
498 				 msglistentry) {
499 		kfree(submsginfo);
500 	}
501 
502 	kfree(msginfo);
503 	return ret;
504 }
505 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
506 
507 /*
508  * vmbus_teardown_gpadl -Teardown the specified GPADL handle
509  */
510 int vmbus_teardown_gpadl(struct vmbus_channel *channel, u32 gpadl_handle)
511 {
512 	struct vmbus_channel_gpadl_teardown *msg;
513 	struct vmbus_channel_msginfo *info;
514 	unsigned long flags;
515 	int ret;
516 
517 	info = kmalloc(sizeof(*info) +
518 		       sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
519 	if (!info)
520 		return -ENOMEM;
521 
522 	init_completion(&info->waitevent);
523 	info->waiting_channel = channel;
524 
525 	msg = (struct vmbus_channel_gpadl_teardown *)info->msg;
526 
527 	msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
528 	msg->child_relid = channel->offermsg.child_relid;
529 	msg->gpadl = gpadl_handle;
530 
531 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
532 	list_add_tail(&info->msglistentry,
533 		      &vmbus_connection.chn_msg_list);
534 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
535 
536 	if (channel->rescind)
537 		goto post_msg_err;
538 
539 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_gpadl_teardown),
540 			     true);
541 
542 	trace_vmbus_teardown_gpadl(msg, ret);
543 
544 	if (ret)
545 		goto post_msg_err;
546 
547 	wait_for_completion(&info->waitevent);
548 
549 post_msg_err:
550 	/*
551 	 * If the channel has been rescinded;
552 	 * we will be awakened by the rescind
553 	 * handler; set the error code to zero so we don't leak memory.
554 	 */
555 	if (channel->rescind)
556 		ret = 0;
557 
558 	spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
559 	list_del(&info->msglistentry);
560 	spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
561 
562 	kfree(info);
563 	return ret;
564 }
565 EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl);
566 
567 static void reset_channel_cb(void *arg)
568 {
569 	struct vmbus_channel *channel = arg;
570 
571 	channel->onchannel_callback = NULL;
572 }
573 
574 void vmbus_reset_channel_cb(struct vmbus_channel *channel)
575 {
576 	/*
577 	 * vmbus_on_event(), running in the per-channel tasklet, can race
578 	 * with vmbus_close_internal() in the case of SMP guest, e.g., when
579 	 * the former is accessing channel->inbound.ring_buffer, the latter
580 	 * could be freeing the ring_buffer pages, so here we must stop it
581 	 * first.
582 	 */
583 	tasklet_disable(&channel->callback_event);
584 
585 	channel->sc_creation_callback = NULL;
586 
587 	/* Stop the callback asap */
588 	if (channel->target_cpu != get_cpu()) {
589 		put_cpu();
590 		smp_call_function_single(channel->target_cpu, reset_channel_cb,
591 					 channel, true);
592 	} else {
593 		reset_channel_cb(channel);
594 		put_cpu();
595 	}
596 
597 	/* Re-enable tasklet for use on re-open */
598 	tasklet_enable(&channel->callback_event);
599 }
600 
601 static int vmbus_close_internal(struct vmbus_channel *channel)
602 {
603 	struct vmbus_channel_close_channel *msg;
604 	int ret;
605 
606 	vmbus_reset_channel_cb(channel);
607 
608 	/*
609 	 * In case a device driver's probe() fails (e.g.,
610 	 * util_probe() -> vmbus_open() returns -ENOMEM) and the device is
611 	 * rescinded later (e.g., we dynamically disable an Integrated Service
612 	 * in Hyper-V Manager), the driver's remove() invokes vmbus_close():
613 	 * here we should skip most of the below cleanup work.
614 	 */
615 	if (channel->state != CHANNEL_OPENED_STATE) {
616 		ret = -EINVAL;
617 		goto out;
618 	}
619 
620 	channel->state = CHANNEL_OPEN_STATE;
621 
622 	/* Send a closing message */
623 
624 	msg = &channel->close_msg.msg;
625 
626 	msg->header.msgtype = CHANNELMSG_CLOSECHANNEL;
627 	msg->child_relid = channel->offermsg.child_relid;
628 
629 	ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_close_channel),
630 			     true);
631 
632 	trace_vmbus_close_internal(msg, ret);
633 
634 	if (ret) {
635 		pr_err("Close failed: close post msg return is %d\n", ret);
636 		/*
637 		 * If we failed to post the close msg,
638 		 * it is perhaps better to leak memory.
639 		 */
640 		goto out;
641 	}
642 
643 	/* Tear down the gpadl for the channel's ring buffer */
644 	if (channel->ringbuffer_gpadlhandle) {
645 		ret = vmbus_teardown_gpadl(channel,
646 					   channel->ringbuffer_gpadlhandle);
647 		if (ret) {
648 			pr_err("Close failed: teardown gpadl return %d\n", ret);
649 			/*
650 			 * If we failed to teardown gpadl,
651 			 * it is perhaps better to leak memory.
652 			 */
653 			goto out;
654 		}
655 	}
656 
657 	/* Cleanup the ring buffers for this channel */
658 	hv_ringbuffer_cleanup(&channel->outbound);
659 	hv_ringbuffer_cleanup(&channel->inbound);
660 
661 	free_pages((unsigned long)channel->ringbuffer_pages,
662 		get_order(channel->ringbuffer_pagecount * PAGE_SIZE));
663 
664 out:
665 	return ret;
666 }
667 
668 /*
669  * vmbus_close - Close the specified channel
670  */
671 void vmbus_close(struct vmbus_channel *channel)
672 {
673 	struct list_head *cur, *tmp;
674 	struct vmbus_channel *cur_channel;
675 
676 	if (channel->primary_channel != NULL) {
677 		/*
678 		 * We will only close sub-channels when
679 		 * the primary is closed.
680 		 */
681 		return;
682 	}
683 	/*
684 	 * Close all the sub-channels first and then close the
685 	 * primary channel.
686 	 */
687 	list_for_each_safe(cur, tmp, &channel->sc_list) {
688 		cur_channel = list_entry(cur, struct vmbus_channel, sc_list);
689 		if (cur_channel->rescind) {
690 			wait_for_completion(&cur_channel->rescind_event);
691 			mutex_lock(&vmbus_connection.channel_mutex);
692 			vmbus_close_internal(cur_channel);
693 			hv_process_channel_removal(
694 					   cur_channel->offermsg.child_relid);
695 		} else {
696 			mutex_lock(&vmbus_connection.channel_mutex);
697 			vmbus_close_internal(cur_channel);
698 		}
699 		mutex_unlock(&vmbus_connection.channel_mutex);
700 	}
701 	/*
702 	 * Now close the primary.
703 	 */
704 	mutex_lock(&vmbus_connection.channel_mutex);
705 	vmbus_close_internal(channel);
706 	mutex_unlock(&vmbus_connection.channel_mutex);
707 }
708 EXPORT_SYMBOL_GPL(vmbus_close);
709 
710 /**
711  * vmbus_sendpacket() - Send the specified buffer on the given channel
712  * @channel: Pointer to vmbus_channel structure.
713  * @buffer: Pointer to the buffer you want to receive the data into.
714  * @bufferlen: Maximum size of what the the buffer will hold
715  * @requestid: Identifier of the request
716  * @type: Type of packet that is being send e.g. negotiate, time
717  * packet etc.
718  *
719  * Sends data in @buffer directly to hyper-v via the vmbus
720  * This will send the data unparsed to hyper-v.
721  *
722  * Mainly used by Hyper-V drivers.
723  */
724 int vmbus_sendpacket(struct vmbus_channel *channel, void *buffer,
725 			   u32 bufferlen, u64 requestid,
726 			   enum vmbus_packet_type type, u32 flags)
727 {
728 	struct vmpacket_descriptor desc;
729 	u32 packetlen = sizeof(struct vmpacket_descriptor) + bufferlen;
730 	u32 packetlen_aligned = ALIGN(packetlen, sizeof(u64));
731 	struct kvec bufferlist[3];
732 	u64 aligned_data = 0;
733 	int num_vecs = ((bufferlen != 0) ? 3 : 1);
734 
735 
736 	/* Setup the descriptor */
737 	desc.type = type; /* VmbusPacketTypeDataInBand; */
738 	desc.flags = flags; /* VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED; */
739 	/* in 8-bytes granularity */
740 	desc.offset8 = sizeof(struct vmpacket_descriptor) >> 3;
741 	desc.len8 = (u16)(packetlen_aligned >> 3);
742 	desc.trans_id = requestid;
743 
744 	bufferlist[0].iov_base = &desc;
745 	bufferlist[0].iov_len = sizeof(struct vmpacket_descriptor);
746 	bufferlist[1].iov_base = buffer;
747 	bufferlist[1].iov_len = bufferlen;
748 	bufferlist[2].iov_base = &aligned_data;
749 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
750 
751 	return hv_ringbuffer_write(channel, bufferlist, num_vecs);
752 }
753 EXPORT_SYMBOL(vmbus_sendpacket);
754 
755 /*
756  * vmbus_sendpacket_pagebuffer - Send a range of single-page buffer
757  * packets using a GPADL Direct packet type. This interface allows you
758  * to control notifying the host. This will be useful for sending
759  * batched data. Also the sender can control the send flags
760  * explicitly.
761  */
762 int vmbus_sendpacket_pagebuffer(struct vmbus_channel *channel,
763 				struct hv_page_buffer pagebuffers[],
764 				u32 pagecount, void *buffer, u32 bufferlen,
765 				u64 requestid)
766 {
767 	int i;
768 	struct vmbus_channel_packet_page_buffer desc;
769 	u32 descsize;
770 	u32 packetlen;
771 	u32 packetlen_aligned;
772 	struct kvec bufferlist[3];
773 	u64 aligned_data = 0;
774 
775 	if (pagecount > MAX_PAGE_BUFFER_COUNT)
776 		return -EINVAL;
777 
778 	/*
779 	 * Adjust the size down since vmbus_channel_packet_page_buffer is the
780 	 * largest size we support
781 	 */
782 	descsize = sizeof(struct vmbus_channel_packet_page_buffer) -
783 			  ((MAX_PAGE_BUFFER_COUNT - pagecount) *
784 			  sizeof(struct hv_page_buffer));
785 	packetlen = descsize + bufferlen;
786 	packetlen_aligned = ALIGN(packetlen, sizeof(u64));
787 
788 	/* Setup the descriptor */
789 	desc.type = VM_PKT_DATA_USING_GPA_DIRECT;
790 	desc.flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
791 	desc.dataoffset8 = descsize >> 3; /* in 8-bytes granularity */
792 	desc.length8 = (u16)(packetlen_aligned >> 3);
793 	desc.transactionid = requestid;
794 	desc.reserved = 0;
795 	desc.rangecount = pagecount;
796 
797 	for (i = 0; i < pagecount; i++) {
798 		desc.range[i].len = pagebuffers[i].len;
799 		desc.range[i].offset = pagebuffers[i].offset;
800 		desc.range[i].pfn	 = pagebuffers[i].pfn;
801 	}
802 
803 	bufferlist[0].iov_base = &desc;
804 	bufferlist[0].iov_len = descsize;
805 	bufferlist[1].iov_base = buffer;
806 	bufferlist[1].iov_len = bufferlen;
807 	bufferlist[2].iov_base = &aligned_data;
808 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
809 
810 	return hv_ringbuffer_write(channel, bufferlist, 3);
811 }
812 EXPORT_SYMBOL_GPL(vmbus_sendpacket_pagebuffer);
813 
814 /*
815  * vmbus_sendpacket_multipagebuffer - Send a multi-page buffer packet
816  * using a GPADL Direct packet type.
817  * The buffer includes the vmbus descriptor.
818  */
819 int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,
820 			      struct vmbus_packet_mpb_array *desc,
821 			      u32 desc_size,
822 			      void *buffer, u32 bufferlen, u64 requestid)
823 {
824 	u32 packetlen;
825 	u32 packetlen_aligned;
826 	struct kvec bufferlist[3];
827 	u64 aligned_data = 0;
828 
829 	packetlen = desc_size + bufferlen;
830 	packetlen_aligned = ALIGN(packetlen, sizeof(u64));
831 
832 	/* Setup the descriptor */
833 	desc->type = VM_PKT_DATA_USING_GPA_DIRECT;
834 	desc->flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
835 	desc->dataoffset8 = desc_size >> 3; /* in 8-bytes granularity */
836 	desc->length8 = (u16)(packetlen_aligned >> 3);
837 	desc->transactionid = requestid;
838 	desc->reserved = 0;
839 	desc->rangecount = 1;
840 
841 	bufferlist[0].iov_base = desc;
842 	bufferlist[0].iov_len = desc_size;
843 	bufferlist[1].iov_base = buffer;
844 	bufferlist[1].iov_len = bufferlen;
845 	bufferlist[2].iov_base = &aligned_data;
846 	bufferlist[2].iov_len = (packetlen_aligned - packetlen);
847 
848 	return hv_ringbuffer_write(channel, bufferlist, 3);
849 }
850 EXPORT_SYMBOL_GPL(vmbus_sendpacket_mpb_desc);
851 
852 /**
853  * vmbus_recvpacket() - Retrieve the user packet on the specified channel
854  * @channel: Pointer to vmbus_channel structure.
855  * @buffer: Pointer to the buffer you want to receive the data into.
856  * @bufferlen: Maximum size of what the the buffer will hold
857  * @buffer_actual_len: The actual size of the data after it was received
858  * @requestid: Identifier of the request
859  *
860  * Receives directly from the hyper-v vmbus and puts the data it received
861  * into Buffer. This will receive the data unparsed from hyper-v.
862  *
863  * Mainly used by Hyper-V drivers.
864  */
865 static inline int
866 __vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
867 		   u32 bufferlen, u32 *buffer_actual_len, u64 *requestid,
868 		   bool raw)
869 {
870 	return hv_ringbuffer_read(channel, buffer, bufferlen,
871 				  buffer_actual_len, requestid, raw);
872 
873 }
874 
875 int vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
876 		     u32 bufferlen, u32 *buffer_actual_len,
877 		     u64 *requestid)
878 {
879 	return __vmbus_recvpacket(channel, buffer, bufferlen,
880 				  buffer_actual_len, requestid, false);
881 }
882 EXPORT_SYMBOL(vmbus_recvpacket);
883 
884 /*
885  * vmbus_recvpacket_raw - Retrieve the raw packet on the specified channel
886  */
887 int vmbus_recvpacket_raw(struct vmbus_channel *channel, void *buffer,
888 			      u32 bufferlen, u32 *buffer_actual_len,
889 			      u64 *requestid)
890 {
891 	return __vmbus_recvpacket(channel, buffer, bufferlen,
892 				  buffer_actual_len, requestid, true);
893 }
894 EXPORT_SYMBOL_GPL(vmbus_recvpacket_raw);
895