vmbus_chan.c revision 302875
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 302875 2016-07-15 06:16:39Z 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/include/hyperv_busdma.h>
49#include <dev/hyperv/vmbus/hv_vmbus_priv.h>
50#include <dev/hyperv/vmbus/hyperv_var.h>
51#include <dev/hyperv/vmbus/vmbus_reg.h>
52#include <dev/hyperv/vmbus/vmbus_var.h>
53
54static void 	vmbus_chan_send_event(hv_vmbus_channel* channel);
55static void	vmbus_chan_update_evtflagcnt(struct vmbus_softc *,
56		    const struct hv_vmbus_channel *);
57
58static void	vmbus_chan_task(void *, int);
59static void	vmbus_chan_task_nobatch(void *, int);
60static void	vmbus_chan_detach_task(void *, int);
61
62static void	vmbus_chan_msgproc_choffer(struct vmbus_softc *,
63		    const struct vmbus_message *);
64static void	vmbus_chan_msgproc_chrescind(struct vmbus_softc *,
65		    const struct vmbus_message *);
66
67/*
68 * Vmbus channel message processing.
69 */
70static const vmbus_chanmsg_proc_t
71vmbus_chan_msgprocs[VMBUS_CHANMSG_TYPE_MAX] = {
72	VMBUS_CHANMSG_PROC(CHOFFER,	vmbus_chan_msgproc_choffer),
73	VMBUS_CHANMSG_PROC(CHRESCIND,	vmbus_chan_msgproc_chrescind),
74
75	VMBUS_CHANMSG_PROC_WAKEUP(CHOPEN_RESP),
76	VMBUS_CHANMSG_PROC_WAKEUP(GPADL_CONNRESP),
77	VMBUS_CHANMSG_PROC_WAKEUP(GPADL_DISCONNRESP)
78};
79
80/**
81 *  @brief Trigger an event notification on the specified channel
82 */
83static void
84vmbus_chan_send_event(hv_vmbus_channel *channel)
85{
86	struct vmbus_softc *sc = channel->vmbus_sc;
87	uint32_t chanid = channel->ch_id;
88
89	atomic_set_long(&sc->vmbus_tx_evtflags[chanid >> VMBUS_EVTFLAG_SHIFT],
90	    1UL << (chanid & VMBUS_EVTFLAG_MASK));
91
92	if (channel->ch_flags & VMBUS_CHAN_FLAG_HASMNF) {
93		atomic_set_int(
94		&sc->vmbus_mnf2->mnf_trigs[channel->ch_montrig_idx].mt_pending,
95		channel->ch_montrig_mask);
96	} else {
97		hypercall_signal_event(channel->ch_monprm_dma.hv_paddr);
98	}
99}
100
101static int
102vmbus_channel_sysctl_monalloc(SYSCTL_HANDLER_ARGS)
103{
104	struct hv_vmbus_channel *chan = arg1;
105	int alloc = 0;
106
107	if (chan->ch_flags & VMBUS_CHAN_FLAG_HASMNF)
108		alloc = 1;
109	return sysctl_handle_int(oidp, &alloc, 0, req);
110}
111
112static void
113vmbus_channel_sysctl_create(hv_vmbus_channel* channel)
114{
115	device_t dev;
116	struct sysctl_oid *devch_sysctl;
117	struct sysctl_oid *devch_id_sysctl, *devch_sub_sysctl;
118	struct sysctl_oid *devch_id_in_sysctl, *devch_id_out_sysctl;
119	struct sysctl_ctx_list *ctx;
120	uint32_t ch_id;
121	uint16_t sub_ch_id;
122	char name[16];
123
124	hv_vmbus_channel* primary_ch = channel->ch_prichan;
125
126	if (primary_ch == NULL) {
127		dev = channel->ch_dev;
128		ch_id = channel->ch_id;
129	} else {
130		dev = primary_ch->ch_dev;
131		ch_id = primary_ch->ch_id;
132		sub_ch_id = channel->ch_subidx;
133	}
134	ctx = &channel->ch_sysctl_ctx;
135	sysctl_ctx_init(ctx);
136	/* This creates dev.DEVNAME.DEVUNIT.channel tree */
137	devch_sysctl = SYSCTL_ADD_NODE(ctx,
138		    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
139		    OID_AUTO, "channel", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
140	/* This creates dev.DEVNAME.DEVUNIT.channel.CHANID tree */
141	snprintf(name, sizeof(name), "%d", ch_id);
142	devch_id_sysctl = SYSCTL_ADD_NODE(ctx,
143	    	    SYSCTL_CHILDREN(devch_sysctl),
144	    	    OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
145
146	if (primary_ch != NULL) {
147		devch_sub_sysctl = SYSCTL_ADD_NODE(ctx,
148			SYSCTL_CHILDREN(devch_id_sysctl),
149			OID_AUTO, "sub", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
150		snprintf(name, sizeof(name), "%d", sub_ch_id);
151		devch_id_sysctl = SYSCTL_ADD_NODE(ctx,
152			SYSCTL_CHILDREN(devch_sub_sysctl),
153			OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
154
155		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(devch_id_sysctl),
156		    OID_AUTO, "chanid", CTLFLAG_RD,
157		    &channel->ch_id, 0, "channel id");
158	}
159	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(devch_id_sysctl), OID_AUTO,
160	    "cpu", CTLFLAG_RD, &channel->ch_cpuid, 0, "owner CPU id");
161	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(devch_id_sysctl), OID_AUTO,
162	    "monitor_allocated", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
163	    channel, 0, vmbus_channel_sysctl_monalloc, "I",
164	    "is monitor allocated to this channel");
165
166	devch_id_in_sysctl = SYSCTL_ADD_NODE(ctx,
167                    SYSCTL_CHILDREN(devch_id_sysctl),
168                    OID_AUTO,
169		    "in",
170		    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
171	devch_id_out_sysctl = SYSCTL_ADD_NODE(ctx,
172                    SYSCTL_CHILDREN(devch_id_sysctl),
173                    OID_AUTO,
174		    "out",
175		    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
176	hv_ring_buffer_stat(ctx,
177		SYSCTL_CHILDREN(devch_id_in_sysctl),
178		&(channel->inbound),
179		"inbound ring buffer stats");
180	hv_ring_buffer_stat(ctx,
181		SYSCTL_CHILDREN(devch_id_out_sysctl),
182		&(channel->outbound),
183		"outbound ring buffer stats");
184}
185
186/**
187 * @brief Open the specified channel
188 */
189int
190hv_vmbus_channel_open(
191	hv_vmbus_channel*		new_channel,
192	uint32_t			send_ring_buffer_size,
193	uint32_t			recv_ring_buffer_size,
194	void*				user_data,
195	uint32_t			user_data_len,
196	vmbus_chan_callback_t		cb,
197	void				*cbarg)
198{
199	struct vmbus_softc *sc = new_channel->vmbus_sc;
200	const struct vmbus_chanmsg_chopen_resp *resp;
201	const struct vmbus_message *msg;
202	struct vmbus_chanmsg_chopen *req;
203	struct vmbus_msghc *mh;
204	uint32_t status;
205	int ret = 0;
206	uint8_t *br;
207
208	if (user_data_len > VMBUS_CHANMSG_CHOPEN_UDATA_SIZE) {
209		device_printf(sc->vmbus_dev,
210		    "invalid udata len %u for chan%u\n",
211		    user_data_len, new_channel->ch_id);
212		return EINVAL;
213	}
214	KASSERT((send_ring_buffer_size & PAGE_MASK) == 0,
215	    ("send bufring size is not multiple page"));
216	KASSERT((recv_ring_buffer_size & PAGE_MASK) == 0,
217	    ("recv bufring size is not multiple page"));
218
219	if (atomic_testandset_int(&new_channel->ch_stflags,
220	    VMBUS_CHAN_ST_OPENED_SHIFT))
221		panic("double-open chan%u", new_channel->ch_id);
222
223	new_channel->ch_cb = cb;
224	new_channel->ch_cbarg = cbarg;
225
226	vmbus_chan_update_evtflagcnt(sc, new_channel);
227
228	new_channel->ch_tq = VMBUS_PCPU_GET(new_channel->vmbus_sc, event_tq,
229	    new_channel->ch_cpuid);
230	if (new_channel->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD) {
231		TASK_INIT(&new_channel->ch_task, 0, vmbus_chan_task,
232		    new_channel);
233	} else {
234		TASK_INIT(&new_channel->ch_task, 0, vmbus_chan_task_nobatch,
235		    new_channel);
236	}
237
238	/*
239	 * Allocate the TX+RX bufrings.
240	 * XXX should use ch_dev dtag
241	 */
242	br = hyperv_dmamem_alloc(bus_get_dma_tag(sc->vmbus_dev),
243	    PAGE_SIZE, 0, send_ring_buffer_size + recv_ring_buffer_size,
244	    &new_channel->ch_bufring_dma, BUS_DMA_WAITOK | BUS_DMA_ZERO);
245	if (br == NULL) {
246		device_printf(sc->vmbus_dev, "bufring allocation failed\n");
247		ret = ENOMEM;
248		goto failed;
249	}
250	new_channel->ch_bufring = br;
251
252	/* TX bufring comes first */
253	hv_vmbus_ring_buffer_init(&new_channel->outbound,
254	    br, send_ring_buffer_size);
255	/* RX bufring immediately follows TX bufring */
256	hv_vmbus_ring_buffer_init(&new_channel->inbound,
257	    br + send_ring_buffer_size, recv_ring_buffer_size);
258
259	/* Create sysctl tree for this channel */
260	vmbus_channel_sysctl_create(new_channel);
261
262	/*
263	 * Connect the bufrings, both RX and TX, to this channel.
264	 */
265	ret = vmbus_chan_gpadl_connect(new_channel,
266		new_channel->ch_bufring_dma.hv_paddr,
267		send_ring_buffer_size + recv_ring_buffer_size,
268		&new_channel->ch_bufring_gpadl);
269	if (ret != 0) {
270		device_printf(sc->vmbus_dev,
271		    "failed to connect bufring GPADL to chan%u\n",
272		    new_channel->ch_id);
273		goto failed;
274	}
275
276	/*
277	 * Open channel w/ the bufring GPADL on the target CPU.
278	 */
279	mh = vmbus_msghc_get(sc, sizeof(*req));
280	if (mh == NULL) {
281		device_printf(sc->vmbus_dev,
282		    "can not get msg hypercall for chopen(chan%u)\n",
283		    new_channel->ch_id);
284		ret = ENXIO;
285		goto failed;
286	}
287
288	req = vmbus_msghc_dataptr(mh);
289	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHOPEN;
290	req->chm_chanid = new_channel->ch_id;
291	req->chm_openid = new_channel->ch_id;
292	req->chm_gpadl = new_channel->ch_bufring_gpadl;
293	req->chm_vcpuid = new_channel->ch_vcpuid;
294	req->chm_rxbr_pgofs = send_ring_buffer_size >> PAGE_SHIFT;
295	if (user_data_len)
296		memcpy(req->chm_udata, user_data, user_data_len);
297
298	ret = vmbus_msghc_exec(sc, mh);
299	if (ret != 0) {
300		device_printf(sc->vmbus_dev,
301		    "chopen(chan%u) msg hypercall exec failed: %d\n",
302		    new_channel->ch_id, ret);
303		vmbus_msghc_put(sc, mh);
304		goto failed;
305	}
306
307	msg = vmbus_msghc_wait_result(sc, mh);
308	resp = (const struct vmbus_chanmsg_chopen_resp *)msg->msg_data;
309	status = resp->chm_status;
310
311	vmbus_msghc_put(sc, mh);
312
313	if (status == 0) {
314		if (bootverbose) {
315			device_printf(sc->vmbus_dev, "chan%u opened\n",
316			    new_channel->ch_id);
317		}
318		return 0;
319	}
320
321	device_printf(sc->vmbus_dev, "failed to open chan%u\n",
322	    new_channel->ch_id);
323	ret = ENXIO;
324
325failed:
326	if (new_channel->ch_bufring_gpadl) {
327		hv_vmbus_channel_teardown_gpdal(new_channel,
328		    new_channel->ch_bufring_gpadl);
329		new_channel->ch_bufring_gpadl = 0;
330	}
331	if (new_channel->ch_bufring != NULL) {
332		hyperv_dmamem_free(&new_channel->ch_bufring_dma,
333		    new_channel->ch_bufring);
334		new_channel->ch_bufring = NULL;
335	}
336	atomic_clear_int(&new_channel->ch_stflags, VMBUS_CHAN_ST_OPENED);
337	return ret;
338}
339
340/**
341 * @brief Establish a GPADL for the specified buffer
342 */
343int
344hv_vmbus_channel_establish_gpadl(struct hv_vmbus_channel *channel,
345    void *contig_buffer, uint32_t size, uint32_t *gpadl)
346{
347	return vmbus_chan_gpadl_connect(channel,
348	    hv_get_phys_addr(contig_buffer), size, gpadl);
349}
350
351int
352vmbus_chan_gpadl_connect(struct hv_vmbus_channel *chan, bus_addr_t paddr,
353    int size, uint32_t *gpadl0)
354{
355	struct vmbus_softc *sc = chan->vmbus_sc;
356	struct vmbus_msghc *mh;
357	struct vmbus_chanmsg_gpadl_conn *req;
358	const struct vmbus_message *msg;
359	size_t reqsz;
360	uint32_t gpadl, status;
361	int page_count, range_len, i, cnt, error;
362	uint64_t page_id;
363
364	/*
365	 * Preliminary checks.
366	 */
367
368	KASSERT((size & PAGE_MASK) == 0,
369	    ("invalid GPA size %d, not multiple page size", size));
370	page_count = size >> PAGE_SHIFT;
371
372	KASSERT((paddr & PAGE_MASK) == 0,
373	    ("GPA is not page aligned %jx", (uintmax_t)paddr));
374	page_id = paddr >> PAGE_SHIFT;
375
376	range_len = __offsetof(struct vmbus_gpa_range, gpa_page[page_count]);
377	/*
378	 * We don't support multiple GPA ranges.
379	 */
380	if (range_len > UINT16_MAX) {
381		device_printf(sc->vmbus_dev, "GPA too large, %d pages\n",
382		    page_count);
383		return EOPNOTSUPP;
384	}
385
386	/*
387	 * Allocate GPADL id.
388	 */
389	gpadl = vmbus_gpadl_alloc(sc);
390	*gpadl0 = gpadl;
391
392	/*
393	 * Connect this GPADL to the target channel.
394	 *
395	 * NOTE:
396	 * Since each message can only hold small set of page
397	 * addresses, several messages may be required to
398	 * complete the connection.
399	 */
400	if (page_count > VMBUS_CHANMSG_GPADL_CONN_PGMAX)
401		cnt = VMBUS_CHANMSG_GPADL_CONN_PGMAX;
402	else
403		cnt = page_count;
404	page_count -= cnt;
405
406	reqsz = __offsetof(struct vmbus_chanmsg_gpadl_conn,
407	    chm_range.gpa_page[cnt]);
408	mh = vmbus_msghc_get(sc, reqsz);
409	if (mh == NULL) {
410		device_printf(sc->vmbus_dev,
411		    "can not get msg hypercall for gpadl->chan%u\n",
412		    chan->ch_id);
413		return EIO;
414	}
415
416	req = vmbus_msghc_dataptr(mh);
417	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_CONN;
418	req->chm_chanid = chan->ch_id;
419	req->chm_gpadl = gpadl;
420	req->chm_range_len = range_len;
421	req->chm_range_cnt = 1;
422	req->chm_range.gpa_len = size;
423	req->chm_range.gpa_ofs = 0;
424	for (i = 0; i < cnt; ++i)
425		req->chm_range.gpa_page[i] = page_id++;
426
427	error = vmbus_msghc_exec(sc, mh);
428	if (error) {
429		device_printf(sc->vmbus_dev,
430		    "gpadl->chan%u msg hypercall exec failed: %d\n",
431		    chan->ch_id, error);
432		vmbus_msghc_put(sc, mh);
433		return error;
434	}
435
436	while (page_count > 0) {
437		struct vmbus_chanmsg_gpadl_subconn *subreq;
438
439		if (page_count > VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX)
440			cnt = VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX;
441		else
442			cnt = page_count;
443		page_count -= cnt;
444
445		reqsz = __offsetof(struct vmbus_chanmsg_gpadl_subconn,
446		    chm_gpa_page[cnt]);
447		vmbus_msghc_reset(mh, reqsz);
448
449		subreq = vmbus_msghc_dataptr(mh);
450		subreq->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_SUBCONN;
451		subreq->chm_gpadl = gpadl;
452		for (i = 0; i < cnt; ++i)
453			subreq->chm_gpa_page[i] = page_id++;
454
455		vmbus_msghc_exec_noresult(mh);
456	}
457	KASSERT(page_count == 0, ("invalid page count %d", page_count));
458
459	msg = vmbus_msghc_wait_result(sc, mh);
460	status = ((const struct vmbus_chanmsg_gpadl_connresp *)
461	    msg->msg_data)->chm_status;
462
463	vmbus_msghc_put(sc, mh);
464
465	if (status != 0) {
466		device_printf(sc->vmbus_dev, "gpadl->chan%u failed: "
467		    "status %u\n", chan->ch_id, status);
468		return EIO;
469	} else {
470		if (bootverbose) {
471			device_printf(sc->vmbus_dev, "gpadl->chan%u "
472			    "succeeded\n", chan->ch_id);
473		}
474	}
475	return 0;
476}
477
478/*
479 * Disconnect the GPA from the target channel
480 */
481int
482hv_vmbus_channel_teardown_gpdal(struct hv_vmbus_channel *chan, uint32_t gpadl)
483{
484	struct vmbus_softc *sc = chan->vmbus_sc;
485	struct vmbus_msghc *mh;
486	struct vmbus_chanmsg_gpadl_disconn *req;
487	int error;
488
489	mh = vmbus_msghc_get(sc, sizeof(*req));
490	if (mh == NULL) {
491		device_printf(sc->vmbus_dev,
492		    "can not get msg hypercall for gpa x->chan%u\n",
493		    chan->ch_id);
494		return EBUSY;
495	}
496
497	req = vmbus_msghc_dataptr(mh);
498	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_DISCONN;
499	req->chm_chanid = chan->ch_id;
500	req->chm_gpadl = gpadl;
501
502	error = vmbus_msghc_exec(sc, mh);
503	if (error) {
504		device_printf(sc->vmbus_dev,
505		    "gpa x->chan%u msg hypercall exec failed: %d\n",
506		    chan->ch_id, error);
507		vmbus_msghc_put(sc, mh);
508		return error;
509	}
510
511	vmbus_msghc_wait_result(sc, mh);
512	/* Discard result; no useful information */
513	vmbus_msghc_put(sc, mh);
514
515	return 0;
516}
517
518static void
519hv_vmbus_channel_close_internal(hv_vmbus_channel *channel)
520{
521	struct vmbus_softc *sc = channel->vmbus_sc;
522	struct vmbus_msghc *mh;
523	struct vmbus_chanmsg_chclose *req;
524	struct taskqueue *tq = channel->ch_tq;
525	int error;
526
527	/* TODO: stringent check */
528	atomic_clear_int(&channel->ch_stflags, VMBUS_CHAN_ST_OPENED);
529
530	sysctl_ctx_free(&channel->ch_sysctl_ctx);
531
532	/*
533	 * Set ch_tq to NULL to avoid more requests be scheduled
534	 */
535	channel->ch_tq = NULL;
536	taskqueue_drain(tq, &channel->ch_task);
537	channel->ch_cb = NULL;
538
539	/**
540	 * Send a closing message
541	 */
542
543	mh = vmbus_msghc_get(sc, sizeof(*req));
544	if (mh == NULL) {
545		device_printf(sc->vmbus_dev,
546		    "can not get msg hypercall for chclose(chan%u)\n",
547		    channel->ch_id);
548		return;
549	}
550
551	req = vmbus_msghc_dataptr(mh);
552	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHCLOSE;
553	req->chm_chanid = channel->ch_id;
554
555	error = vmbus_msghc_exec_noresult(mh);
556	vmbus_msghc_put(sc, mh);
557
558	if (error) {
559		device_printf(sc->vmbus_dev,
560		    "chclose(chan%u) msg hypercall exec failed: %d\n",
561		    channel->ch_id, error);
562		return;
563	} else if (bootverbose) {
564		device_printf(sc->vmbus_dev, "close chan%u\n",
565		    channel->ch_id);
566	}
567
568	/* Tear down the gpadl for the channel's ring buffer */
569	if (channel->ch_bufring_gpadl) {
570		hv_vmbus_channel_teardown_gpdal(channel,
571		    channel->ch_bufring_gpadl);
572		channel->ch_bufring_gpadl = 0;
573	}
574
575	/* TODO: Send a msg to release the childRelId */
576
577	/* cleanup the ring buffers for this channel */
578	hv_ring_buffer_cleanup(&channel->outbound);
579	hv_ring_buffer_cleanup(&channel->inbound);
580
581	if (channel->ch_bufring != NULL) {
582		hyperv_dmamem_free(&channel->ch_bufring_dma,
583		    channel->ch_bufring);
584		channel->ch_bufring = NULL;
585	}
586}
587
588/*
589 * Caller should make sure that all sub-channels have
590 * been added to 'chan' and all to-be-closed channels
591 * are not being opened.
592 */
593void
594hv_vmbus_channel_close(struct hv_vmbus_channel *chan)
595{
596	int subchan_cnt;
597
598	if (!VMBUS_CHAN_ISPRIMARY(chan)) {
599		/*
600		 * Sub-channel is closed when its primary channel
601		 * is closed; done.
602		 */
603		return;
604	}
605
606	/*
607	 * Close all sub-channels, if any.
608	 */
609	subchan_cnt = chan->ch_subchan_cnt;
610	if (subchan_cnt > 0) {
611		struct hv_vmbus_channel **subchan;
612		int i;
613
614		subchan = vmbus_get_subchan(chan, subchan_cnt);
615		for (i = 0; i < subchan_cnt; ++i)
616			hv_vmbus_channel_close_internal(subchan[i]);
617		vmbus_rel_subchan(subchan, subchan_cnt);
618	}
619
620	/* Then close the primary channel. */
621	hv_vmbus_channel_close_internal(chan);
622}
623
624/**
625 * @brief Send the specified buffer on the given channel
626 */
627int
628hv_vmbus_channel_send_packet(
629	hv_vmbus_channel*	channel,
630	void*			buffer,
631	uint32_t		buffer_len,
632	uint64_t		request_id,
633	hv_vmbus_packet_type	type,
634	uint32_t		flags)
635{
636	int			ret = 0;
637	struct vmbus_chanpkt pkt;
638	uint32_t		packet_len;
639	uint64_t		aligned_data;
640	uint32_t		packet_len_aligned;
641	boolean_t		need_sig;
642	struct iovec		iov[3];
643
644	packet_len = sizeof(pkt) + buffer_len;
645	packet_len_aligned = roundup2(packet_len, VMBUS_CHANPKT_SIZE_ALIGN);
646	aligned_data = 0;
647
648	/*
649	 * Setup channel packet.
650	 */
651	pkt.cp_hdr.cph_type = type;
652	pkt.cp_hdr.cph_flags = flags;
653	pkt.cp_hdr.cph_data_ofs = sizeof(pkt) >> VMBUS_CHANPKT_SIZE_SHIFT;
654	pkt.cp_hdr.cph_len = packet_len_aligned >> VMBUS_CHANPKT_SIZE_SHIFT;
655	pkt.cp_hdr.cph_xactid = request_id;
656
657	iov[0].iov_base = &pkt;
658	iov[0].iov_len = sizeof(pkt);
659
660	iov[1].iov_base = buffer;
661	iov[1].iov_len = buffer_len;
662
663	iov[2].iov_base = &aligned_data;
664	iov[2].iov_len = packet_len_aligned - packet_len;
665
666	ret = hv_ring_buffer_write(&channel->outbound, iov, 3, &need_sig);
667
668	/* TODO: We should determine if this is optional */
669	if (ret == 0 && need_sig)
670		vmbus_chan_send_event(channel);
671
672	return (ret);
673}
674
675/**
676 * @brief Send a range of single-page buffer packets using
677 * a GPADL Direct packet type
678 */
679int
680hv_vmbus_channel_send_packet_pagebuffer(
681	hv_vmbus_channel*	channel,
682	hv_vmbus_page_buffer	page_buffers[],
683	uint32_t		page_count,
684	void*			buffer,
685	uint32_t		buffer_len,
686	uint64_t		request_id)
687{
688
689	int					ret = 0;
690	boolean_t				need_sig;
691	uint32_t				packet_len;
692	uint32_t				page_buflen;
693	uint32_t				packetLen_aligned;
694	struct iovec				iov[4];
695	hv_vmbus_channel_packet_page_buffer	desc;
696	uint32_t				descSize;
697	uint64_t				alignedData = 0;
698
699	if (page_count > HV_MAX_PAGE_BUFFER_COUNT)
700		return (EINVAL);
701
702	/*
703	 * Adjust the size down since hv_vmbus_channel_packet_page_buffer
704	 *  is the largest size we support
705	 */
706	descSize = __offsetof(hv_vmbus_channel_packet_page_buffer, range);
707	page_buflen = sizeof(hv_vmbus_page_buffer) * page_count;
708	packet_len = descSize + page_buflen + buffer_len;
709	packetLen_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
710
711	/* Setup the descriptor */
712	desc.type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
713	desc.flags = HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
714	/* in 8-bytes granularity */
715	desc.data_offset8 = (descSize + page_buflen) >> 3;
716	desc.length8 = (uint16_t) (packetLen_aligned >> 3);
717	desc.transaction_id = request_id;
718	desc.range_count = page_count;
719
720	iov[0].iov_base = &desc;
721	iov[0].iov_len = descSize;
722
723	iov[1].iov_base = page_buffers;
724	iov[1].iov_len = page_buflen;
725
726	iov[2].iov_base = buffer;
727	iov[2].iov_len = buffer_len;
728
729	iov[3].iov_base = &alignedData;
730	iov[3].iov_len = packetLen_aligned - packet_len;
731
732	ret = hv_ring_buffer_write(&channel->outbound, iov, 4, &need_sig);
733
734	/* TODO: We should determine if this is optional */
735	if (ret == 0 && need_sig)
736		vmbus_chan_send_event(channel);
737
738	return (ret);
739}
740
741/**
742 * @brief Send a multi-page buffer packet using a GPADL Direct packet type
743 */
744int
745hv_vmbus_channel_send_packet_multipagebuffer(
746	hv_vmbus_channel*		channel,
747	hv_vmbus_multipage_buffer*	multi_page_buffer,
748	void*				buffer,
749	uint32_t			buffer_len,
750	uint64_t			request_id)
751{
752
753	int			ret = 0;
754	uint32_t		desc_size;
755	boolean_t		need_sig;
756	uint32_t		packet_len;
757	uint32_t		packet_len_aligned;
758	uint32_t		pfn_count;
759	uint64_t		aligned_data = 0;
760	struct iovec		iov[3];
761	hv_vmbus_channel_packet_multipage_buffer desc;
762
763	pfn_count =
764	    HV_NUM_PAGES_SPANNED(
765		    multi_page_buffer->offset,
766		    multi_page_buffer->length);
767
768	if ((pfn_count == 0) || (pfn_count > HV_MAX_MULTIPAGE_BUFFER_COUNT))
769	    return (EINVAL);
770	/*
771	 * Adjust the size down since hv_vmbus_channel_packet_multipage_buffer
772	 * is the largest size we support
773	 */
774	desc_size =
775	    sizeof(hv_vmbus_channel_packet_multipage_buffer) -
776		    ((HV_MAX_MULTIPAGE_BUFFER_COUNT - pfn_count) *
777			sizeof(uint64_t));
778	packet_len = desc_size + buffer_len;
779	packet_len_aligned = HV_ALIGN_UP(packet_len, sizeof(uint64_t));
780
781	/*
782	 * Setup the descriptor
783	 */
784	desc.type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
785	desc.flags = HV_VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
786	desc.data_offset8 = desc_size >> 3; /* in 8-bytes granularity */
787	desc.length8 = (uint16_t) (packet_len_aligned >> 3);
788	desc.transaction_id = request_id;
789	desc.range_count = 1;
790
791	desc.range.length = multi_page_buffer->length;
792	desc.range.offset = multi_page_buffer->offset;
793
794	memcpy(desc.range.pfn_array, multi_page_buffer->pfn_array,
795		pfn_count * sizeof(uint64_t));
796
797	iov[0].iov_base = &desc;
798	iov[0].iov_len = desc_size;
799
800	iov[1].iov_base = buffer;
801	iov[1].iov_len = buffer_len;
802
803	iov[2].iov_base = &aligned_data;
804	iov[2].iov_len = packet_len_aligned - packet_len;
805
806	ret = hv_ring_buffer_write(&channel->outbound, iov, 3, &need_sig);
807
808	/* TODO: We should determine if this is optional */
809	if (ret == 0 && need_sig)
810		vmbus_chan_send_event(channel);
811
812	return (ret);
813}
814
815/**
816 * @brief Retrieve the user packet on the specified channel
817 */
818int
819hv_vmbus_channel_recv_packet(
820	hv_vmbus_channel*	channel,
821	void*			Buffer,
822	uint32_t		buffer_len,
823	uint32_t*		buffer_actual_len,
824	uint64_t*		request_id)
825{
826	int			ret;
827	uint32_t		user_len;
828	uint32_t		packet_len;
829	hv_vm_packet_descriptor	desc;
830
831	*buffer_actual_len = 0;
832	*request_id = 0;
833
834	ret = hv_ring_buffer_peek(&channel->inbound, &desc,
835		sizeof(hv_vm_packet_descriptor));
836	if (ret != 0)
837		return (0);
838
839	packet_len = desc.length8 << 3;
840	user_len = packet_len - (desc.data_offset8 << 3);
841
842	*buffer_actual_len = user_len;
843
844	if (user_len > buffer_len)
845		return (EINVAL);
846
847	*request_id = desc.transaction_id;
848
849	/* Copy over the packet to the user buffer */
850	ret = hv_ring_buffer_read(&channel->inbound, Buffer, user_len,
851		(desc.data_offset8 << 3));
852
853	return (0);
854}
855
856/**
857 * @brief Retrieve the raw packet on the specified channel
858 */
859int
860hv_vmbus_channel_recv_packet_raw(
861	hv_vmbus_channel*	channel,
862	void*			buffer,
863	uint32_t		buffer_len,
864	uint32_t*		buffer_actual_len,
865	uint64_t*		request_id)
866{
867	int		ret;
868	uint32_t	packetLen;
869	hv_vm_packet_descriptor	desc;
870
871	*buffer_actual_len = 0;
872	*request_id = 0;
873
874	ret = hv_ring_buffer_peek(
875		&channel->inbound, &desc,
876		sizeof(hv_vm_packet_descriptor));
877
878	if (ret != 0)
879	    return (0);
880
881	packetLen = desc.length8 << 3;
882	*buffer_actual_len = packetLen;
883
884	if (packetLen > buffer_len)
885	    return (ENOBUFS);
886
887	*request_id = desc.transaction_id;
888
889	/* Copy over the entire packet to the user buffer */
890	ret = hv_ring_buffer_read(&channel->inbound, buffer, packetLen, 0);
891
892	return (0);
893}
894
895static void
896vmbus_chan_task(void *xchan, int pending __unused)
897{
898	struct hv_vmbus_channel *chan = xchan;
899	vmbus_chan_callback_t cb = chan->ch_cb;
900	void *cbarg = chan->ch_cbarg;
901
902	/*
903	 * Optimize host to guest signaling by ensuring:
904	 * 1. While reading the channel, we disable interrupts from
905	 *    host.
906	 * 2. Ensure that we process all posted messages from the host
907	 *    before returning from this callback.
908	 * 3. Once we return, enable signaling from the host. Once this
909	 *    state is set we check to see if additional packets are
910	 *    available to read. In this case we repeat the process.
911	 *
912	 * NOTE: Interrupt has been disabled in the ISR.
913	 */
914	for (;;) {
915		uint32_t left;
916
917		cb(cbarg);
918
919		left = hv_ring_buffer_read_end(&chan->inbound);
920		if (left == 0) {
921			/* No more data in RX bufring; done */
922			break;
923		}
924		hv_ring_buffer_read_begin(&chan->inbound);
925	}
926}
927
928static void
929vmbus_chan_task_nobatch(void *xchan, int pending __unused)
930{
931	struct hv_vmbus_channel *chan = xchan;
932
933	chan->ch_cb(chan->ch_cbarg);
934}
935
936static __inline void
937vmbus_event_flags_proc(struct vmbus_softc *sc, volatile u_long *event_flags,
938    int flag_cnt)
939{
940	int f;
941
942	for (f = 0; f < flag_cnt; ++f) {
943		uint32_t chid_base;
944		u_long flags;
945		int chid_ofs;
946
947		if (event_flags[f] == 0)
948			continue;
949
950		flags = atomic_swap_long(&event_flags[f], 0);
951		chid_base = f << VMBUS_EVTFLAG_SHIFT;
952
953		while ((chid_ofs = ffsl(flags)) != 0) {
954			struct hv_vmbus_channel *channel;
955
956			--chid_ofs; /* NOTE: ffsl is 1-based */
957			flags &= ~(1UL << chid_ofs);
958
959			channel = sc->vmbus_chmap[chid_base + chid_ofs];
960
961			/* if channel is closed or closing */
962			if (channel == NULL || channel->ch_tq == NULL)
963				continue;
964
965			if (channel->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD)
966				hv_ring_buffer_read_begin(&channel->inbound);
967			taskqueue_enqueue(channel->ch_tq, &channel->ch_task);
968		}
969	}
970}
971
972void
973vmbus_event_proc(struct vmbus_softc *sc, int cpu)
974{
975	struct vmbus_evtflags *eventf;
976
977	/*
978	 * On Host with Win8 or above, the event page can be checked directly
979	 * to get the id of the channel that has the pending interrupt.
980	 */
981	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
982	vmbus_event_flags_proc(sc, eventf->evt_flags,
983	    VMBUS_PCPU_GET(sc, event_flags_cnt, cpu));
984}
985
986void
987vmbus_event_proc_compat(struct vmbus_softc *sc, int cpu)
988{
989	struct vmbus_evtflags *eventf;
990
991	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
992	if (atomic_testandclear_long(&eventf->evt_flags[0], 0)) {
993		vmbus_event_flags_proc(sc, sc->vmbus_rx_evtflags,
994		    VMBUS_CHAN_MAX_COMPAT >> VMBUS_EVTFLAG_SHIFT);
995	}
996}
997
998static void
999vmbus_chan_update_evtflagcnt(struct vmbus_softc *sc,
1000    const struct hv_vmbus_channel *chan)
1001{
1002	volatile int *flag_cnt_ptr;
1003	int flag_cnt;
1004
1005	flag_cnt = (chan->ch_id / VMBUS_EVTFLAG_LEN) + 1;
1006	flag_cnt_ptr = VMBUS_PCPU_PTR(sc, event_flags_cnt, chan->ch_cpuid);
1007
1008	for (;;) {
1009		int old_flag_cnt;
1010
1011		old_flag_cnt = *flag_cnt_ptr;
1012		if (old_flag_cnt >= flag_cnt)
1013			break;
1014		if (atomic_cmpset_int(flag_cnt_ptr, old_flag_cnt, flag_cnt)) {
1015			if (bootverbose) {
1016				device_printf(sc->vmbus_dev,
1017				    "channel%u update cpu%d flag_cnt to %d\n",
1018				    chan->ch_id, chan->ch_cpuid, flag_cnt);
1019			}
1020			break;
1021		}
1022	}
1023}
1024
1025static struct hv_vmbus_channel *
1026vmbus_chan_alloc(struct vmbus_softc *sc)
1027{
1028	struct hv_vmbus_channel *chan;
1029
1030	chan = malloc(sizeof(*chan), M_DEVBUF, M_WAITOK | M_ZERO);
1031
1032	chan->ch_monprm = hyperv_dmamem_alloc(bus_get_dma_tag(sc->vmbus_dev),
1033	    HYPERCALL_PARAM_ALIGN, 0, sizeof(struct hyperv_mon_param),
1034	    &chan->ch_monprm_dma, BUS_DMA_WAITOK | BUS_DMA_ZERO);
1035	if (chan->ch_monprm == NULL) {
1036		device_printf(sc->vmbus_dev, "monprm alloc failed\n");
1037		free(chan, M_DEVBUF);
1038		return NULL;
1039	}
1040
1041	chan->vmbus_sc = sc;
1042	mtx_init(&chan->ch_subchan_lock, "vmbus subchan", NULL, MTX_DEF);
1043	TAILQ_INIT(&chan->ch_subchans);
1044	TASK_INIT(&chan->ch_detach_task, 0, vmbus_chan_detach_task, chan);
1045
1046	return chan;
1047}
1048
1049static void
1050vmbus_chan_free(struct hv_vmbus_channel *chan)
1051{
1052	/* TODO: assert sub-channel list is empty */
1053	/* TODO: asset no longer on the primary channel's sub-channel list */
1054	/* TODO: asset no longer on the vmbus channel list */
1055	hyperv_dmamem_free(&chan->ch_monprm_dma, chan->ch_monprm);
1056	mtx_destroy(&chan->ch_subchan_lock);
1057	free(chan, M_DEVBUF);
1058}
1059
1060static int
1061vmbus_chan_add(struct hv_vmbus_channel *newchan)
1062{
1063	struct vmbus_softc *sc = newchan->vmbus_sc;
1064	struct hv_vmbus_channel *prichan;
1065
1066	if (newchan->ch_id == 0) {
1067		/*
1068		 * XXX
1069		 * Chan0 will neither be processed nor should be offered;
1070		 * skip it.
1071		 */
1072		device_printf(sc->vmbus_dev, "got chan0 offer, discard\n");
1073		return EINVAL;
1074	} else if (newchan->ch_id >= VMBUS_CHAN_MAX) {
1075		device_printf(sc->vmbus_dev, "invalid chan%u offer\n",
1076		    newchan->ch_id);
1077		return EINVAL;
1078	}
1079	sc->vmbus_chmap[newchan->ch_id] = newchan;
1080
1081	if (bootverbose) {
1082		device_printf(sc->vmbus_dev, "chan%u subidx%u offer\n",
1083		    newchan->ch_id, newchan->ch_subidx);
1084	}
1085
1086	mtx_lock(&sc->vmbus_prichan_lock);
1087	TAILQ_FOREACH(prichan, &sc->vmbus_prichans, ch_prilink) {
1088		/*
1089		 * Sub-channel will have the same type GUID and instance
1090		 * GUID as its primary channel.
1091		 */
1092		if (memcmp(&prichan->ch_guid_type, &newchan->ch_guid_type,
1093		    sizeof(struct hyperv_guid)) == 0 &&
1094		    memcmp(&prichan->ch_guid_inst, &newchan->ch_guid_inst,
1095		    sizeof(struct hyperv_guid)) == 0)
1096			break;
1097	}
1098	if (VMBUS_CHAN_ISPRIMARY(newchan)) {
1099		if (prichan == NULL) {
1100			/* Install the new primary channel */
1101			TAILQ_INSERT_TAIL(&sc->vmbus_prichans, newchan,
1102			    ch_prilink);
1103			mtx_unlock(&sc->vmbus_prichan_lock);
1104			return 0;
1105		} else {
1106			mtx_unlock(&sc->vmbus_prichan_lock);
1107			device_printf(sc->vmbus_dev, "duplicated primary "
1108			    "chan%u\n", newchan->ch_id);
1109			return EINVAL;
1110		}
1111	} else { /* Sub-channel */
1112		if (prichan == NULL) {
1113			mtx_unlock(&sc->vmbus_prichan_lock);
1114			device_printf(sc->vmbus_dev, "no primary chan for "
1115			    "chan%u\n", newchan->ch_id);
1116			return EINVAL;
1117		}
1118		/*
1119		 * Found the primary channel for this sub-channel and
1120		 * move on.
1121		 *
1122		 * XXX refcnt prichan
1123		 */
1124	}
1125	mtx_unlock(&sc->vmbus_prichan_lock);
1126
1127	/*
1128	 * This is a sub-channel; link it with the primary channel.
1129	 */
1130	KASSERT(!VMBUS_CHAN_ISPRIMARY(newchan),
1131	    ("new channel is not sub-channel"));
1132	KASSERT(prichan != NULL, ("no primary channel"));
1133
1134	newchan->ch_prichan = prichan;
1135	newchan->ch_dev = prichan->ch_dev;
1136
1137	mtx_lock(&prichan->ch_subchan_lock);
1138	TAILQ_INSERT_TAIL(&prichan->ch_subchans, newchan, ch_sublink);
1139	/*
1140	 * Bump up sub-channel count and notify anyone that is
1141	 * interested in this sub-channel, after this sub-channel
1142	 * is setup.
1143	 */
1144	prichan->ch_subchan_cnt++;
1145	mtx_unlock(&prichan->ch_subchan_lock);
1146	wakeup(prichan);
1147
1148	return 0;
1149}
1150
1151void
1152vmbus_channel_cpu_set(struct hv_vmbus_channel *chan, int cpu)
1153{
1154	KASSERT(cpu >= 0 && cpu < mp_ncpus, ("invalid cpu %d", cpu));
1155
1156	if (chan->vmbus_sc->vmbus_version == VMBUS_VERSION_WS2008 ||
1157	    chan->vmbus_sc->vmbus_version == VMBUS_VERSION_WIN7) {
1158		/* Only cpu0 is supported */
1159		cpu = 0;
1160	}
1161
1162	chan->ch_cpuid = cpu;
1163	chan->ch_vcpuid = VMBUS_PCPU_GET(chan->vmbus_sc, vcpuid, cpu);
1164
1165	if (bootverbose) {
1166		printf("vmbus_chan%u: assigned to cpu%u [vcpu%u]\n",
1167		    chan->ch_id, chan->ch_cpuid, chan->ch_vcpuid);
1168	}
1169}
1170
1171void
1172vmbus_channel_cpu_rr(struct hv_vmbus_channel *chan)
1173{
1174	static uint32_t vmbus_chan_nextcpu;
1175	int cpu;
1176
1177	cpu = atomic_fetchadd_int(&vmbus_chan_nextcpu, 1) % mp_ncpus;
1178	vmbus_channel_cpu_set(chan, cpu);
1179}
1180
1181static void
1182vmbus_chan_cpu_default(struct hv_vmbus_channel *chan)
1183{
1184	/*
1185	 * By default, pin the channel to cpu0.  Devices having
1186	 * special channel-cpu mapping requirement should call
1187	 * vmbus_channel_cpu_{set,rr}().
1188	 */
1189	vmbus_channel_cpu_set(chan, 0);
1190}
1191
1192static void
1193vmbus_chan_msgproc_choffer(struct vmbus_softc *sc,
1194    const struct vmbus_message *msg)
1195{
1196	const struct vmbus_chanmsg_choffer *offer;
1197	struct hv_vmbus_channel *chan;
1198	int error;
1199
1200	offer = (const struct vmbus_chanmsg_choffer *)msg->msg_data;
1201
1202	chan = vmbus_chan_alloc(sc);
1203	if (chan == NULL) {
1204		device_printf(sc->vmbus_dev, "allocate chan%u failed\n",
1205		    offer->chm_chanid);
1206		return;
1207	}
1208
1209	chan->ch_id = offer->chm_chanid;
1210	chan->ch_subidx = offer->chm_subidx;
1211	chan->ch_guid_type = offer->chm_chtype;
1212	chan->ch_guid_inst = offer->chm_chinst;
1213
1214	/* Batch reading is on by default */
1215	chan->ch_flags |= VMBUS_CHAN_FLAG_BATCHREAD;
1216
1217	chan->ch_monprm->mp_connid = VMBUS_CONNID_EVENT;
1218	if (sc->vmbus_version != VMBUS_VERSION_WS2008)
1219		chan->ch_monprm->mp_connid = offer->chm_connid;
1220
1221	if (offer->chm_flags1 & VMBUS_CHOFFER_FLAG1_HASMNF) {
1222		/*
1223		 * Setup MNF stuffs.
1224		 */
1225		chan->ch_flags |= VMBUS_CHAN_FLAG_HASMNF;
1226		chan->ch_montrig_idx = offer->chm_montrig / VMBUS_MONTRIG_LEN;
1227		if (chan->ch_montrig_idx >= VMBUS_MONTRIGS_MAX)
1228			panic("invalid monitor trigger %u", offer->chm_montrig);
1229		chan->ch_montrig_mask =
1230		    1 << (offer->chm_montrig % VMBUS_MONTRIG_LEN);
1231	}
1232
1233	/* Select default cpu for this channel. */
1234	vmbus_chan_cpu_default(chan);
1235
1236	error = vmbus_chan_add(chan);
1237	if (error) {
1238		device_printf(sc->vmbus_dev, "add chan%u failed: %d\n",
1239		    chan->ch_id, error);
1240		vmbus_chan_free(chan);
1241		return;
1242	}
1243
1244	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1245		/*
1246		 * Add device for this primary channel.
1247		 *
1248		 * NOTE:
1249		 * Error is ignored here; don't have much to do if error
1250		 * really happens.
1251		 */
1252		vmbus_add_child(chan);
1253	}
1254}
1255
1256/*
1257 * XXX pretty broken; need rework.
1258 */
1259static void
1260vmbus_chan_msgproc_chrescind(struct vmbus_softc *sc,
1261    const struct vmbus_message *msg)
1262{
1263	const struct vmbus_chanmsg_chrescind *note;
1264	struct hv_vmbus_channel *chan;
1265
1266	note = (const struct vmbus_chanmsg_chrescind *)msg->msg_data;
1267	if (note->chm_chanid > VMBUS_CHAN_MAX) {
1268		device_printf(sc->vmbus_dev, "invalid rescinded chan%u\n",
1269		    note->chm_chanid);
1270		return;
1271	}
1272
1273	if (bootverbose) {
1274		device_printf(sc->vmbus_dev, "chan%u rescinded\n",
1275		    note->chm_chanid);
1276	}
1277
1278	chan = sc->vmbus_chmap[note->chm_chanid];
1279	if (chan == NULL)
1280		return;
1281	sc->vmbus_chmap[note->chm_chanid] = NULL;
1282
1283	taskqueue_enqueue(taskqueue_thread, &chan->ch_detach_task);
1284}
1285
1286static void
1287vmbus_chan_detach_task(void *xchan, int pending __unused)
1288{
1289	struct hv_vmbus_channel *chan = xchan;
1290
1291	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1292		/* Only primary channel owns the device */
1293		vmbus_delete_child(chan);
1294		/* NOTE: DO NOT free primary channel for now */
1295	} else {
1296		struct vmbus_softc *sc = chan->vmbus_sc;
1297		struct hv_vmbus_channel *pri_chan = chan->ch_prichan;
1298		struct vmbus_chanmsg_chfree *req;
1299		struct vmbus_msghc *mh;
1300		int error;
1301
1302		mh = vmbus_msghc_get(sc, sizeof(*req));
1303		if (mh == NULL) {
1304			device_printf(sc->vmbus_dev,
1305			    "can not get msg hypercall for chfree(chan%u)\n",
1306			    chan->ch_id);
1307			goto remove;
1308		}
1309
1310		req = vmbus_msghc_dataptr(mh);
1311		req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHFREE;
1312		req->chm_chanid = chan->ch_id;
1313
1314		error = vmbus_msghc_exec_noresult(mh);
1315		vmbus_msghc_put(sc, mh);
1316
1317		if (error) {
1318			device_printf(sc->vmbus_dev,
1319			    "chfree(chan%u) failed: %d",
1320			    chan->ch_id, error);
1321			/* NOTE: Move on! */
1322		} else {
1323			if (bootverbose) {
1324				device_printf(sc->vmbus_dev, "chan%u freed\n",
1325				    chan->ch_id);
1326			}
1327		}
1328remove:
1329		mtx_lock(&pri_chan->ch_subchan_lock);
1330		TAILQ_REMOVE(&pri_chan->ch_subchans, chan, ch_sublink);
1331		KASSERT(pri_chan->ch_subchan_cnt > 0,
1332		    ("invalid subchan_cnt %d", pri_chan->ch_subchan_cnt));
1333		pri_chan->ch_subchan_cnt--;
1334		mtx_unlock(&pri_chan->ch_subchan_lock);
1335		wakeup(pri_chan);
1336
1337		vmbus_chan_free(chan);
1338	}
1339}
1340
1341/*
1342 * Detach all devices and destroy the corresponding primary channels.
1343 */
1344void
1345vmbus_chan_destroy_all(struct vmbus_softc *sc)
1346{
1347	struct hv_vmbus_channel *chan;
1348
1349	mtx_lock(&sc->vmbus_prichan_lock);
1350	while ((chan = TAILQ_FIRST(&sc->vmbus_prichans)) != NULL) {
1351		KASSERT(VMBUS_CHAN_ISPRIMARY(chan), ("not primary channel"));
1352		TAILQ_REMOVE(&sc->vmbus_prichans, chan, ch_prilink);
1353		mtx_unlock(&sc->vmbus_prichan_lock);
1354
1355		vmbus_delete_child(chan);
1356		vmbus_chan_free(chan);
1357
1358		mtx_lock(&sc->vmbus_prichan_lock);
1359	}
1360	bzero(sc->vmbus_chmap,
1361	    sizeof(struct hv_vmbus_channel *) * VMBUS_CHAN_MAX);
1362	mtx_unlock(&sc->vmbus_prichan_lock);
1363}
1364
1365/**
1366 * @brief Select the best outgoing channel
1367 *
1368 * The channel whose vcpu binding is closest to the currect vcpu will
1369 * be selected.
1370 * If no multi-channel, always select primary channel
1371 *
1372 * @param primary - primary channel
1373 */
1374struct hv_vmbus_channel *
1375vmbus_select_outgoing_channel(struct hv_vmbus_channel *primary)
1376{
1377	hv_vmbus_channel *new_channel = NULL;
1378	hv_vmbus_channel *outgoing_channel = primary;
1379	int old_cpu_distance = 0;
1380	int new_cpu_distance = 0;
1381	int cur_vcpu = 0;
1382	int smp_pro_id = PCPU_GET(cpuid);
1383
1384	if (TAILQ_EMPTY(&primary->ch_subchans)) {
1385		return outgoing_channel;
1386	}
1387
1388	if (smp_pro_id >= MAXCPU) {
1389		return outgoing_channel;
1390	}
1391
1392	cur_vcpu = VMBUS_PCPU_GET(primary->vmbus_sc, vcpuid, smp_pro_id);
1393
1394	/* XXX need lock */
1395	TAILQ_FOREACH(new_channel, &primary->ch_subchans, ch_sublink) {
1396		if ((new_channel->ch_stflags & VMBUS_CHAN_ST_OPENED) == 0) {
1397			continue;
1398		}
1399
1400		if (new_channel->ch_vcpuid == cur_vcpu){
1401			return new_channel;
1402		}
1403
1404		old_cpu_distance = ((outgoing_channel->ch_vcpuid > cur_vcpu) ?
1405		    (outgoing_channel->ch_vcpuid - cur_vcpu) :
1406		    (cur_vcpu - outgoing_channel->ch_vcpuid));
1407
1408		new_cpu_distance = ((new_channel->ch_vcpuid > cur_vcpu) ?
1409		    (new_channel->ch_vcpuid - cur_vcpu) :
1410		    (cur_vcpu - new_channel->ch_vcpuid));
1411
1412		if (old_cpu_distance < new_cpu_distance) {
1413			continue;
1414		}
1415
1416		outgoing_channel = new_channel;
1417	}
1418
1419	return(outgoing_channel);
1420}
1421
1422struct hv_vmbus_channel **
1423vmbus_get_subchan(struct hv_vmbus_channel *pri_chan, int subchan_cnt)
1424{
1425	struct hv_vmbus_channel **ret, *chan;
1426	int i;
1427
1428	ret = malloc(subchan_cnt * sizeof(struct hv_vmbus_channel *), M_TEMP,
1429	    M_WAITOK);
1430
1431	mtx_lock(&pri_chan->ch_subchan_lock);
1432
1433	while (pri_chan->ch_subchan_cnt < subchan_cnt)
1434		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "subch", 0);
1435
1436	i = 0;
1437	TAILQ_FOREACH(chan, &pri_chan->ch_subchans, ch_sublink) {
1438		/* TODO: refcnt chan */
1439		ret[i] = chan;
1440
1441		++i;
1442		if (i == subchan_cnt)
1443			break;
1444	}
1445	KASSERT(i == subchan_cnt, ("invalid subchan count %d, should be %d",
1446	    pri_chan->ch_subchan_cnt, subchan_cnt));
1447
1448	mtx_unlock(&pri_chan->ch_subchan_lock);
1449
1450	return ret;
1451}
1452
1453void
1454vmbus_rel_subchan(struct hv_vmbus_channel **subchan, int subchan_cnt __unused)
1455{
1456
1457	free(subchan, M_TEMP);
1458}
1459
1460void
1461vmbus_drain_subchan(struct hv_vmbus_channel *pri_chan)
1462{
1463	mtx_lock(&pri_chan->ch_subchan_lock);
1464	while (pri_chan->ch_subchan_cnt > 0)
1465		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "dsubch", 0);
1466	mtx_unlock(&pri_chan->ch_subchan_lock);
1467}
1468
1469void
1470vmbus_chan_msgproc(struct vmbus_softc *sc, const struct vmbus_message *msg)
1471{
1472	vmbus_chanmsg_proc_t msg_proc;
1473	uint32_t msg_type;
1474
1475	msg_type = ((const struct vmbus_chanmsg_hdr *)msg->msg_data)->chm_type;
1476	KASSERT(msg_type < VMBUS_CHANMSG_TYPE_MAX,
1477	    ("invalid message type %u", msg_type));
1478
1479	msg_proc = vmbus_chan_msgprocs[msg_type];
1480	if (msg_proc != NULL)
1481		msg_proc(sc, msg);
1482}
1483