vmbus_chan.c revision 302806
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 302806 2016-07-14 06:10:00Z 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_chan_send_event(hv_vmbus_channel* channel);
54static void	vmbus_chan_update_evtflagcnt(struct vmbus_softc *,
55		    const struct hv_vmbus_channel *);
56static void	vmbus_chan_task(void *, int);
57static void	vmbus_chan_task_nobatch(void *, int);
58
59/**
60 *  @brief Trigger an event notification on the specified channel
61 */
62static void
63vmbus_chan_send_event(hv_vmbus_channel *channel)
64{
65	struct vmbus_softc *sc = channel->vmbus_sc;
66	uint32_t chanid = channel->ch_id;
67
68	atomic_set_long(&sc->vmbus_tx_evtflags[chanid >> VMBUS_EVTFLAG_SHIFT],
69	    1UL << (chanid & VMBUS_EVTFLAG_MASK));
70
71	if (channel->ch_flags & VMBUS_CHAN_FLAG_HASMNF) {
72		atomic_set_int(
73		&sc->vmbus_mnf2->mnf_trigs[channel->ch_montrig_idx].mt_pending,
74		channel->ch_montrig_mask);
75	} else {
76		hypercall_signal_event(channel->ch_monprm_dma.hv_paddr);
77	}
78}
79
80static int
81vmbus_channel_sysctl_monalloc(SYSCTL_HANDLER_ARGS)
82{
83	struct hv_vmbus_channel *chan = arg1;
84	int alloc = 0;
85
86	if (chan->ch_flags & VMBUS_CHAN_FLAG_HASMNF)
87		alloc = 1;
88	return sysctl_handle_int(oidp, &alloc, 0, req);
89}
90
91static void
92vmbus_channel_sysctl_create(hv_vmbus_channel* channel)
93{
94	device_t dev;
95	struct sysctl_oid *devch_sysctl;
96	struct sysctl_oid *devch_id_sysctl, *devch_sub_sysctl;
97	struct sysctl_oid *devch_id_in_sysctl, *devch_id_out_sysctl;
98	struct sysctl_ctx_list *ctx;
99	uint32_t ch_id;
100	uint16_t sub_ch_id;
101	char name[16];
102
103	hv_vmbus_channel* primary_ch = channel->primary_channel;
104
105	if (primary_ch == NULL) {
106		dev = channel->ch_dev;
107		ch_id = channel->ch_id;
108	} else {
109		dev = primary_ch->ch_dev;
110		ch_id = primary_ch->ch_id;
111		sub_ch_id = channel->ch_subidx;
112	}
113	ctx = &channel->ch_sysctl_ctx;
114	sysctl_ctx_init(ctx);
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->ch_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->ch_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_chan_update_evtflagcnt(sc, new_channel);
210
211	new_channel->rxq = VMBUS_PCPU_GET(new_channel->vmbus_sc, event_tq,
212	    new_channel->target_cpu);
213	if (new_channel->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD) {
214		TASK_INIT(&new_channel->channel_task, 0,
215		    vmbus_chan_task, new_channel);
216	} else {
217		TASK_INIT(&new_channel->channel_task, 0,
218		    vmbus_chan_task_nobatch, new_channel);
219	}
220
221	/* Allocate the ring buffer */
222	out = contigmalloc((send_ring_buffer_size + recv_ring_buffer_size),
223	    M_DEVBUF, M_ZERO, 0UL, BUS_SPACE_MAXADDR, PAGE_SIZE, 0);
224	KASSERT(out != NULL,
225	    ("Error VMBUS: contigmalloc failed to allocate Ring Buffer!"));
226	if (out == NULL)
227		return (ENOMEM);
228
229	in = ((uint8_t *) out + send_ring_buffer_size);
230
231	new_channel->ring_buffer_pages = out;
232	new_channel->ring_buffer_page_count = (send_ring_buffer_size +
233	    recv_ring_buffer_size) >> PAGE_SHIFT;
234	new_channel->ring_buffer_size = send_ring_buffer_size +
235	    recv_ring_buffer_size;
236
237	hv_vmbus_ring_buffer_init(
238		&new_channel->outbound,
239		out,
240		send_ring_buffer_size);
241
242	hv_vmbus_ring_buffer_init(
243		&new_channel->inbound,
244		in,
245		recv_ring_buffer_size);
246
247	/* Create sysctl tree for this channel */
248	vmbus_channel_sysctl_create(new_channel);
249
250	/**
251	 * Establish the gpadl for the ring buffer
252	 */
253	new_channel->ring_buffer_gpadl_handle = 0;
254
255	ret = hv_vmbus_channel_establish_gpadl(new_channel,
256		new_channel->outbound.ring_buffer,
257		send_ring_buffer_size + recv_ring_buffer_size,
258		&new_channel->ring_buffer_gpadl_handle);
259
260	/*
261	 * Open channel w/ the bufring GPADL on the target CPU.
262	 */
263	mh = vmbus_msghc_get(sc, sizeof(*req));
264	if (mh == NULL) {
265		device_printf(sc->vmbus_dev,
266		    "can not get msg hypercall for chopen(chan%u)\n",
267		    new_channel->ch_id);
268		return ENXIO;
269	}
270
271	req = vmbus_msghc_dataptr(mh);
272	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHOPEN;
273	req->chm_chanid = new_channel->ch_id;
274	req->chm_openid = new_channel->ch_id;
275	req->chm_gpadl = new_channel->ring_buffer_gpadl_handle;
276	req->chm_vcpuid = new_channel->target_vcpu;
277	req->chm_rxbr_pgofs = send_ring_buffer_size >> PAGE_SHIFT;
278	if (user_data_len)
279		memcpy(req->chm_udata, user_data, user_data_len);
280
281	ret = vmbus_msghc_exec(sc, mh);
282	if (ret != 0) {
283		device_printf(sc->vmbus_dev,
284		    "chopen(chan%u) msg hypercall exec failed: %d\n",
285		    new_channel->ch_id, ret);
286		vmbus_msghc_put(sc, mh);
287		return ret;
288	}
289
290	msg = vmbus_msghc_wait_result(sc, mh);
291	resp = (const struct vmbus_chanmsg_chopen_resp *)msg->msg_data;
292	status = resp->chm_status;
293
294	vmbus_msghc_put(sc, mh);
295
296	if (status == 0) {
297		new_channel->state = HV_CHANNEL_OPENED_STATE;
298		if (bootverbose) {
299			device_printf(sc->vmbus_dev, "chan%u opened\n",
300			    new_channel->ch_id);
301		}
302	} else {
303		device_printf(sc->vmbus_dev, "failed to open chan%u\n",
304		    new_channel->ch_id);
305		ret = ENXIO;
306	}
307	return (ret);
308}
309
310/**
311 * @brief Establish a GPADL for the specified buffer
312 */
313int
314hv_vmbus_channel_establish_gpadl(struct hv_vmbus_channel *channel,
315    void *contig_buffer, uint32_t size, uint32_t *gpadl0)
316{
317	struct vmbus_softc *sc = channel->vmbus_sc;
318	struct vmbus_msghc *mh;
319	struct vmbus_chanmsg_gpadl_conn *req;
320	const struct vmbus_message *msg;
321	size_t reqsz;
322	uint32_t gpadl, status;
323	int page_count, range_len, i, cnt, error;
324	uint64_t page_id, paddr;
325
326	/*
327	 * Preliminary checks.
328	 */
329
330	KASSERT((size & PAGE_MASK) == 0,
331	    ("invalid GPA size %u, not multiple page size", size));
332	page_count = size >> PAGE_SHIFT;
333
334	paddr = hv_get_phys_addr(contig_buffer);
335	KASSERT((paddr & PAGE_MASK) == 0,
336	    ("GPA is not page aligned %jx", (uintmax_t)paddr));
337	page_id = paddr >> PAGE_SHIFT;
338
339	range_len = __offsetof(struct vmbus_gpa_range, gpa_page[page_count]);
340	/*
341	 * We don't support multiple GPA ranges.
342	 */
343	if (range_len > UINT16_MAX) {
344		device_printf(sc->vmbus_dev, "GPA too large, %d pages\n",
345		    page_count);
346		return EOPNOTSUPP;
347	}
348
349	/*
350	 * Allocate GPADL id.
351	 */
352	gpadl = vmbus_gpadl_alloc(sc);
353	*gpadl0 = gpadl;
354
355	/*
356	 * Connect this GPADL to the target channel.
357	 *
358	 * NOTE:
359	 * Since each message can only hold small set of page
360	 * addresses, several messages may be required to
361	 * complete the connection.
362	 */
363	if (page_count > VMBUS_CHANMSG_GPADL_CONN_PGMAX)
364		cnt = VMBUS_CHANMSG_GPADL_CONN_PGMAX;
365	else
366		cnt = page_count;
367	page_count -= cnt;
368
369	reqsz = __offsetof(struct vmbus_chanmsg_gpadl_conn,
370	    chm_range.gpa_page[cnt]);
371	mh = vmbus_msghc_get(sc, reqsz);
372	if (mh == NULL) {
373		device_printf(sc->vmbus_dev,
374		    "can not get msg hypercall for gpadl->chan%u\n",
375		    channel->ch_id);
376		return EIO;
377	}
378
379	req = vmbus_msghc_dataptr(mh);
380	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_CONN;
381	req->chm_chanid = channel->ch_id;
382	req->chm_gpadl = gpadl;
383	req->chm_range_len = range_len;
384	req->chm_range_cnt = 1;
385	req->chm_range.gpa_len = size;
386	req->chm_range.gpa_ofs = 0;
387	for (i = 0; i < cnt; ++i)
388		req->chm_range.gpa_page[i] = page_id++;
389
390	error = vmbus_msghc_exec(sc, mh);
391	if (error) {
392		device_printf(sc->vmbus_dev,
393		    "gpadl->chan%u msg hypercall exec failed: %d\n",
394		    channel->ch_id, error);
395		vmbus_msghc_put(sc, mh);
396		return error;
397	}
398
399	while (page_count > 0) {
400		struct vmbus_chanmsg_gpadl_subconn *subreq;
401
402		if (page_count > VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX)
403			cnt = VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX;
404		else
405			cnt = page_count;
406		page_count -= cnt;
407
408		reqsz = __offsetof(struct vmbus_chanmsg_gpadl_subconn,
409		    chm_gpa_page[cnt]);
410		vmbus_msghc_reset(mh, reqsz);
411
412		subreq = vmbus_msghc_dataptr(mh);
413		subreq->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_SUBCONN;
414		subreq->chm_gpadl = gpadl;
415		for (i = 0; i < cnt; ++i)
416			subreq->chm_gpa_page[i] = page_id++;
417
418		vmbus_msghc_exec_noresult(mh);
419	}
420	KASSERT(page_count == 0, ("invalid page count %d", page_count));
421
422	msg = vmbus_msghc_wait_result(sc, mh);
423	status = ((const struct vmbus_chanmsg_gpadl_connresp *)
424	    msg->msg_data)->chm_status;
425
426	vmbus_msghc_put(sc, mh);
427
428	if (status != 0) {
429		device_printf(sc->vmbus_dev, "gpadl->chan%u failed: "
430		    "status %u\n", channel->ch_id, status);
431		return EIO;
432	} else {
433		if (bootverbose) {
434			device_printf(sc->vmbus_dev, "gpadl->chan%u "
435			    "succeeded\n", channel->ch_id);
436		}
437	}
438	return 0;
439}
440
441/*
442 * Disconnect the GPA from the target channel
443 */
444int
445hv_vmbus_channel_teardown_gpdal(struct hv_vmbus_channel *chan, uint32_t gpadl)
446{
447	struct vmbus_softc *sc = chan->vmbus_sc;
448	struct vmbus_msghc *mh;
449	struct vmbus_chanmsg_gpadl_disconn *req;
450	int error;
451
452	mh = vmbus_msghc_get(sc, sizeof(*req));
453	if (mh == NULL) {
454		device_printf(sc->vmbus_dev,
455		    "can not get msg hypercall for gpa x->chan%u\n",
456		    chan->ch_id);
457		return EBUSY;
458	}
459
460	req = vmbus_msghc_dataptr(mh);
461	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_DISCONN;
462	req->chm_chanid = chan->ch_id;
463	req->chm_gpadl = gpadl;
464
465	error = vmbus_msghc_exec(sc, mh);
466	if (error) {
467		device_printf(sc->vmbus_dev,
468		    "gpa x->chan%u msg hypercall exec failed: %d\n",
469		    chan->ch_id, error);
470		vmbus_msghc_put(sc, mh);
471		return error;
472	}
473
474	vmbus_msghc_wait_result(sc, mh);
475	/* Discard result; no useful information */
476	vmbus_msghc_put(sc, mh);
477
478	return 0;
479}
480
481static void
482hv_vmbus_channel_close_internal(hv_vmbus_channel *channel)
483{
484	struct vmbus_softc *sc = channel->vmbus_sc;
485	struct vmbus_msghc *mh;
486	struct vmbus_chanmsg_chclose *req;
487	struct taskqueue *rxq = channel->rxq;
488	int error;
489
490	channel->state = HV_CHANNEL_OPEN_STATE;
491	sysctl_ctx_free(&channel->ch_sysctl_ctx);
492
493	/*
494	 * set rxq to NULL to avoid more requests be scheduled
495	 */
496	channel->rxq = NULL;
497	taskqueue_drain(rxq, &channel->channel_task);
498	channel->on_channel_callback = NULL;
499
500	/**
501	 * Send a closing message
502	 */
503
504	mh = vmbus_msghc_get(sc, sizeof(*req));
505	if (mh == NULL) {
506		device_printf(sc->vmbus_dev,
507		    "can not get msg hypercall for chclose(chan%u)\n",
508		    channel->ch_id);
509		return;
510	}
511
512	req = vmbus_msghc_dataptr(mh);
513	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHCLOSE;
514	req->chm_chanid = channel->ch_id;
515
516	error = vmbus_msghc_exec_noresult(mh);
517	vmbus_msghc_put(sc, mh);
518
519	if (error) {
520		device_printf(sc->vmbus_dev,
521		    "chclose(chan%u) msg hypercall exec failed: %d\n",
522		    channel->ch_id, error);
523		return;
524	} else if (bootverbose) {
525		device_printf(sc->vmbus_dev, "close chan%u\n",
526		    channel->ch_id);
527	}
528
529	/* Tear down the gpadl for the channel's ring buffer */
530	if (channel->ring_buffer_gpadl_handle) {
531		hv_vmbus_channel_teardown_gpdal(channel,
532			channel->ring_buffer_gpadl_handle);
533	}
534
535	/* TODO: Send a msg to release the childRelId */
536
537	/* cleanup the ring buffers for this channel */
538	hv_ring_buffer_cleanup(&channel->outbound);
539	hv_ring_buffer_cleanup(&channel->inbound);
540
541	contigfree(channel->ring_buffer_pages, channel->ring_buffer_size,
542	    M_DEVBUF);
543}
544
545/**
546 * @brief Close the specified channel
547 */
548void
549hv_vmbus_channel_close(hv_vmbus_channel *channel)
550{
551	hv_vmbus_channel*	sub_channel;
552
553	if (channel->primary_channel != NULL) {
554		/*
555		 * We only close multi-channels when the primary is
556		 * closed.
557		 */
558		return;
559	}
560
561	/*
562	 * Close all multi-channels first.
563	 */
564	TAILQ_FOREACH(sub_channel, &channel->sc_list_anchor,
565	    sc_list_entry) {
566		if (sub_channel->state != HV_CHANNEL_OPENED_STATE)
567			continue;
568		hv_vmbus_channel_close_internal(sub_channel);
569	}
570	/*
571	 * Then close the primary channel.
572	 */
573	hv_vmbus_channel_close_internal(channel);
574}
575
576/**
577 * @brief Send the specified buffer on the given channel
578 */
579int
580hv_vmbus_channel_send_packet(
581	hv_vmbus_channel*	channel,
582	void*			buffer,
583	uint32_t		buffer_len,
584	uint64_t		request_id,
585	hv_vmbus_packet_type	type,
586	uint32_t		flags)
587{
588	int			ret = 0;
589	hv_vm_packet_descriptor	desc;
590	uint32_t		packet_len;
591	uint64_t		aligned_data;
592	uint32_t		packet_len_aligned;
593	boolean_t		need_sig;
594	hv_vmbus_sg_buffer_list	buffer_list[3];
595
596	packet_len = sizeof(hv_vm_packet_descriptor) + buffer_len;
597	packet_len_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
598	aligned_data = 0;
599
600	/* Setup the descriptor */
601	desc.type = type;   /* HV_VMBUS_PACKET_TYPE_DATA_IN_BAND;             */
602	desc.flags = flags; /* HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED */
603			    /* in 8-bytes granularity */
604	desc.data_offset8 = sizeof(hv_vm_packet_descriptor) >> 3;
605	desc.length8 = (uint16_t) (packet_len_aligned >> 3);
606	desc.transaction_id = request_id;
607
608	buffer_list[0].data = &desc;
609	buffer_list[0].length = sizeof(hv_vm_packet_descriptor);
610
611	buffer_list[1].data = buffer;
612	buffer_list[1].length = buffer_len;
613
614	buffer_list[2].data = &aligned_data;
615	buffer_list[2].length = packet_len_aligned - packet_len;
616
617	ret = hv_ring_buffer_write(&channel->outbound, buffer_list, 3,
618	    &need_sig);
619
620	/* TODO: We should determine if this is optional */
621	if (ret == 0 && need_sig)
622		vmbus_chan_send_event(channel);
623
624	return (ret);
625}
626
627/**
628 * @brief Send a range of single-page buffer packets using
629 * a GPADL Direct packet type
630 */
631int
632hv_vmbus_channel_send_packet_pagebuffer(
633	hv_vmbus_channel*	channel,
634	hv_vmbus_page_buffer	page_buffers[],
635	uint32_t		page_count,
636	void*			buffer,
637	uint32_t		buffer_len,
638	uint64_t		request_id)
639{
640
641	int					ret = 0;
642	boolean_t				need_sig;
643	uint32_t				packet_len;
644	uint32_t				page_buflen;
645	uint32_t				packetLen_aligned;
646	hv_vmbus_sg_buffer_list			buffer_list[4];
647	hv_vmbus_channel_packet_page_buffer	desc;
648	uint32_t				descSize;
649	uint64_t				alignedData = 0;
650
651	if (page_count > HV_MAX_PAGE_BUFFER_COUNT)
652		return (EINVAL);
653
654	/*
655	 * Adjust the size down since hv_vmbus_channel_packet_page_buffer
656	 *  is the largest size we support
657	 */
658	descSize = __offsetof(hv_vmbus_channel_packet_page_buffer, range);
659	page_buflen = sizeof(hv_vmbus_page_buffer) * page_count;
660	packet_len = descSize + page_buflen + buffer_len;
661	packetLen_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
662
663	/* Setup the descriptor */
664	desc.type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
665	desc.flags = HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
666	/* in 8-bytes granularity */
667	desc.data_offset8 = (descSize + page_buflen) >> 3;
668	desc.length8 = (uint16_t) (packetLen_aligned >> 3);
669	desc.transaction_id = request_id;
670	desc.range_count = page_count;
671
672	buffer_list[0].data = &desc;
673	buffer_list[0].length = descSize;
674
675	buffer_list[1].data = page_buffers;
676	buffer_list[1].length = page_buflen;
677
678	buffer_list[2].data = buffer;
679	buffer_list[2].length = buffer_len;
680
681	buffer_list[3].data = &alignedData;
682	buffer_list[3].length = packetLen_aligned - packet_len;
683
684	ret = hv_ring_buffer_write(&channel->outbound, buffer_list, 4,
685	    &need_sig);
686
687	/* TODO: We should determine if this is optional */
688	if (ret == 0 && need_sig)
689		vmbus_chan_send_event(channel);
690
691	return (ret);
692}
693
694/**
695 * @brief Send a multi-page buffer packet using a GPADL Direct packet type
696 */
697int
698hv_vmbus_channel_send_packet_multipagebuffer(
699	hv_vmbus_channel*		channel,
700	hv_vmbus_multipage_buffer*	multi_page_buffer,
701	void*				buffer,
702	uint32_t			buffer_len,
703	uint64_t			request_id)
704{
705
706	int			ret = 0;
707	uint32_t		desc_size;
708	boolean_t		need_sig;
709	uint32_t		packet_len;
710	uint32_t		packet_len_aligned;
711	uint32_t		pfn_count;
712	uint64_t		aligned_data = 0;
713	hv_vmbus_sg_buffer_list	buffer_list[3];
714	hv_vmbus_channel_packet_multipage_buffer desc;
715
716	pfn_count =
717	    HV_NUM_PAGES_SPANNED(
718		    multi_page_buffer->offset,
719		    multi_page_buffer->length);
720
721	if ((pfn_count == 0) || (pfn_count > HV_MAX_MULTIPAGE_BUFFER_COUNT))
722	    return (EINVAL);
723	/*
724	 * Adjust the size down since hv_vmbus_channel_packet_multipage_buffer
725	 * is the largest size we support
726	 */
727	desc_size =
728	    sizeof(hv_vmbus_channel_packet_multipage_buffer) -
729		    ((HV_MAX_MULTIPAGE_BUFFER_COUNT - pfn_count) *
730			sizeof(uint64_t));
731	packet_len = desc_size + buffer_len;
732	packet_len_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
733
734	/*
735	 * Setup the descriptor
736	 */
737	desc.type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
738	desc.flags = HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
739	desc.data_offset8 = desc_size >> 3; /* in 8-bytes granularity */
740	desc.length8 = (uint16_t) (packet_len_aligned >> 3);
741	desc.transaction_id = request_id;
742	desc.range_count = 1;
743
744	desc.range.length = multi_page_buffer->length;
745	desc.range.offset = multi_page_buffer->offset;
746
747	memcpy(desc.range.pfn_array, multi_page_buffer->pfn_array,
748		pfn_count * sizeof(uint64_t));
749
750	buffer_list[0].data = &desc;
751	buffer_list[0].length = desc_size;
752
753	buffer_list[1].data = buffer;
754	buffer_list[1].length = buffer_len;
755
756	buffer_list[2].data = &aligned_data;
757	buffer_list[2].length = packet_len_aligned - packet_len;
758
759	ret = hv_ring_buffer_write(&channel->outbound, buffer_list, 3,
760	    &need_sig);
761
762	/* TODO: We should determine if this is optional */
763	if (ret == 0 && need_sig)
764		vmbus_chan_send_event(channel);
765
766	return (ret);
767}
768
769/**
770 * @brief Retrieve the user packet on the specified channel
771 */
772int
773hv_vmbus_channel_recv_packet(
774	hv_vmbus_channel*	channel,
775	void*			Buffer,
776	uint32_t		buffer_len,
777	uint32_t*		buffer_actual_len,
778	uint64_t*		request_id)
779{
780	int			ret;
781	uint32_t		user_len;
782	uint32_t		packet_len;
783	hv_vm_packet_descriptor	desc;
784
785	*buffer_actual_len = 0;
786	*request_id = 0;
787
788	ret = hv_ring_buffer_peek(&channel->inbound, &desc,
789		sizeof(hv_vm_packet_descriptor));
790	if (ret != 0)
791		return (0);
792
793	packet_len = desc.length8 << 3;
794	user_len = packet_len - (desc.data_offset8 << 3);
795
796	*buffer_actual_len = user_len;
797
798	if (user_len > buffer_len)
799		return (EINVAL);
800
801	*request_id = desc.transaction_id;
802
803	/* Copy over the packet to the user buffer */
804	ret = hv_ring_buffer_read(&channel->inbound, Buffer, user_len,
805		(desc.data_offset8 << 3));
806
807	return (0);
808}
809
810/**
811 * @brief Retrieve the raw packet on the specified channel
812 */
813int
814hv_vmbus_channel_recv_packet_raw(
815	hv_vmbus_channel*	channel,
816	void*			buffer,
817	uint32_t		buffer_len,
818	uint32_t*		buffer_actual_len,
819	uint64_t*		request_id)
820{
821	int		ret;
822	uint32_t	packetLen;
823	hv_vm_packet_descriptor	desc;
824
825	*buffer_actual_len = 0;
826	*request_id = 0;
827
828	ret = hv_ring_buffer_peek(
829		&channel->inbound, &desc,
830		sizeof(hv_vm_packet_descriptor));
831
832	if (ret != 0)
833	    return (0);
834
835	packetLen = desc.length8 << 3;
836	*buffer_actual_len = packetLen;
837
838	if (packetLen > buffer_len)
839	    return (ENOBUFS);
840
841	*request_id = desc.transaction_id;
842
843	/* Copy over the entire packet to the user buffer */
844	ret = hv_ring_buffer_read(&channel->inbound, buffer, packetLen, 0);
845
846	return (0);
847}
848
849static void
850vmbus_chan_task(void *xchan, int pending __unused)
851{
852	struct hv_vmbus_channel *chan = xchan;
853	void (*callback)(void *);
854	void *arg;
855
856	arg = chan->channel_callback_context;
857	callback = chan->on_channel_callback;
858
859	/*
860	 * Optimize host to guest signaling by ensuring:
861	 * 1. While reading the channel, we disable interrupts from
862	 *    host.
863	 * 2. Ensure that we process all posted messages from the host
864	 *    before returning from this callback.
865	 * 3. Once we return, enable signaling from the host. Once this
866	 *    state is set we check to see if additional packets are
867	 *    available to read. In this case we repeat the process.
868	 *
869	 * NOTE: Interrupt has been disabled in the ISR.
870	 */
871	for (;;) {
872		uint32_t left;
873
874		callback(arg);
875
876		left = hv_ring_buffer_read_end(&chan->inbound);
877		if (left == 0) {
878			/* No more data in RX bufring; done */
879			break;
880		}
881		hv_ring_buffer_read_begin(&chan->inbound);
882	}
883}
884
885static void
886vmbus_chan_task_nobatch(void *xchan, int pending __unused)
887{
888	struct hv_vmbus_channel *chan = xchan;
889
890	chan->on_channel_callback(chan->channel_callback_context);
891}
892
893static __inline void
894vmbus_event_flags_proc(struct vmbus_softc *sc, volatile u_long *event_flags,
895    int flag_cnt)
896{
897	int f;
898
899	for (f = 0; f < flag_cnt; ++f) {
900		uint32_t chid_base;
901		u_long flags;
902		int chid_ofs;
903
904		if (event_flags[f] == 0)
905			continue;
906
907		flags = atomic_swap_long(&event_flags[f], 0);
908		chid_base = f << VMBUS_EVTFLAG_SHIFT;
909
910		while ((chid_ofs = ffsl(flags)) != 0) {
911			struct hv_vmbus_channel *channel;
912
913			--chid_ofs; /* NOTE: ffsl is 1-based */
914			flags &= ~(1UL << chid_ofs);
915
916			channel = sc->vmbus_chmap[chid_base + chid_ofs];
917
918			/* if channel is closed or closing */
919			if (channel == NULL || channel->rxq == NULL)
920				continue;
921
922			if (channel->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD)
923				hv_ring_buffer_read_begin(&channel->inbound);
924			taskqueue_enqueue(channel->rxq, &channel->channel_task);
925		}
926	}
927}
928
929void
930vmbus_event_proc(struct vmbus_softc *sc, int cpu)
931{
932	struct vmbus_evtflags *eventf;
933
934	/*
935	 * On Host with Win8 or above, the event page can be checked directly
936	 * to get the id of the channel that has the pending interrupt.
937	 */
938	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
939	vmbus_event_flags_proc(sc, eventf->evt_flags,
940	    VMBUS_PCPU_GET(sc, event_flags_cnt, cpu));
941}
942
943void
944vmbus_event_proc_compat(struct vmbus_softc *sc, int cpu)
945{
946	struct vmbus_evtflags *eventf;
947
948	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
949	if (atomic_testandclear_long(&eventf->evt_flags[0], 0)) {
950		vmbus_event_flags_proc(sc, sc->vmbus_rx_evtflags,
951		    VMBUS_CHAN_MAX_COMPAT >> VMBUS_EVTFLAG_SHIFT);
952	}
953}
954
955static void
956vmbus_chan_update_evtflagcnt(struct vmbus_softc *sc,
957    const struct hv_vmbus_channel *chan)
958{
959	volatile int *flag_cnt_ptr;
960	int flag_cnt;
961
962	flag_cnt = (chan->ch_id / VMBUS_EVTFLAG_LEN) + 1;
963	flag_cnt_ptr = VMBUS_PCPU_PTR(sc, event_flags_cnt, chan->target_cpu);
964
965	for (;;) {
966		int old_flag_cnt;
967
968		old_flag_cnt = *flag_cnt_ptr;
969		if (old_flag_cnt >= flag_cnt)
970			break;
971		if (atomic_cmpset_int(flag_cnt_ptr, old_flag_cnt, flag_cnt)) {
972			if (bootverbose) {
973				device_printf(sc->vmbus_dev,
974				    "channel%u update cpu%d flag_cnt to %d\n",
975				    chan->ch_id,
976				    chan->target_cpu, flag_cnt);
977			}
978			break;
979		}
980	}
981}
982