vmbus_chan.c revision 302619
1/*-
2 * Copyright (c) 2009-2012,2016 Microsoft Corp.
3 * Copyright (c) 2012 NetApp Inc.
4 * Copyright (c) 2012 Citrix Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice unmodified, this list of conditions, and the following
12 *    disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/dev/hyperv/vmbus/hv_channel.c 302619 2016-07-12 05:09:07Z sephe $");
31
32#include <sys/param.h>
33#include <sys/kernel.h>
34#include <sys/malloc.h>
35#include <sys/systm.h>
36#include <sys/mbuf.h>
37#include <sys/lock.h>
38#include <sys/mutex.h>
39#include <sys/sysctl.h>
40
41#include <machine/atomic.h>
42#include <machine/bus.h>
43
44#include <vm/vm.h>
45#include <vm/vm_param.h>
46#include <vm/pmap.h>
47
48#include <dev/hyperv/vmbus/hv_vmbus_priv.h>
49#include <dev/hyperv/vmbus/hyperv_var.h>
50#include <dev/hyperv/vmbus/vmbus_reg.h>
51#include <dev/hyperv/vmbus/vmbus_var.h>
52
53static void 	vmbus_channel_set_event(hv_vmbus_channel* channel);
54static void	VmbusProcessChannelEvent(void* channel, int pending);
55
56/**
57 *  @brief Trigger an event notification on the specified channel
58 */
59static void
60vmbus_channel_set_event(hv_vmbus_channel *channel)
61{
62	struct vmbus_softc *sc = channel->vmbus_sc;
63	uint32_t chanid = channel->offer_msg.child_rel_id;
64
65	atomic_set_long(&sc->vmbus_tx_evtflags[chanid >> VMBUS_EVTFLAG_SHIFT],
66	    1UL << (chanid & VMBUS_EVTFLAG_MASK));
67
68	if (channel->offer_msg.monitor_allocated) {
69		hv_vmbus_monitor_page *monitor_page;
70
71		monitor_page = sc->vmbus_mnf2;
72		synch_set_bit(channel->monitor_bit,
73			(uint32_t *)&monitor_page->
74				trigger_group[channel->monitor_group].u.pending);
75	} else {
76		hypercall_signal_event(channel->ch_sigevt_dma.hv_paddr);
77	}
78
79}
80
81static int
82vmbus_channel_sysctl_monalloc(SYSCTL_HANDLER_ARGS)
83{
84	struct hv_vmbus_channel *chan = arg1;
85	int alloc = 0;
86
87	if (chan->offer_msg.monitor_allocated)
88		alloc = 1;
89	return sysctl_handle_int(oidp, &alloc, 0, req);
90}
91
92static void
93vmbus_channel_sysctl_create(hv_vmbus_channel* channel)
94{
95	device_t dev;
96	struct sysctl_oid *devch_sysctl;
97	struct sysctl_oid *devch_id_sysctl, *devch_sub_sysctl;
98	struct sysctl_oid *devch_id_in_sysctl, *devch_id_out_sysctl;
99	struct sysctl_ctx_list *ctx;
100	uint32_t ch_id;
101	uint16_t sub_ch_id;
102	char name[16];
103
104	hv_vmbus_channel* primary_ch = channel->primary_channel;
105
106	if (primary_ch == NULL) {
107		dev = channel->device->device;
108		ch_id = channel->offer_msg.child_rel_id;
109	} else {
110		dev = primary_ch->device->device;
111		ch_id = primary_ch->offer_msg.child_rel_id;
112		sub_ch_id = channel->offer_msg.offer.sub_channel_index;
113	}
114	ctx = device_get_sysctl_ctx(dev);
115	/* This creates dev.DEVNAME.DEVUNIT.channel tree */
116	devch_sysctl = SYSCTL_ADD_NODE(ctx,
117		    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
118		    OID_AUTO, "channel", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
119	/* This creates dev.DEVNAME.DEVUNIT.channel.CHANID tree */
120	snprintf(name, sizeof(name), "%d", ch_id);
121	devch_id_sysctl = SYSCTL_ADD_NODE(ctx,
122	    	    SYSCTL_CHILDREN(devch_sysctl),
123	    	    OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
124
125	if (primary_ch != NULL) {
126		devch_sub_sysctl = SYSCTL_ADD_NODE(ctx,
127			SYSCTL_CHILDREN(devch_id_sysctl),
128			OID_AUTO, "sub", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
129		snprintf(name, sizeof(name), "%d", sub_ch_id);
130		devch_id_sysctl = SYSCTL_ADD_NODE(ctx,
131			SYSCTL_CHILDREN(devch_sub_sysctl),
132			OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
133
134		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(devch_id_sysctl),
135		    OID_AUTO, "chanid", CTLFLAG_RD,
136		    &channel->offer_msg.child_rel_id, 0, "channel id");
137	}
138	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(devch_id_sysctl), OID_AUTO,
139	    "cpu", CTLFLAG_RD, &channel->target_cpu, 0, "owner CPU id");
140	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(devch_id_sysctl), OID_AUTO,
141	    "monitor_allocated", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
142	    channel, 0, vmbus_channel_sysctl_monalloc, "I",
143	    "is monitor allocated to this channel");
144
145	devch_id_in_sysctl = SYSCTL_ADD_NODE(ctx,
146                    SYSCTL_CHILDREN(devch_id_sysctl),
147                    OID_AUTO,
148		    "in",
149		    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
150	devch_id_out_sysctl = SYSCTL_ADD_NODE(ctx,
151                    SYSCTL_CHILDREN(devch_id_sysctl),
152                    OID_AUTO,
153		    "out",
154		    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
155	hv_ring_buffer_stat(ctx,
156		SYSCTL_CHILDREN(devch_id_in_sysctl),
157		&(channel->inbound),
158		"inbound ring buffer stats");
159	hv_ring_buffer_stat(ctx,
160		SYSCTL_CHILDREN(devch_id_out_sysctl),
161		&(channel->outbound),
162		"outbound ring buffer stats");
163}
164
165/**
166 * @brief Open the specified channel
167 */
168int
169hv_vmbus_channel_open(
170	hv_vmbus_channel*		new_channel,
171	uint32_t			send_ring_buffer_size,
172	uint32_t			recv_ring_buffer_size,
173	void*				user_data,
174	uint32_t			user_data_len,
175	hv_vmbus_pfn_channel_callback	pfn_on_channel_callback,
176	void* 				context)
177{
178	struct vmbus_softc *sc = new_channel->vmbus_sc;
179	const struct vmbus_chanmsg_chopen_resp *resp;
180	const struct vmbus_message *msg;
181	struct vmbus_chanmsg_chopen *req;
182	struct vmbus_msghc *mh;
183	uint32_t status;
184	int ret = 0;
185	void *in, *out;
186
187	if (user_data_len > VMBUS_CHANMSG_CHOPEN_UDATA_SIZE) {
188		device_printf(sc->vmbus_dev,
189		    "invalid udata len %u for chan%u\n",
190		    user_data_len, new_channel->offer_msg.child_rel_id);
191		return EINVAL;
192	}
193
194	mtx_lock(&new_channel->sc_lock);
195	if (new_channel->state == HV_CHANNEL_OPEN_STATE) {
196	    new_channel->state = HV_CHANNEL_OPENING_STATE;
197	} else {
198	    mtx_unlock(&new_channel->sc_lock);
199	    if(bootverbose)
200		printf("VMBUS: Trying to open channel <%p> which in "
201		    "%d state.\n", new_channel, new_channel->state);
202	    return (EINVAL);
203	}
204	mtx_unlock(&new_channel->sc_lock);
205
206	new_channel->on_channel_callback = pfn_on_channel_callback;
207	new_channel->channel_callback_context = context;
208
209	vmbus_on_channel_open(new_channel);
210
211	new_channel->rxq = VMBUS_PCPU_GET(new_channel->vmbus_sc, event_tq,
212	    new_channel->target_cpu);
213	TASK_INIT(&new_channel->channel_task, 0, VmbusProcessChannelEvent, new_channel);
214
215	/* Allocate the ring buffer */
216	out = contigmalloc((send_ring_buffer_size + recv_ring_buffer_size),
217	    M_DEVBUF, M_ZERO, 0UL, BUS_SPACE_MAXADDR, PAGE_SIZE, 0);
218	KASSERT(out != NULL,
219	    ("Error VMBUS: contigmalloc failed to allocate Ring Buffer!"));
220	if (out == NULL)
221		return (ENOMEM);
222
223	in = ((uint8_t *) out + send_ring_buffer_size);
224
225	new_channel->ring_buffer_pages = out;
226	new_channel->ring_buffer_page_count = (send_ring_buffer_size +
227	    recv_ring_buffer_size) >> PAGE_SHIFT;
228	new_channel->ring_buffer_size = send_ring_buffer_size +
229	    recv_ring_buffer_size;
230
231	hv_vmbus_ring_buffer_init(
232		&new_channel->outbound,
233		out,
234		send_ring_buffer_size);
235
236	hv_vmbus_ring_buffer_init(
237		&new_channel->inbound,
238		in,
239		recv_ring_buffer_size);
240
241	/* Create sysctl tree for this channel */
242	vmbus_channel_sysctl_create(new_channel);
243
244	/**
245	 * Establish the gpadl for the ring buffer
246	 */
247	new_channel->ring_buffer_gpadl_handle = 0;
248
249	ret = hv_vmbus_channel_establish_gpadl(new_channel,
250		new_channel->outbound.ring_buffer,
251		send_ring_buffer_size + recv_ring_buffer_size,
252		&new_channel->ring_buffer_gpadl_handle);
253
254	/*
255	 * Open channel w/ the bufring GPADL on the target CPU.
256	 */
257	mh = vmbus_msghc_get(sc, sizeof(*req));
258	if (mh == NULL) {
259		device_printf(sc->vmbus_dev,
260		    "can not get msg hypercall for chopen(chan%u)\n",
261		    new_channel->offer_msg.child_rel_id);
262		return ENXIO;
263	}
264
265	req = vmbus_msghc_dataptr(mh);
266	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHOPEN;
267	req->chm_chanid = new_channel->offer_msg.child_rel_id;
268	req->chm_openid = new_channel->offer_msg.child_rel_id;
269	req->chm_gpadl = new_channel->ring_buffer_gpadl_handle;
270	req->chm_vcpuid = new_channel->target_vcpu;
271	req->chm_rxbr_pgofs = send_ring_buffer_size >> PAGE_SHIFT;
272	if (user_data_len)
273		memcpy(req->chm_udata, user_data, user_data_len);
274
275	ret = vmbus_msghc_exec(sc, mh);
276	if (ret != 0) {
277		device_printf(sc->vmbus_dev,
278		    "chopen(chan%u) msg hypercall exec failed: %d\n",
279		    new_channel->offer_msg.child_rel_id, ret);
280		vmbus_msghc_put(sc, mh);
281		return ret;
282	}
283
284	msg = vmbus_msghc_wait_result(sc, mh);
285	resp = (const struct vmbus_chanmsg_chopen_resp *)msg->msg_data;
286	status = resp->chm_status;
287
288	vmbus_msghc_put(sc, mh);
289
290	if (status == 0) {
291		new_channel->state = HV_CHANNEL_OPENED_STATE;
292		if (bootverbose) {
293			device_printf(sc->vmbus_dev, "chan%u opened\n",
294			    new_channel->offer_msg.child_rel_id);
295		}
296	} else {
297		device_printf(sc->vmbus_dev, "failed to open chan%u\n",
298		    new_channel->offer_msg.child_rel_id);
299		ret = ENXIO;
300	}
301	return (ret);
302}
303
304/**
305 * @brief Establish a GPADL for the specified buffer
306 */
307int
308hv_vmbus_channel_establish_gpadl(struct hv_vmbus_channel *channel,
309    void *contig_buffer, uint32_t size, uint32_t *gpadl0)
310{
311	struct vmbus_softc *sc = channel->vmbus_sc;
312	struct vmbus_msghc *mh;
313	struct vmbus_chanmsg_gpadl_conn *req;
314	const struct vmbus_message *msg;
315	size_t reqsz;
316	uint32_t gpadl, status;
317	int page_count, range_len, i, cnt, error;
318	uint64_t page_id, paddr;
319
320	/*
321	 * Preliminary checks.
322	 */
323
324	KASSERT((size & PAGE_MASK) == 0,
325	    ("invalid GPA size %u, not multiple page size", size));
326	page_count = size >> PAGE_SHIFT;
327
328	paddr = hv_get_phys_addr(contig_buffer);
329	KASSERT((paddr & PAGE_MASK) == 0,
330	    ("GPA is not page aligned %jx", (uintmax_t)paddr));
331	page_id = paddr >> PAGE_SHIFT;
332
333	range_len = __offsetof(struct vmbus_gpa_range, gpa_page[page_count]);
334	/*
335	 * We don't support multiple GPA ranges.
336	 */
337	if (range_len > UINT16_MAX) {
338		device_printf(sc->vmbus_dev, "GPA too large, %d pages\n",
339		    page_count);
340		return EOPNOTSUPP;
341	}
342
343	/*
344	 * Allocate GPADL id.
345	 */
346	gpadl = atomic_fetchadd_int(
347	    &hv_vmbus_g_connection.next_gpadl_handle, 1);
348	*gpadl0 = gpadl;
349
350	/*
351	 * Connect this GPADL to the target channel.
352	 *
353	 * NOTE:
354	 * Since each message can only hold small set of page
355	 * addresses, several messages may be required to
356	 * complete the connection.
357	 */
358	if (page_count > VMBUS_CHANMSG_GPADL_CONN_PGMAX)
359		cnt = VMBUS_CHANMSG_GPADL_CONN_PGMAX;
360	else
361		cnt = page_count;
362	page_count -= cnt;
363
364	reqsz = __offsetof(struct vmbus_chanmsg_gpadl_conn,
365	    chm_range.gpa_page[cnt]);
366	mh = vmbus_msghc_get(sc, reqsz);
367	if (mh == NULL) {
368		device_printf(sc->vmbus_dev,
369		    "can not get msg hypercall for gpadl->chan%u\n",
370		    channel->offer_msg.child_rel_id);
371		return EIO;
372	}
373
374	req = vmbus_msghc_dataptr(mh);
375	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_CONN;
376	req->chm_chanid = channel->offer_msg.child_rel_id;
377	req->chm_gpadl = gpadl;
378	req->chm_range_len = range_len;
379	req->chm_range_cnt = 1;
380	req->chm_range.gpa_len = size;
381	req->chm_range.gpa_ofs = 0;
382	for (i = 0; i < cnt; ++i)
383		req->chm_range.gpa_page[i] = page_id++;
384
385	error = vmbus_msghc_exec(sc, mh);
386	if (error) {
387		device_printf(sc->vmbus_dev,
388		    "gpadl->chan%u msg hypercall exec failed: %d\n",
389		    channel->offer_msg.child_rel_id, error);
390		vmbus_msghc_put(sc, mh);
391		return error;
392	}
393
394	while (page_count > 0) {
395		struct vmbus_chanmsg_gpadl_subconn *subreq;
396
397		if (page_count > VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX)
398			cnt = VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX;
399		else
400			cnt = page_count;
401		page_count -= cnt;
402
403		reqsz = __offsetof(struct vmbus_chanmsg_gpadl_subconn,
404		    chm_gpa_page[cnt]);
405		vmbus_msghc_reset(mh, reqsz);
406
407		subreq = vmbus_msghc_dataptr(mh);
408		subreq->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_SUBCONN;
409		subreq->chm_gpadl = gpadl;
410		for (i = 0; i < cnt; ++i)
411			subreq->chm_gpa_page[i] = page_id++;
412
413		vmbus_msghc_exec_noresult(mh);
414	}
415	KASSERT(page_count == 0, ("invalid page count %d", page_count));
416
417	msg = vmbus_msghc_wait_result(sc, mh);
418	status = ((const struct vmbus_chanmsg_gpadl_connresp *)
419	    msg->msg_data)->chm_status;
420
421	vmbus_msghc_put(sc, mh);
422
423	if (status != 0) {
424		device_printf(sc->vmbus_dev, "gpadl->chan%u failed: "
425		    "status %u\n", channel->offer_msg.child_rel_id, status);
426		return EIO;
427	}
428	return 0;
429}
430
431/*
432 * Disconnect the GPA from the target channel
433 */
434int
435hv_vmbus_channel_teardown_gpdal(struct hv_vmbus_channel *chan, uint32_t gpadl)
436{
437	struct vmbus_softc *sc = chan->vmbus_sc;
438	struct vmbus_msghc *mh;
439	struct vmbus_chanmsg_gpadl_disconn *req;
440	int error;
441
442	mh = vmbus_msghc_get(sc, sizeof(*req));
443	if (mh == NULL) {
444		device_printf(sc->vmbus_dev,
445		    "can not get msg hypercall for gpa x->chan%u\n",
446		    chan->offer_msg.child_rel_id);
447		return EBUSY;
448	}
449
450	req = vmbus_msghc_dataptr(mh);
451	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_DISCONN;
452	req->chm_chanid = chan->offer_msg.child_rel_id;
453	req->chm_gpadl = gpadl;
454
455	error = vmbus_msghc_exec(sc, mh);
456	if (error) {
457		device_printf(sc->vmbus_dev,
458		    "gpa x->chan%u msg hypercall exec failed: %d\n",
459		    chan->offer_msg.child_rel_id, error);
460		vmbus_msghc_put(sc, mh);
461		return error;
462	}
463
464	vmbus_msghc_wait_result(sc, mh);
465	/* Discard result; no useful information */
466	vmbus_msghc_put(sc, mh);
467
468	return 0;
469}
470
471static void
472hv_vmbus_channel_close_internal(hv_vmbus_channel *channel)
473{
474	struct vmbus_softc *sc = channel->vmbus_sc;
475	struct vmbus_msghc *mh;
476	struct vmbus_chanmsg_chclose *req;
477	struct taskqueue *rxq = channel->rxq;
478	int error;
479
480	channel->state = HV_CHANNEL_OPEN_STATE;
481
482	/*
483	 * set rxq to NULL to avoid more requests be scheduled
484	 */
485	channel->rxq = NULL;
486	taskqueue_drain(rxq, &channel->channel_task);
487	channel->on_channel_callback = NULL;
488
489	/**
490	 * Send a closing message
491	 */
492
493	mh = vmbus_msghc_get(sc, sizeof(*req));
494	if (mh == NULL) {
495		device_printf(sc->vmbus_dev,
496		    "can not get msg hypercall for chclose(chan%u)\n",
497		    channel->offer_msg.child_rel_id);
498		return;
499	}
500
501	req = vmbus_msghc_dataptr(mh);
502	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHCLOSE;
503	req->chm_chanid = channel->offer_msg.child_rel_id;
504
505	error = vmbus_msghc_exec_noresult(mh);
506	vmbus_msghc_put(sc, mh);
507
508	if (error) {
509		device_printf(sc->vmbus_dev,
510		    "chclose(chan%u) msg hypercall exec failed: %d\n",
511		    channel->offer_msg.child_rel_id, error);
512		return;
513	} else if (bootverbose) {
514		device_printf(sc->vmbus_dev, "close chan%u\n",
515		    channel->offer_msg.child_rel_id);
516	}
517
518	/* Tear down the gpadl for the channel's ring buffer */
519	if (channel->ring_buffer_gpadl_handle) {
520		hv_vmbus_channel_teardown_gpdal(channel,
521			channel->ring_buffer_gpadl_handle);
522	}
523
524	/* TODO: Send a msg to release the childRelId */
525
526	/* cleanup the ring buffers for this channel */
527	hv_ring_buffer_cleanup(&channel->outbound);
528	hv_ring_buffer_cleanup(&channel->inbound);
529
530	contigfree(channel->ring_buffer_pages, channel->ring_buffer_size,
531	    M_DEVBUF);
532}
533
534/**
535 * @brief Close the specified channel
536 */
537void
538hv_vmbus_channel_close(hv_vmbus_channel *channel)
539{
540	hv_vmbus_channel*	sub_channel;
541
542	if (channel->primary_channel != NULL) {
543		/*
544		 * We only close multi-channels when the primary is
545		 * closed.
546		 */
547		return;
548	}
549
550	/*
551	 * Close all multi-channels first.
552	 */
553	TAILQ_FOREACH(sub_channel, &channel->sc_list_anchor,
554	    sc_list_entry) {
555		if (sub_channel->state != HV_CHANNEL_OPENED_STATE)
556			continue;
557		hv_vmbus_channel_close_internal(sub_channel);
558	}
559	/*
560	 * Then close the primary channel.
561	 */
562	hv_vmbus_channel_close_internal(channel);
563}
564
565/**
566 * @brief Send the specified buffer on the given channel
567 */
568int
569hv_vmbus_channel_send_packet(
570	hv_vmbus_channel*	channel,
571	void*			buffer,
572	uint32_t		buffer_len,
573	uint64_t		request_id,
574	hv_vmbus_packet_type	type,
575	uint32_t		flags)
576{
577	int			ret = 0;
578	hv_vm_packet_descriptor	desc;
579	uint32_t		packet_len;
580	uint64_t		aligned_data;
581	uint32_t		packet_len_aligned;
582	boolean_t		need_sig;
583	hv_vmbus_sg_buffer_list	buffer_list[3];
584
585	packet_len = sizeof(hv_vm_packet_descriptor) + buffer_len;
586	packet_len_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
587	aligned_data = 0;
588
589	/* Setup the descriptor */
590	desc.type = type;   /* HV_VMBUS_PACKET_TYPE_DATA_IN_BAND;             */
591	desc.flags = flags; /* HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED */
592			    /* in 8-bytes granularity */
593	desc.data_offset8 = sizeof(hv_vm_packet_descriptor) >> 3;
594	desc.length8 = (uint16_t) (packet_len_aligned >> 3);
595	desc.transaction_id = request_id;
596
597	buffer_list[0].data = &desc;
598	buffer_list[0].length = sizeof(hv_vm_packet_descriptor);
599
600	buffer_list[1].data = buffer;
601	buffer_list[1].length = buffer_len;
602
603	buffer_list[2].data = &aligned_data;
604	buffer_list[2].length = packet_len_aligned - packet_len;
605
606	ret = hv_ring_buffer_write(&channel->outbound, buffer_list, 3,
607	    &need_sig);
608
609	/* TODO: We should determine if this is optional */
610	if (ret == 0 && need_sig) {
611		vmbus_channel_set_event(channel);
612	}
613
614	return (ret);
615}
616
617/**
618 * @brief Send a range of single-page buffer packets using
619 * a GPADL Direct packet type
620 */
621int
622hv_vmbus_channel_send_packet_pagebuffer(
623	hv_vmbus_channel*	channel,
624	hv_vmbus_page_buffer	page_buffers[],
625	uint32_t		page_count,
626	void*			buffer,
627	uint32_t		buffer_len,
628	uint64_t		request_id)
629{
630
631	int					ret = 0;
632	boolean_t				need_sig;
633	uint32_t				packet_len;
634	uint32_t				page_buflen;
635	uint32_t				packetLen_aligned;
636	hv_vmbus_sg_buffer_list			buffer_list[4];
637	hv_vmbus_channel_packet_page_buffer	desc;
638	uint32_t				descSize;
639	uint64_t				alignedData = 0;
640
641	if (page_count > HV_MAX_PAGE_BUFFER_COUNT)
642		return (EINVAL);
643
644	/*
645	 * Adjust the size down since hv_vmbus_channel_packet_page_buffer
646	 *  is the largest size we support
647	 */
648	descSize = __offsetof(hv_vmbus_channel_packet_page_buffer, range);
649	page_buflen = sizeof(hv_vmbus_page_buffer) * page_count;
650	packet_len = descSize + page_buflen + buffer_len;
651	packetLen_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
652
653	/* Setup the descriptor */
654	desc.type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
655	desc.flags = HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
656	/* in 8-bytes granularity */
657	desc.data_offset8 = (descSize + page_buflen) >> 3;
658	desc.length8 = (uint16_t) (packetLen_aligned >> 3);
659	desc.transaction_id = request_id;
660	desc.range_count = page_count;
661
662	buffer_list[0].data = &desc;
663	buffer_list[0].length = descSize;
664
665	buffer_list[1].data = page_buffers;
666	buffer_list[1].length = page_buflen;
667
668	buffer_list[2].data = buffer;
669	buffer_list[2].length = buffer_len;
670
671	buffer_list[3].data = &alignedData;
672	buffer_list[3].length = packetLen_aligned - packet_len;
673
674	ret = hv_ring_buffer_write(&channel->outbound, buffer_list, 4,
675	    &need_sig);
676
677	/* TODO: We should determine if this is optional */
678	if (ret == 0 && need_sig) {
679		vmbus_channel_set_event(channel);
680	}
681
682	return (ret);
683}
684
685/**
686 * @brief Send a multi-page buffer packet using a GPADL Direct packet type
687 */
688int
689hv_vmbus_channel_send_packet_multipagebuffer(
690	hv_vmbus_channel*		channel,
691	hv_vmbus_multipage_buffer*	multi_page_buffer,
692	void*				buffer,
693	uint32_t			buffer_len,
694	uint64_t			request_id)
695{
696
697	int			ret = 0;
698	uint32_t		desc_size;
699	boolean_t		need_sig;
700	uint32_t		packet_len;
701	uint32_t		packet_len_aligned;
702	uint32_t		pfn_count;
703	uint64_t		aligned_data = 0;
704	hv_vmbus_sg_buffer_list	buffer_list[3];
705	hv_vmbus_channel_packet_multipage_buffer desc;
706
707	pfn_count =
708	    HV_NUM_PAGES_SPANNED(
709		    multi_page_buffer->offset,
710		    multi_page_buffer->length);
711
712	if ((pfn_count == 0) || (pfn_count > HV_MAX_MULTIPAGE_BUFFER_COUNT))
713	    return (EINVAL);
714	/*
715	 * Adjust the size down since hv_vmbus_channel_packet_multipage_buffer
716	 * is the largest size we support
717	 */
718	desc_size =
719	    sizeof(hv_vmbus_channel_packet_multipage_buffer) -
720		    ((HV_MAX_MULTIPAGE_BUFFER_COUNT - pfn_count) *
721			sizeof(uint64_t));
722	packet_len = desc_size + buffer_len;
723	packet_len_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
724
725	/*
726	 * Setup the descriptor
727	 */
728	desc.type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
729	desc.flags = HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
730	desc.data_offset8 = desc_size >> 3; /* in 8-bytes granularity */
731	desc.length8 = (uint16_t) (packet_len_aligned >> 3);
732	desc.transaction_id = request_id;
733	desc.range_count = 1;
734
735	desc.range.length = multi_page_buffer->length;
736	desc.range.offset = multi_page_buffer->offset;
737
738	memcpy(desc.range.pfn_array, multi_page_buffer->pfn_array,
739		pfn_count * sizeof(uint64_t));
740
741	buffer_list[0].data = &desc;
742	buffer_list[0].length = desc_size;
743
744	buffer_list[1].data = buffer;
745	buffer_list[1].length = buffer_len;
746
747	buffer_list[2].data = &aligned_data;
748	buffer_list[2].length = packet_len_aligned - packet_len;
749
750	ret = hv_ring_buffer_write(&channel->outbound, buffer_list, 3,
751	    &need_sig);
752
753	/* TODO: We should determine if this is optional */
754	if (ret == 0 && need_sig) {
755	    vmbus_channel_set_event(channel);
756	}
757
758	return (ret);
759}
760
761/**
762 * @brief Retrieve the user packet on the specified channel
763 */
764int
765hv_vmbus_channel_recv_packet(
766	hv_vmbus_channel*	channel,
767	void*			Buffer,
768	uint32_t		buffer_len,
769	uint32_t*		buffer_actual_len,
770	uint64_t*		request_id)
771{
772	int			ret;
773	uint32_t		user_len;
774	uint32_t		packet_len;
775	hv_vm_packet_descriptor	desc;
776
777	*buffer_actual_len = 0;
778	*request_id = 0;
779
780	ret = hv_ring_buffer_peek(&channel->inbound, &desc,
781		sizeof(hv_vm_packet_descriptor));
782	if (ret != 0)
783		return (0);
784
785	packet_len = desc.length8 << 3;
786	user_len = packet_len - (desc.data_offset8 << 3);
787
788	*buffer_actual_len = user_len;
789
790	if (user_len > buffer_len)
791		return (EINVAL);
792
793	*request_id = desc.transaction_id;
794
795	/* Copy over the packet to the user buffer */
796	ret = hv_ring_buffer_read(&channel->inbound, Buffer, user_len,
797		(desc.data_offset8 << 3));
798
799	return (0);
800}
801
802/**
803 * @brief Retrieve the raw packet on the specified channel
804 */
805int
806hv_vmbus_channel_recv_packet_raw(
807	hv_vmbus_channel*	channel,
808	void*			buffer,
809	uint32_t		buffer_len,
810	uint32_t*		buffer_actual_len,
811	uint64_t*		request_id)
812{
813	int		ret;
814	uint32_t	packetLen;
815	hv_vm_packet_descriptor	desc;
816
817	*buffer_actual_len = 0;
818	*request_id = 0;
819
820	ret = hv_ring_buffer_peek(
821		&channel->inbound, &desc,
822		sizeof(hv_vm_packet_descriptor));
823
824	if (ret != 0)
825	    return (0);
826
827	packetLen = desc.length8 << 3;
828	*buffer_actual_len = packetLen;
829
830	if (packetLen > buffer_len)
831	    return (ENOBUFS);
832
833	*request_id = desc.transaction_id;
834
835	/* Copy over the entire packet to the user buffer */
836	ret = hv_ring_buffer_read(&channel->inbound, buffer, packetLen, 0);
837
838	return (0);
839}
840
841
842/**
843 * Process a channel event notification
844 */
845static void
846VmbusProcessChannelEvent(void* context, int pending)
847{
848	void* arg;
849	uint32_t bytes_to_read;
850	hv_vmbus_channel* channel = (hv_vmbus_channel*)context;
851	boolean_t is_batched_reading;
852
853	if (channel->on_channel_callback != NULL) {
854		arg = channel->channel_callback_context;
855		is_batched_reading = channel->batched_reading;
856		/*
857		 * Optimize host to guest signaling by ensuring:
858		 * 1. While reading the channel, we disable interrupts from
859		 *    host.
860		 * 2. Ensure that we process all posted messages from the host
861		 *    before returning from this callback.
862		 * 3. Once we return, enable signaling from the host. Once this
863		 *    state is set we check to see if additional packets are
864		 *    available to read. In this case we repeat the process.
865		 */
866		do {
867			if (is_batched_reading)
868				hv_ring_buffer_read_begin(&channel->inbound);
869
870			channel->on_channel_callback(arg);
871
872			if (is_batched_reading)
873				bytes_to_read =
874				    hv_ring_buffer_read_end(&channel->inbound);
875			else
876				bytes_to_read = 0;
877		} while (is_batched_reading && (bytes_to_read != 0));
878	}
879}
880