vmbus_chan.c revision 302879
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 302879 2016-07-15 06:49:45Z 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
675int
676vmbus_chan_send_sglist(struct hv_vmbus_channel *chan,
677    struct vmbus_gpa sg[], int sglen, void *data, int dlen, uint64_t xactid)
678{
679	struct vmbus_chanpkt_sglist pkt;
680	int pktlen, pad_pktlen, hlen, error;
681	struct iovec iov[4];
682	boolean_t send_evt;
683	uint64_t pad = 0;
684
685	KASSERT(sglen < VMBUS_CHAN_SGLIST_MAX,
686	    ("invalid sglist len %d", sglen));
687
688	hlen = __offsetof(struct vmbus_chanpkt_sglist, cp_gpa[sglen]);
689	pktlen = hlen + dlen;
690	pad_pktlen = roundup2(pktlen, VMBUS_CHANPKT_SIZE_ALIGN);
691
692	pkt.cp_hdr.cph_type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
693	pkt.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
694	pkt.cp_hdr.cph_data_ofs = hlen >> VMBUS_CHANPKT_SIZE_SHIFT;
695	pkt.cp_hdr.cph_len = pad_pktlen >> VMBUS_CHANPKT_SIZE_SHIFT;
696	pkt.cp_hdr.cph_xactid = xactid;
697	pkt.cp_rsvd = 0;
698	pkt.cp_gpa_cnt = sglen;
699
700	iov[0].iov_base = &pkt;
701	iov[0].iov_len = sizeof(pkt);
702	iov[1].iov_base = sg;
703	iov[1].iov_len = sizeof(struct vmbus_gpa) * sglen;
704	iov[2].iov_base = data;
705	iov[2].iov_len = dlen;
706	iov[3].iov_base = &pad;
707	iov[3].iov_len = pad_pktlen - pktlen;
708
709	error = hv_ring_buffer_write(&chan->outbound, iov, 4, &send_evt);
710	if (!error && send_evt)
711		vmbus_chan_send_event(chan);
712	return error;
713}
714
715int
716vmbus_chan_send_prplist(struct hv_vmbus_channel *chan,
717    struct vmbus_gpa_range *prp, int prp_cnt, void *data, int dlen,
718    uint64_t xactid)
719{
720	struct vmbus_chanpkt_prplist pkt;
721	int pktlen, pad_pktlen, hlen, error;
722	struct iovec iov[4];
723	boolean_t send_evt;
724	uint64_t pad = 0;
725
726	KASSERT(prp_cnt < VMBUS_CHAN_PRPLIST_MAX,
727	    ("invalid prplist entry count %d", prp_cnt));
728
729	hlen = __offsetof(struct vmbus_chanpkt_prplist,
730	    cp_range[0].gpa_page[prp_cnt]);
731	pktlen = hlen + dlen;
732	pad_pktlen = roundup2(pktlen, VMBUS_CHANPKT_SIZE_ALIGN);
733
734	pkt.cp_hdr.cph_type = HV_VMBUS_PACKET_TYPE_DATA_USING_GPA_DIRECT;
735	pkt.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
736	pkt.cp_hdr.cph_data_ofs = hlen >> VMBUS_CHANPKT_SIZE_SHIFT;
737	pkt.cp_hdr.cph_len = pad_pktlen >> VMBUS_CHANPKT_SIZE_SHIFT;
738	pkt.cp_hdr.cph_xactid = xactid;
739	pkt.cp_rsvd = 0;
740	pkt.cp_range_cnt = 1;
741
742	iov[0].iov_base = &pkt;
743	iov[0].iov_len = sizeof(pkt);
744	iov[1].iov_base = prp;
745	iov[1].iov_len = __offsetof(struct vmbus_gpa_range, gpa_page[prp_cnt]);
746	iov[2].iov_base = data;
747	iov[2].iov_len = dlen;
748	iov[3].iov_base = &pad;
749	iov[3].iov_len = pad_pktlen - pktlen;
750
751	error = hv_ring_buffer_write(&chan->outbound, iov, 4, &send_evt);
752	if (!error && send_evt)
753		vmbus_chan_send_event(chan);
754	return error;
755}
756
757/**
758 * @brief Retrieve the user packet on the specified channel
759 */
760int
761hv_vmbus_channel_recv_packet(
762	hv_vmbus_channel*	channel,
763	void*			Buffer,
764	uint32_t		buffer_len,
765	uint32_t*		buffer_actual_len,
766	uint64_t*		request_id)
767{
768	int			ret;
769	uint32_t		user_len;
770	uint32_t		packet_len;
771	hv_vm_packet_descriptor	desc;
772
773	*buffer_actual_len = 0;
774	*request_id = 0;
775
776	ret = hv_ring_buffer_peek(&channel->inbound, &desc,
777		sizeof(hv_vm_packet_descriptor));
778	if (ret != 0)
779		return (0);
780
781	packet_len = desc.length8 << 3;
782	user_len = packet_len - (desc.data_offset8 << 3);
783
784	*buffer_actual_len = user_len;
785
786	if (user_len > buffer_len)
787		return (EINVAL);
788
789	*request_id = desc.transaction_id;
790
791	/* Copy over the packet to the user buffer */
792	ret = hv_ring_buffer_read(&channel->inbound, Buffer, user_len,
793		(desc.data_offset8 << 3));
794
795	return (0);
796}
797
798/**
799 * @brief Retrieve the raw packet on the specified channel
800 */
801int
802hv_vmbus_channel_recv_packet_raw(
803	hv_vmbus_channel*	channel,
804	void*			buffer,
805	uint32_t		buffer_len,
806	uint32_t*		buffer_actual_len,
807	uint64_t*		request_id)
808{
809	int		ret;
810	uint32_t	packetLen;
811	hv_vm_packet_descriptor	desc;
812
813	*buffer_actual_len = 0;
814	*request_id = 0;
815
816	ret = hv_ring_buffer_peek(
817		&channel->inbound, &desc,
818		sizeof(hv_vm_packet_descriptor));
819
820	if (ret != 0)
821	    return (0);
822
823	packetLen = desc.length8 << 3;
824	*buffer_actual_len = packetLen;
825
826	if (packetLen > buffer_len)
827	    return (ENOBUFS);
828
829	*request_id = desc.transaction_id;
830
831	/* Copy over the entire packet to the user buffer */
832	ret = hv_ring_buffer_read(&channel->inbound, buffer, packetLen, 0);
833
834	return (0);
835}
836
837static void
838vmbus_chan_task(void *xchan, int pending __unused)
839{
840	struct hv_vmbus_channel *chan = xchan;
841	vmbus_chan_callback_t cb = chan->ch_cb;
842	void *cbarg = chan->ch_cbarg;
843
844	/*
845	 * Optimize host to guest signaling by ensuring:
846	 * 1. While reading the channel, we disable interrupts from
847	 *    host.
848	 * 2. Ensure that we process all posted messages from the host
849	 *    before returning from this callback.
850	 * 3. Once we return, enable signaling from the host. Once this
851	 *    state is set we check to see if additional packets are
852	 *    available to read. In this case we repeat the process.
853	 *
854	 * NOTE: Interrupt has been disabled in the ISR.
855	 */
856	for (;;) {
857		uint32_t left;
858
859		cb(cbarg);
860
861		left = hv_ring_buffer_read_end(&chan->inbound);
862		if (left == 0) {
863			/* No more data in RX bufring; done */
864			break;
865		}
866		hv_ring_buffer_read_begin(&chan->inbound);
867	}
868}
869
870static void
871vmbus_chan_task_nobatch(void *xchan, int pending __unused)
872{
873	struct hv_vmbus_channel *chan = xchan;
874
875	chan->ch_cb(chan->ch_cbarg);
876}
877
878static __inline void
879vmbus_event_flags_proc(struct vmbus_softc *sc, volatile u_long *event_flags,
880    int flag_cnt)
881{
882	int f;
883
884	for (f = 0; f < flag_cnt; ++f) {
885		uint32_t chid_base;
886		u_long flags;
887		int chid_ofs;
888
889		if (event_flags[f] == 0)
890			continue;
891
892		flags = atomic_swap_long(&event_flags[f], 0);
893		chid_base = f << VMBUS_EVTFLAG_SHIFT;
894
895		while ((chid_ofs = ffsl(flags)) != 0) {
896			struct hv_vmbus_channel *channel;
897
898			--chid_ofs; /* NOTE: ffsl is 1-based */
899			flags &= ~(1UL << chid_ofs);
900
901			channel = sc->vmbus_chmap[chid_base + chid_ofs];
902
903			/* if channel is closed or closing */
904			if (channel == NULL || channel->ch_tq == NULL)
905				continue;
906
907			if (channel->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD)
908				hv_ring_buffer_read_begin(&channel->inbound);
909			taskqueue_enqueue(channel->ch_tq, &channel->ch_task);
910		}
911	}
912}
913
914void
915vmbus_event_proc(struct vmbus_softc *sc, int cpu)
916{
917	struct vmbus_evtflags *eventf;
918
919	/*
920	 * On Host with Win8 or above, the event page can be checked directly
921	 * to get the id of the channel that has the pending interrupt.
922	 */
923	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
924	vmbus_event_flags_proc(sc, eventf->evt_flags,
925	    VMBUS_PCPU_GET(sc, event_flags_cnt, cpu));
926}
927
928void
929vmbus_event_proc_compat(struct vmbus_softc *sc, int cpu)
930{
931	struct vmbus_evtflags *eventf;
932
933	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
934	if (atomic_testandclear_long(&eventf->evt_flags[0], 0)) {
935		vmbus_event_flags_proc(sc, sc->vmbus_rx_evtflags,
936		    VMBUS_CHAN_MAX_COMPAT >> VMBUS_EVTFLAG_SHIFT);
937	}
938}
939
940static void
941vmbus_chan_update_evtflagcnt(struct vmbus_softc *sc,
942    const struct hv_vmbus_channel *chan)
943{
944	volatile int *flag_cnt_ptr;
945	int flag_cnt;
946
947	flag_cnt = (chan->ch_id / VMBUS_EVTFLAG_LEN) + 1;
948	flag_cnt_ptr = VMBUS_PCPU_PTR(sc, event_flags_cnt, chan->ch_cpuid);
949
950	for (;;) {
951		int old_flag_cnt;
952
953		old_flag_cnt = *flag_cnt_ptr;
954		if (old_flag_cnt >= flag_cnt)
955			break;
956		if (atomic_cmpset_int(flag_cnt_ptr, old_flag_cnt, flag_cnt)) {
957			if (bootverbose) {
958				device_printf(sc->vmbus_dev,
959				    "channel%u update cpu%d flag_cnt to %d\n",
960				    chan->ch_id, chan->ch_cpuid, flag_cnt);
961			}
962			break;
963		}
964	}
965}
966
967static struct hv_vmbus_channel *
968vmbus_chan_alloc(struct vmbus_softc *sc)
969{
970	struct hv_vmbus_channel *chan;
971
972	chan = malloc(sizeof(*chan), M_DEVBUF, M_WAITOK | M_ZERO);
973
974	chan->ch_monprm = hyperv_dmamem_alloc(bus_get_dma_tag(sc->vmbus_dev),
975	    HYPERCALL_PARAM_ALIGN, 0, sizeof(struct hyperv_mon_param),
976	    &chan->ch_monprm_dma, BUS_DMA_WAITOK | BUS_DMA_ZERO);
977	if (chan->ch_monprm == NULL) {
978		device_printf(sc->vmbus_dev, "monprm alloc failed\n");
979		free(chan, M_DEVBUF);
980		return NULL;
981	}
982
983	chan->vmbus_sc = sc;
984	mtx_init(&chan->ch_subchan_lock, "vmbus subchan", NULL, MTX_DEF);
985	TAILQ_INIT(&chan->ch_subchans);
986	TASK_INIT(&chan->ch_detach_task, 0, vmbus_chan_detach_task, chan);
987
988	return chan;
989}
990
991static void
992vmbus_chan_free(struct hv_vmbus_channel *chan)
993{
994	/* TODO: assert sub-channel list is empty */
995	/* TODO: asset no longer on the primary channel's sub-channel list */
996	/* TODO: asset no longer on the vmbus channel list */
997	hyperv_dmamem_free(&chan->ch_monprm_dma, chan->ch_monprm);
998	mtx_destroy(&chan->ch_subchan_lock);
999	free(chan, M_DEVBUF);
1000}
1001
1002static int
1003vmbus_chan_add(struct hv_vmbus_channel *newchan)
1004{
1005	struct vmbus_softc *sc = newchan->vmbus_sc;
1006	struct hv_vmbus_channel *prichan;
1007
1008	if (newchan->ch_id == 0) {
1009		/*
1010		 * XXX
1011		 * Chan0 will neither be processed nor should be offered;
1012		 * skip it.
1013		 */
1014		device_printf(sc->vmbus_dev, "got chan0 offer, discard\n");
1015		return EINVAL;
1016	} else if (newchan->ch_id >= VMBUS_CHAN_MAX) {
1017		device_printf(sc->vmbus_dev, "invalid chan%u offer\n",
1018		    newchan->ch_id);
1019		return EINVAL;
1020	}
1021	sc->vmbus_chmap[newchan->ch_id] = newchan;
1022
1023	if (bootverbose) {
1024		device_printf(sc->vmbus_dev, "chan%u subidx%u offer\n",
1025		    newchan->ch_id, newchan->ch_subidx);
1026	}
1027
1028	mtx_lock(&sc->vmbus_prichan_lock);
1029	TAILQ_FOREACH(prichan, &sc->vmbus_prichans, ch_prilink) {
1030		/*
1031		 * Sub-channel will have the same type GUID and instance
1032		 * GUID as its primary channel.
1033		 */
1034		if (memcmp(&prichan->ch_guid_type, &newchan->ch_guid_type,
1035		    sizeof(struct hyperv_guid)) == 0 &&
1036		    memcmp(&prichan->ch_guid_inst, &newchan->ch_guid_inst,
1037		    sizeof(struct hyperv_guid)) == 0)
1038			break;
1039	}
1040	if (VMBUS_CHAN_ISPRIMARY(newchan)) {
1041		if (prichan == NULL) {
1042			/* Install the new primary channel */
1043			TAILQ_INSERT_TAIL(&sc->vmbus_prichans, newchan,
1044			    ch_prilink);
1045			mtx_unlock(&sc->vmbus_prichan_lock);
1046			return 0;
1047		} else {
1048			mtx_unlock(&sc->vmbus_prichan_lock);
1049			device_printf(sc->vmbus_dev, "duplicated primary "
1050			    "chan%u\n", newchan->ch_id);
1051			return EINVAL;
1052		}
1053	} else { /* Sub-channel */
1054		if (prichan == NULL) {
1055			mtx_unlock(&sc->vmbus_prichan_lock);
1056			device_printf(sc->vmbus_dev, "no primary chan for "
1057			    "chan%u\n", newchan->ch_id);
1058			return EINVAL;
1059		}
1060		/*
1061		 * Found the primary channel for this sub-channel and
1062		 * move on.
1063		 *
1064		 * XXX refcnt prichan
1065		 */
1066	}
1067	mtx_unlock(&sc->vmbus_prichan_lock);
1068
1069	/*
1070	 * This is a sub-channel; link it with the primary channel.
1071	 */
1072	KASSERT(!VMBUS_CHAN_ISPRIMARY(newchan),
1073	    ("new channel is not sub-channel"));
1074	KASSERT(prichan != NULL, ("no primary channel"));
1075
1076	newchan->ch_prichan = prichan;
1077	newchan->ch_dev = prichan->ch_dev;
1078
1079	mtx_lock(&prichan->ch_subchan_lock);
1080	TAILQ_INSERT_TAIL(&prichan->ch_subchans, newchan, ch_sublink);
1081	/*
1082	 * Bump up sub-channel count and notify anyone that is
1083	 * interested in this sub-channel, after this sub-channel
1084	 * is setup.
1085	 */
1086	prichan->ch_subchan_cnt++;
1087	mtx_unlock(&prichan->ch_subchan_lock);
1088	wakeup(prichan);
1089
1090	return 0;
1091}
1092
1093void
1094vmbus_channel_cpu_set(struct hv_vmbus_channel *chan, int cpu)
1095{
1096	KASSERT(cpu >= 0 && cpu < mp_ncpus, ("invalid cpu %d", cpu));
1097
1098	if (chan->vmbus_sc->vmbus_version == VMBUS_VERSION_WS2008 ||
1099	    chan->vmbus_sc->vmbus_version == VMBUS_VERSION_WIN7) {
1100		/* Only cpu0 is supported */
1101		cpu = 0;
1102	}
1103
1104	chan->ch_cpuid = cpu;
1105	chan->ch_vcpuid = VMBUS_PCPU_GET(chan->vmbus_sc, vcpuid, cpu);
1106
1107	if (bootverbose) {
1108		printf("vmbus_chan%u: assigned to cpu%u [vcpu%u]\n",
1109		    chan->ch_id, chan->ch_cpuid, chan->ch_vcpuid);
1110	}
1111}
1112
1113void
1114vmbus_channel_cpu_rr(struct hv_vmbus_channel *chan)
1115{
1116	static uint32_t vmbus_chan_nextcpu;
1117	int cpu;
1118
1119	cpu = atomic_fetchadd_int(&vmbus_chan_nextcpu, 1) % mp_ncpus;
1120	vmbus_channel_cpu_set(chan, cpu);
1121}
1122
1123static void
1124vmbus_chan_cpu_default(struct hv_vmbus_channel *chan)
1125{
1126	/*
1127	 * By default, pin the channel to cpu0.  Devices having
1128	 * special channel-cpu mapping requirement should call
1129	 * vmbus_channel_cpu_{set,rr}().
1130	 */
1131	vmbus_channel_cpu_set(chan, 0);
1132}
1133
1134static void
1135vmbus_chan_msgproc_choffer(struct vmbus_softc *sc,
1136    const struct vmbus_message *msg)
1137{
1138	const struct vmbus_chanmsg_choffer *offer;
1139	struct hv_vmbus_channel *chan;
1140	int error;
1141
1142	offer = (const struct vmbus_chanmsg_choffer *)msg->msg_data;
1143
1144	chan = vmbus_chan_alloc(sc);
1145	if (chan == NULL) {
1146		device_printf(sc->vmbus_dev, "allocate chan%u failed\n",
1147		    offer->chm_chanid);
1148		return;
1149	}
1150
1151	chan->ch_id = offer->chm_chanid;
1152	chan->ch_subidx = offer->chm_subidx;
1153	chan->ch_guid_type = offer->chm_chtype;
1154	chan->ch_guid_inst = offer->chm_chinst;
1155
1156	/* Batch reading is on by default */
1157	chan->ch_flags |= VMBUS_CHAN_FLAG_BATCHREAD;
1158
1159	chan->ch_monprm->mp_connid = VMBUS_CONNID_EVENT;
1160	if (sc->vmbus_version != VMBUS_VERSION_WS2008)
1161		chan->ch_monprm->mp_connid = offer->chm_connid;
1162
1163	if (offer->chm_flags1 & VMBUS_CHOFFER_FLAG1_HASMNF) {
1164		/*
1165		 * Setup MNF stuffs.
1166		 */
1167		chan->ch_flags |= VMBUS_CHAN_FLAG_HASMNF;
1168		chan->ch_montrig_idx = offer->chm_montrig / VMBUS_MONTRIG_LEN;
1169		if (chan->ch_montrig_idx >= VMBUS_MONTRIGS_MAX)
1170			panic("invalid monitor trigger %u", offer->chm_montrig);
1171		chan->ch_montrig_mask =
1172		    1 << (offer->chm_montrig % VMBUS_MONTRIG_LEN);
1173	}
1174
1175	/* Select default cpu for this channel. */
1176	vmbus_chan_cpu_default(chan);
1177
1178	error = vmbus_chan_add(chan);
1179	if (error) {
1180		device_printf(sc->vmbus_dev, "add chan%u failed: %d\n",
1181		    chan->ch_id, error);
1182		vmbus_chan_free(chan);
1183		return;
1184	}
1185
1186	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1187		/*
1188		 * Add device for this primary channel.
1189		 *
1190		 * NOTE:
1191		 * Error is ignored here; don't have much to do if error
1192		 * really happens.
1193		 */
1194		vmbus_add_child(chan);
1195	}
1196}
1197
1198/*
1199 * XXX pretty broken; need rework.
1200 */
1201static void
1202vmbus_chan_msgproc_chrescind(struct vmbus_softc *sc,
1203    const struct vmbus_message *msg)
1204{
1205	const struct vmbus_chanmsg_chrescind *note;
1206	struct hv_vmbus_channel *chan;
1207
1208	note = (const struct vmbus_chanmsg_chrescind *)msg->msg_data;
1209	if (note->chm_chanid > VMBUS_CHAN_MAX) {
1210		device_printf(sc->vmbus_dev, "invalid rescinded chan%u\n",
1211		    note->chm_chanid);
1212		return;
1213	}
1214
1215	if (bootverbose) {
1216		device_printf(sc->vmbus_dev, "chan%u rescinded\n",
1217		    note->chm_chanid);
1218	}
1219
1220	chan = sc->vmbus_chmap[note->chm_chanid];
1221	if (chan == NULL)
1222		return;
1223	sc->vmbus_chmap[note->chm_chanid] = NULL;
1224
1225	taskqueue_enqueue(taskqueue_thread, &chan->ch_detach_task);
1226}
1227
1228static void
1229vmbus_chan_detach_task(void *xchan, int pending __unused)
1230{
1231	struct hv_vmbus_channel *chan = xchan;
1232
1233	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1234		/* Only primary channel owns the device */
1235		vmbus_delete_child(chan);
1236		/* NOTE: DO NOT free primary channel for now */
1237	} else {
1238		struct vmbus_softc *sc = chan->vmbus_sc;
1239		struct hv_vmbus_channel *pri_chan = chan->ch_prichan;
1240		struct vmbus_chanmsg_chfree *req;
1241		struct vmbus_msghc *mh;
1242		int error;
1243
1244		mh = vmbus_msghc_get(sc, sizeof(*req));
1245		if (mh == NULL) {
1246			device_printf(sc->vmbus_dev,
1247			    "can not get msg hypercall for chfree(chan%u)\n",
1248			    chan->ch_id);
1249			goto remove;
1250		}
1251
1252		req = vmbus_msghc_dataptr(mh);
1253		req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHFREE;
1254		req->chm_chanid = chan->ch_id;
1255
1256		error = vmbus_msghc_exec_noresult(mh);
1257		vmbus_msghc_put(sc, mh);
1258
1259		if (error) {
1260			device_printf(sc->vmbus_dev,
1261			    "chfree(chan%u) failed: %d",
1262			    chan->ch_id, error);
1263			/* NOTE: Move on! */
1264		} else {
1265			if (bootverbose) {
1266				device_printf(sc->vmbus_dev, "chan%u freed\n",
1267				    chan->ch_id);
1268			}
1269		}
1270remove:
1271		mtx_lock(&pri_chan->ch_subchan_lock);
1272		TAILQ_REMOVE(&pri_chan->ch_subchans, chan, ch_sublink);
1273		KASSERT(pri_chan->ch_subchan_cnt > 0,
1274		    ("invalid subchan_cnt %d", pri_chan->ch_subchan_cnt));
1275		pri_chan->ch_subchan_cnt--;
1276		mtx_unlock(&pri_chan->ch_subchan_lock);
1277		wakeup(pri_chan);
1278
1279		vmbus_chan_free(chan);
1280	}
1281}
1282
1283/*
1284 * Detach all devices and destroy the corresponding primary channels.
1285 */
1286void
1287vmbus_chan_destroy_all(struct vmbus_softc *sc)
1288{
1289	struct hv_vmbus_channel *chan;
1290
1291	mtx_lock(&sc->vmbus_prichan_lock);
1292	while ((chan = TAILQ_FIRST(&sc->vmbus_prichans)) != NULL) {
1293		KASSERT(VMBUS_CHAN_ISPRIMARY(chan), ("not primary channel"));
1294		TAILQ_REMOVE(&sc->vmbus_prichans, chan, ch_prilink);
1295		mtx_unlock(&sc->vmbus_prichan_lock);
1296
1297		vmbus_delete_child(chan);
1298		vmbus_chan_free(chan);
1299
1300		mtx_lock(&sc->vmbus_prichan_lock);
1301	}
1302	bzero(sc->vmbus_chmap,
1303	    sizeof(struct hv_vmbus_channel *) * VMBUS_CHAN_MAX);
1304	mtx_unlock(&sc->vmbus_prichan_lock);
1305}
1306
1307/**
1308 * @brief Select the best outgoing channel
1309 *
1310 * The channel whose vcpu binding is closest to the currect vcpu will
1311 * be selected.
1312 * If no multi-channel, always select primary channel
1313 *
1314 * @param primary - primary channel
1315 */
1316struct hv_vmbus_channel *
1317vmbus_select_outgoing_channel(struct hv_vmbus_channel *primary)
1318{
1319	hv_vmbus_channel *new_channel = NULL;
1320	hv_vmbus_channel *outgoing_channel = primary;
1321	int old_cpu_distance = 0;
1322	int new_cpu_distance = 0;
1323	int cur_vcpu = 0;
1324	int smp_pro_id = PCPU_GET(cpuid);
1325
1326	if (TAILQ_EMPTY(&primary->ch_subchans)) {
1327		return outgoing_channel;
1328	}
1329
1330	if (smp_pro_id >= MAXCPU) {
1331		return outgoing_channel;
1332	}
1333
1334	cur_vcpu = VMBUS_PCPU_GET(primary->vmbus_sc, vcpuid, smp_pro_id);
1335
1336	/* XXX need lock */
1337	TAILQ_FOREACH(new_channel, &primary->ch_subchans, ch_sublink) {
1338		if ((new_channel->ch_stflags & VMBUS_CHAN_ST_OPENED) == 0) {
1339			continue;
1340		}
1341
1342		if (new_channel->ch_vcpuid == cur_vcpu){
1343			return new_channel;
1344		}
1345
1346		old_cpu_distance = ((outgoing_channel->ch_vcpuid > cur_vcpu) ?
1347		    (outgoing_channel->ch_vcpuid - cur_vcpu) :
1348		    (cur_vcpu - outgoing_channel->ch_vcpuid));
1349
1350		new_cpu_distance = ((new_channel->ch_vcpuid > cur_vcpu) ?
1351		    (new_channel->ch_vcpuid - cur_vcpu) :
1352		    (cur_vcpu - new_channel->ch_vcpuid));
1353
1354		if (old_cpu_distance < new_cpu_distance) {
1355			continue;
1356		}
1357
1358		outgoing_channel = new_channel;
1359	}
1360
1361	return(outgoing_channel);
1362}
1363
1364struct hv_vmbus_channel **
1365vmbus_get_subchan(struct hv_vmbus_channel *pri_chan, int subchan_cnt)
1366{
1367	struct hv_vmbus_channel **ret, *chan;
1368	int i;
1369
1370	ret = malloc(subchan_cnt * sizeof(struct hv_vmbus_channel *), M_TEMP,
1371	    M_WAITOK);
1372
1373	mtx_lock(&pri_chan->ch_subchan_lock);
1374
1375	while (pri_chan->ch_subchan_cnt < subchan_cnt)
1376		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "subch", 0);
1377
1378	i = 0;
1379	TAILQ_FOREACH(chan, &pri_chan->ch_subchans, ch_sublink) {
1380		/* TODO: refcnt chan */
1381		ret[i] = chan;
1382
1383		++i;
1384		if (i == subchan_cnt)
1385			break;
1386	}
1387	KASSERT(i == subchan_cnt, ("invalid subchan count %d, should be %d",
1388	    pri_chan->ch_subchan_cnt, subchan_cnt));
1389
1390	mtx_unlock(&pri_chan->ch_subchan_lock);
1391
1392	return ret;
1393}
1394
1395void
1396vmbus_rel_subchan(struct hv_vmbus_channel **subchan, int subchan_cnt __unused)
1397{
1398
1399	free(subchan, M_TEMP);
1400}
1401
1402void
1403vmbus_drain_subchan(struct hv_vmbus_channel *pri_chan)
1404{
1405	mtx_lock(&pri_chan->ch_subchan_lock);
1406	while (pri_chan->ch_subchan_cnt > 0)
1407		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "dsubch", 0);
1408	mtx_unlock(&pri_chan->ch_subchan_lock);
1409}
1410
1411void
1412vmbus_chan_msgproc(struct vmbus_softc *sc, const struct vmbus_message *msg)
1413{
1414	vmbus_chanmsg_proc_t msg_proc;
1415	uint32_t msg_type;
1416
1417	msg_type = ((const struct vmbus_chanmsg_hdr *)msg->msg_data)->chm_type;
1418	KASSERT(msg_type < VMBUS_CHANMSG_TYPE_MAX,
1419	    ("invalid message type %u", msg_type));
1420
1421	msg_proc = vmbus_chan_msgprocs[msg_type];
1422	if (msg_proc != NULL)
1423		msg_proc(sc, msg);
1424}
1425