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