xref: /freebsd/sys/dev/hyperv/vmbus/vmbus_chan.c (revision 69718b786d3943ea9a99eeeb5f5f6162f11c78b7)
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/bus.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/mutex.h>
38 #include <sys/smp.h>
39 #include <sys/sysctl.h>
40 #include <sys/systm.h>
41 
42 #include <machine/atomic.h>
43 #include <machine/stdarg.h>
44 
45 #include <dev/hyperv/include/hyperv_busdma.h>
46 #include <dev/hyperv/include/vmbus_xact.h>
47 #include <dev/hyperv/vmbus/hyperv_var.h>
48 #include <dev/hyperv/vmbus/vmbus_reg.h>
49 #include <dev/hyperv/vmbus/vmbus_var.h>
50 #include <dev/hyperv/vmbus/vmbus_brvar.h>
51 #include <dev/hyperv/vmbus/vmbus_chanvar.h>
52 
53 static void			vmbus_chan_update_evtflagcnt(
54 				    struct vmbus_softc *,
55 				    const struct vmbus_channel *);
56 static int			vmbus_chan_close_internal(
57 				    struct vmbus_channel *);
58 static int			vmbus_chan_sysctl_mnf(SYSCTL_HANDLER_ARGS);
59 static void			vmbus_chan_sysctl_create(
60 				    struct vmbus_channel *);
61 static struct vmbus_channel	*vmbus_chan_alloc(struct vmbus_softc *);
62 static void			vmbus_chan_free(struct vmbus_channel *);
63 static int			vmbus_chan_add(struct vmbus_channel *);
64 static void			vmbus_chan_cpu_default(struct vmbus_channel *);
65 static int			vmbus_chan_release(struct vmbus_channel *);
66 static void			vmbus_chan_set_chmap(struct vmbus_channel *);
67 static void			vmbus_chan_clear_chmap(struct vmbus_channel *);
68 static void			vmbus_chan_detach(struct vmbus_channel *);
69 static bool			vmbus_chan_wait_revoke(
70 				    const struct vmbus_channel *);
71 
72 static void			vmbus_chan_ins_prilist(struct vmbus_softc *,
73 				    struct vmbus_channel *);
74 static void			vmbus_chan_rem_prilist(struct vmbus_softc *,
75 				    struct vmbus_channel *);
76 static void			vmbus_chan_ins_list(struct vmbus_softc *,
77 				    struct vmbus_channel *);
78 static void			vmbus_chan_rem_list(struct vmbus_softc *,
79 				    struct vmbus_channel *);
80 static void			vmbus_chan_ins_sublist(struct vmbus_channel *,
81 				    struct vmbus_channel *);
82 static void			vmbus_chan_rem_sublist(struct vmbus_channel *,
83 				    struct vmbus_channel *);
84 
85 static void			vmbus_chan_task(void *, int);
86 static void			vmbus_chan_task_nobatch(void *, int);
87 static void			vmbus_chan_clrchmap_task(void *, int);
88 static void			vmbus_prichan_attach_task(void *, int);
89 static void			vmbus_subchan_attach_task(void *, int);
90 static void			vmbus_prichan_detach_task(void *, int);
91 static void			vmbus_subchan_detach_task(void *, int);
92 
93 static void			vmbus_chan_msgproc_choffer(struct vmbus_softc *,
94 				    const struct vmbus_message *);
95 static void			vmbus_chan_msgproc_chrescind(
96 				    struct vmbus_softc *,
97 				    const struct vmbus_message *);
98 
99 static int			vmbus_chan_printf(const struct vmbus_channel *,
100 				    const char *, ...) __printflike(2, 3);
101 
102 /*
103  * Vmbus channel message processing.
104  */
105 static const vmbus_chanmsg_proc_t
106 vmbus_chan_msgprocs[VMBUS_CHANMSG_TYPE_MAX] = {
107 	VMBUS_CHANMSG_PROC(CHOFFER,	vmbus_chan_msgproc_choffer),
108 	VMBUS_CHANMSG_PROC(CHRESCIND,	vmbus_chan_msgproc_chrescind),
109 
110 	VMBUS_CHANMSG_PROC_WAKEUP(CHOPEN_RESP),
111 	VMBUS_CHANMSG_PROC_WAKEUP(GPADL_CONNRESP),
112 	VMBUS_CHANMSG_PROC_WAKEUP(GPADL_DISCONNRESP)
113 };
114 
115 /*
116  * Notify host that there are data pending on our TX bufring.
117  */
118 static __inline void
119 vmbus_chan_signal_tx(const struct vmbus_channel *chan)
120 {
121 	atomic_set_long(chan->ch_evtflag, chan->ch_evtflag_mask);
122 	if (chan->ch_txflags & VMBUS_CHAN_TXF_HASMNF)
123 		atomic_set_int(chan->ch_montrig, chan->ch_montrig_mask);
124 	else
125 		hypercall_signal_event(chan->ch_monprm_dma.hv_paddr);
126 }
127 
128 static void
129 vmbus_chan_ins_prilist(struct vmbus_softc *sc, struct vmbus_channel *chan)
130 {
131 
132 	mtx_assert(&sc->vmbus_prichan_lock, MA_OWNED);
133 	if (atomic_testandset_int(&chan->ch_stflags,
134 	    VMBUS_CHAN_ST_ONPRIL_SHIFT))
135 		panic("channel is already on the prilist");
136 	TAILQ_INSERT_TAIL(&sc->vmbus_prichans, chan, ch_prilink);
137 }
138 
139 static void
140 vmbus_chan_rem_prilist(struct vmbus_softc *sc, struct vmbus_channel *chan)
141 {
142 
143 	mtx_assert(&sc->vmbus_prichan_lock, MA_OWNED);
144 	if (atomic_testandclear_int(&chan->ch_stflags,
145 	    VMBUS_CHAN_ST_ONPRIL_SHIFT) == 0)
146 		panic("channel is not on the prilist");
147 	TAILQ_REMOVE(&sc->vmbus_prichans, chan, ch_prilink);
148 }
149 
150 static void
151 vmbus_chan_ins_sublist(struct vmbus_channel *prichan,
152     struct vmbus_channel *chan)
153 {
154 
155 	mtx_assert(&prichan->ch_subchan_lock, MA_OWNED);
156 
157 	if (atomic_testandset_int(&chan->ch_stflags,
158 	    VMBUS_CHAN_ST_ONSUBL_SHIFT))
159 		panic("channel is already on the sublist");
160 	TAILQ_INSERT_TAIL(&prichan->ch_subchans, chan, ch_sublink);
161 
162 	/* Bump sub-channel count. */
163 	prichan->ch_subchan_cnt++;
164 }
165 
166 static void
167 vmbus_chan_rem_sublist(struct vmbus_channel *prichan,
168     struct vmbus_channel *chan)
169 {
170 
171 	mtx_assert(&prichan->ch_subchan_lock, MA_OWNED);
172 
173 	KASSERT(prichan->ch_subchan_cnt > 0,
174 	    ("invalid subchan_cnt %d", prichan->ch_subchan_cnt));
175 	prichan->ch_subchan_cnt--;
176 
177 	if (atomic_testandclear_int(&chan->ch_stflags,
178 	    VMBUS_CHAN_ST_ONSUBL_SHIFT) == 0)
179 		panic("channel is not on the sublist");
180 	TAILQ_REMOVE(&prichan->ch_subchans, chan, ch_sublink);
181 }
182 
183 static void
184 vmbus_chan_ins_list(struct vmbus_softc *sc, struct vmbus_channel *chan)
185 {
186 
187 	mtx_assert(&sc->vmbus_chan_lock, MA_OWNED);
188 	if (atomic_testandset_int(&chan->ch_stflags,
189 	    VMBUS_CHAN_ST_ONLIST_SHIFT))
190 		panic("channel is already on the list");
191 	TAILQ_INSERT_TAIL(&sc->vmbus_chans, chan, ch_link);
192 }
193 
194 static void
195 vmbus_chan_rem_list(struct vmbus_softc *sc, struct vmbus_channel *chan)
196 {
197 
198 	mtx_assert(&sc->vmbus_chan_lock, MA_OWNED);
199 	if (atomic_testandclear_int(&chan->ch_stflags,
200 	    VMBUS_CHAN_ST_ONLIST_SHIFT) == 0)
201 		panic("channel is not on the list");
202 	TAILQ_REMOVE(&sc->vmbus_chans, chan, ch_link);
203 }
204 
205 static int
206 vmbus_chan_sysctl_mnf(SYSCTL_HANDLER_ARGS)
207 {
208 	struct vmbus_channel *chan = arg1;
209 	int mnf = 0;
210 
211 	if (chan->ch_txflags & VMBUS_CHAN_TXF_HASMNF)
212 		mnf = 1;
213 	return sysctl_handle_int(oidp, &mnf, 0, req);
214 }
215 
216 static void
217 vmbus_chan_sysctl_create(struct vmbus_channel *chan)
218 {
219 	struct sysctl_oid *ch_tree, *chid_tree, *br_tree;
220 	struct sysctl_ctx_list *ctx;
221 	uint32_t ch_id;
222 	char name[16];
223 
224 	/*
225 	 * Add sysctl nodes related to this channel to this
226 	 * channel's sysctl ctx, so that they can be destroyed
227 	 * independently upon close of this channel, which can
228 	 * happen even if the device is not detached.
229 	 */
230 	ctx = &chan->ch_sysctl_ctx;
231 	sysctl_ctx_init(ctx);
232 
233 	/*
234 	 * Create dev.NAME.UNIT.channel tree.
235 	 */
236 	ch_tree = SYSCTL_ADD_NODE(ctx,
237 	    SYSCTL_CHILDREN(device_get_sysctl_tree(chan->ch_dev)),
238 	    OID_AUTO, "channel", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
239 	if (ch_tree == NULL)
240 		return;
241 
242 	/*
243 	 * Create dev.NAME.UNIT.channel.CHANID tree.
244 	 */
245 	if (VMBUS_CHAN_ISPRIMARY(chan))
246 		ch_id = chan->ch_id;
247 	else
248 		ch_id = chan->ch_prichan->ch_id;
249 	snprintf(name, sizeof(name), "%d", ch_id);
250 	chid_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(ch_tree),
251 	    OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
252 	if (chid_tree == NULL)
253 		return;
254 
255 	if (!VMBUS_CHAN_ISPRIMARY(chan)) {
256 		/*
257 		 * Create dev.NAME.UNIT.channel.CHANID.sub tree.
258 		 */
259 		ch_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(chid_tree),
260 		    OID_AUTO, "sub", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
261 		if (ch_tree == NULL)
262 			return;
263 
264 		/*
265 		 * Create dev.NAME.UNIT.channel.CHANID.sub.SUBIDX tree.
266 		 *
267 		 * NOTE:
268 		 * chid_tree is changed to this new sysctl tree.
269 		 */
270 		snprintf(name, sizeof(name), "%d", chan->ch_subidx);
271 		chid_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(ch_tree),
272 		    OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
273 		if (chid_tree == NULL)
274 			return;
275 
276 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
277 		    "chanid", CTLFLAG_RD, &chan->ch_id, 0, "channel id");
278 	}
279 
280 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
281 	    "cpu", CTLFLAG_RD, &chan->ch_cpuid, 0, "owner CPU id");
282 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
283 	    "mnf", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
284 	    chan, 0, vmbus_chan_sysctl_mnf, "I",
285 	    "has monitor notification facilities");
286 
287 	br_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
288 	    "br", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
289 	if (br_tree != NULL) {
290 		/*
291 		 * Create sysctl tree for RX bufring.
292 		 */
293 		vmbus_br_sysctl_create(ctx, br_tree, &chan->ch_rxbr.rxbr, "rx");
294 		/*
295 		 * Create sysctl tree for TX bufring.
296 		 */
297 		vmbus_br_sysctl_create(ctx, br_tree, &chan->ch_txbr.txbr, "tx");
298 	}
299 }
300 
301 int
302 vmbus_chan_open(struct vmbus_channel *chan, int txbr_size, int rxbr_size,
303     const void *udata, int udlen, vmbus_chan_callback_t cb, void *cbarg)
304 {
305 	struct vmbus_chan_br cbr;
306 	int error;
307 
308 	/*
309 	 * Allocate the TX+RX bufrings.
310 	 */
311 	KASSERT(chan->ch_bufring == NULL, ("bufrings are allocated"));
312 	chan->ch_bufring = hyperv_dmamem_alloc(bus_get_dma_tag(chan->ch_dev),
313 	    PAGE_SIZE, 0, txbr_size + rxbr_size, &chan->ch_bufring_dma,
314 	    BUS_DMA_WAITOK);
315 	if (chan->ch_bufring == NULL) {
316 		vmbus_chan_printf(chan, "bufring allocation failed\n");
317 		return (ENOMEM);
318 	}
319 
320 	cbr.cbr = chan->ch_bufring;
321 	cbr.cbr_paddr = chan->ch_bufring_dma.hv_paddr;
322 	cbr.cbr_txsz = txbr_size;
323 	cbr.cbr_rxsz = rxbr_size;
324 
325 	error = vmbus_chan_open_br(chan, &cbr, udata, udlen, cb, cbarg);
326 	if (error) {
327 		if (error == EISCONN) {
328 			/*
329 			 * XXX
330 			 * The bufring GPADL is still connected; abandon
331 			 * this bufring, instead of having mysterious
332 			 * crash or trashed data later on.
333 			 */
334 			vmbus_chan_printf(chan, "chan%u bufring GPADL "
335 			    "is still connected upon channel open error; "
336 			    "leak %d bytes memory\n", chan->ch_id,
337 			    txbr_size + rxbr_size);
338 		} else {
339 			hyperv_dmamem_free(&chan->ch_bufring_dma,
340 			    chan->ch_bufring);
341 		}
342 		chan->ch_bufring = NULL;
343 	}
344 	return (error);
345 }
346 
347 int
348 vmbus_chan_open_br(struct vmbus_channel *chan, const struct vmbus_chan_br *cbr,
349     const void *udata, int udlen, vmbus_chan_callback_t cb, void *cbarg)
350 {
351 	struct vmbus_softc *sc = chan->ch_vmbus;
352 	const struct vmbus_message *msg;
353 	struct vmbus_chanmsg_chopen *req;
354 	struct vmbus_msghc *mh;
355 	uint32_t status;
356 	int error, txbr_size, rxbr_size;
357 	task_fn_t *task_fn;
358 	uint8_t *br;
359 
360 	if (udlen > VMBUS_CHANMSG_CHOPEN_UDATA_SIZE) {
361 		vmbus_chan_printf(chan,
362 		    "invalid udata len %d for chan%u\n", udlen, chan->ch_id);
363 		return (EINVAL);
364 	}
365 
366 	br = cbr->cbr;
367 	txbr_size = cbr->cbr_txsz;
368 	rxbr_size = cbr->cbr_rxsz;
369 	KASSERT((txbr_size & PAGE_MASK) == 0,
370 	    ("send bufring size is not multiple page"));
371 	KASSERT((rxbr_size & PAGE_MASK) == 0,
372 	    ("recv bufring size is not multiple page"));
373 	KASSERT((cbr->cbr_paddr & PAGE_MASK) == 0,
374 	    ("bufring is not page aligned"));
375 
376 	/*
377 	 * Zero out the TX/RX bufrings, in case that they were used before.
378 	 */
379 	memset(br, 0, txbr_size + rxbr_size);
380 
381 	if (atomic_testandset_int(&chan->ch_stflags,
382 	    VMBUS_CHAN_ST_OPENED_SHIFT))
383 		panic("double-open chan%u", chan->ch_id);
384 
385 	chan->ch_cb = cb;
386 	chan->ch_cbarg = cbarg;
387 
388 	vmbus_chan_update_evtflagcnt(sc, chan);
389 
390 	chan->ch_tq = VMBUS_PCPU_GET(chan->ch_vmbus, event_tq, chan->ch_cpuid);
391 	if (chan->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD)
392 		task_fn = vmbus_chan_task;
393 	else
394 		task_fn = vmbus_chan_task_nobatch;
395 	TASK_INIT(&chan->ch_task, 0, task_fn, chan);
396 
397 	/* TX bufring comes first */
398 	vmbus_txbr_setup(&chan->ch_txbr, br, txbr_size);
399 	/* RX bufring immediately follows TX bufring */
400 	vmbus_rxbr_setup(&chan->ch_rxbr, br + txbr_size, rxbr_size);
401 
402 	/* Create sysctl tree for this channel */
403 	vmbus_chan_sysctl_create(chan);
404 
405 	/*
406 	 * Connect the bufrings, both RX and TX, to this channel.
407 	 */
408 	error = vmbus_chan_gpadl_connect(chan, cbr->cbr_paddr,
409 	    txbr_size + rxbr_size, &chan->ch_bufring_gpadl);
410 	if (error) {
411 		vmbus_chan_printf(chan,
412 		    "failed to connect bufring GPADL to chan%u\n", chan->ch_id);
413 		goto failed;
414 	}
415 
416 	/*
417 	 * Install this channel, before it is opened, but after everything
418 	 * else has been setup.
419 	 */
420 	vmbus_chan_set_chmap(chan);
421 
422 	/*
423 	 * Open channel w/ the bufring GPADL on the target CPU.
424 	 */
425 	mh = vmbus_msghc_get(sc, sizeof(*req));
426 	if (mh == NULL) {
427 		vmbus_chan_printf(chan,
428 		    "can not get msg hypercall for chopen(chan%u)\n",
429 		    chan->ch_id);
430 		error = ENXIO;
431 		goto failed;
432 	}
433 
434 	req = vmbus_msghc_dataptr(mh);
435 	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHOPEN;
436 	req->chm_chanid = chan->ch_id;
437 	req->chm_openid = chan->ch_id;
438 	req->chm_gpadl = chan->ch_bufring_gpadl;
439 	req->chm_vcpuid = chan->ch_vcpuid;
440 	req->chm_txbr_pgcnt = txbr_size >> PAGE_SHIFT;
441 	if (udlen > 0)
442 		memcpy(req->chm_udata, udata, udlen);
443 
444 	error = vmbus_msghc_exec(sc, mh);
445 	if (error) {
446 		vmbus_chan_printf(chan,
447 		    "chopen(chan%u) msg hypercall exec failed: %d\n",
448 		    chan->ch_id, error);
449 		vmbus_msghc_put(sc, mh);
450 		goto failed;
451 	}
452 
453 	for (;;) {
454 		msg = vmbus_msghc_poll_result(sc, mh);
455 		if (msg != NULL)
456 			break;
457 		if (vmbus_chan_is_revoked(chan)) {
458 			int i;
459 
460 			/*
461 			 * NOTE:
462 			 * Hypervisor does _not_ send response CHOPEN to
463 			 * a revoked channel.
464 			 */
465 			vmbus_chan_printf(chan,
466 			    "chan%u is revoked, when it is being opened\n",
467 			    chan->ch_id);
468 
469 			/*
470 			 * XXX
471 			 * Add extra delay before cancel the hypercall
472 			 * execution; mainly to close any possible
473 			 * CHRESCIND and CHOPEN_RESP races on the
474 			 * hypervisor side.
475 			 */
476 #define REVOKE_LINGER	100
477 			for (i = 0; i < REVOKE_LINGER; ++i) {
478 				msg = vmbus_msghc_poll_result(sc, mh);
479 				if (msg != NULL)
480 					break;
481 				DELAY(1000);
482 			}
483 #undef REVOKE_LINGER
484 			if (msg == NULL)
485 				vmbus_msghc_exec_cancel(sc, mh);
486 			break;
487 		}
488 		DELAY(1000);
489 	}
490 	if (msg != NULL) {
491 		status = ((const struct vmbus_chanmsg_chopen_resp *)
492 		    msg->msg_data)->chm_status;
493 	} else {
494 		/* XXX any non-0 value is ok here. */
495 		status = 0xff;
496 	}
497 
498 	vmbus_msghc_put(sc, mh);
499 
500 	if (status == 0) {
501 		if (bootverbose)
502 			vmbus_chan_printf(chan, "chan%u opened\n", chan->ch_id);
503 		return (0);
504 	}
505 
506 	vmbus_chan_printf(chan, "failed to open chan%u\n", chan->ch_id);
507 	error = ENXIO;
508 
509 failed:
510 	sysctl_ctx_free(&chan->ch_sysctl_ctx);
511 	vmbus_chan_clear_chmap(chan);
512 	if (chan->ch_bufring_gpadl != 0) {
513 		int error1;
514 
515 		error1 = vmbus_chan_gpadl_disconnect(chan,
516 		    chan->ch_bufring_gpadl);
517 		if (error1) {
518 			/*
519 			 * Give caller a hint that the bufring GPADL is still
520 			 * connected.
521 			 */
522 			error = EISCONN;
523 		}
524 		chan->ch_bufring_gpadl = 0;
525 	}
526 	atomic_clear_int(&chan->ch_stflags, VMBUS_CHAN_ST_OPENED);
527 	return (error);
528 }
529 
530 int
531 vmbus_chan_gpadl_connect(struct vmbus_channel *chan, bus_addr_t paddr,
532     int size, uint32_t *gpadl0)
533 {
534 	struct vmbus_softc *sc = chan->ch_vmbus;
535 	struct vmbus_msghc *mh;
536 	struct vmbus_chanmsg_gpadl_conn *req;
537 	const struct vmbus_message *msg;
538 	size_t reqsz;
539 	uint32_t gpadl, status;
540 	int page_count, range_len, i, cnt, error;
541 	uint64_t page_id;
542 
543 	KASSERT(*gpadl0 == 0, ("GPADL is not zero"));
544 
545 	/*
546 	 * Preliminary checks.
547 	 */
548 
549 	KASSERT((size & PAGE_MASK) == 0,
550 	    ("invalid GPA size %d, not multiple page size", size));
551 	page_count = size >> PAGE_SHIFT;
552 
553 	KASSERT((paddr & PAGE_MASK) == 0,
554 	    ("GPA is not page aligned %jx", (uintmax_t)paddr));
555 	page_id = paddr >> PAGE_SHIFT;
556 
557 	range_len = __offsetof(struct vmbus_gpa_range, gpa_page[page_count]);
558 	/*
559 	 * We don't support multiple GPA ranges.
560 	 */
561 	if (range_len > UINT16_MAX) {
562 		vmbus_chan_printf(chan, "GPA too large, %d pages\n",
563 		    page_count);
564 		return EOPNOTSUPP;
565 	}
566 
567 	/*
568 	 * Allocate GPADL id.
569 	 */
570 	gpadl = vmbus_gpadl_alloc(sc);
571 
572 	/*
573 	 * Connect this GPADL to the target channel.
574 	 *
575 	 * NOTE:
576 	 * Since each message can only hold small set of page
577 	 * addresses, several messages may be required to
578 	 * complete the connection.
579 	 */
580 	if (page_count > VMBUS_CHANMSG_GPADL_CONN_PGMAX)
581 		cnt = VMBUS_CHANMSG_GPADL_CONN_PGMAX;
582 	else
583 		cnt = page_count;
584 	page_count -= cnt;
585 
586 	reqsz = __offsetof(struct vmbus_chanmsg_gpadl_conn,
587 	    chm_range.gpa_page[cnt]);
588 	mh = vmbus_msghc_get(sc, reqsz);
589 	if (mh == NULL) {
590 		vmbus_chan_printf(chan,
591 		    "can not get msg hypercall for gpadl_conn(chan%u)\n",
592 		    chan->ch_id);
593 		return EIO;
594 	}
595 
596 	req = vmbus_msghc_dataptr(mh);
597 	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_CONN;
598 	req->chm_chanid = chan->ch_id;
599 	req->chm_gpadl = gpadl;
600 	req->chm_range_len = range_len;
601 	req->chm_range_cnt = 1;
602 	req->chm_range.gpa_len = size;
603 	req->chm_range.gpa_ofs = 0;
604 	for (i = 0; i < cnt; ++i)
605 		req->chm_range.gpa_page[i] = page_id++;
606 
607 	error = vmbus_msghc_exec(sc, mh);
608 	if (error) {
609 		vmbus_chan_printf(chan,
610 		    "gpadl_conn(chan%u) msg hypercall exec failed: %d\n",
611 		    chan->ch_id, error);
612 		vmbus_msghc_put(sc, mh);
613 		return error;
614 	}
615 
616 	while (page_count > 0) {
617 		struct vmbus_chanmsg_gpadl_subconn *subreq;
618 
619 		if (page_count > VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX)
620 			cnt = VMBUS_CHANMSG_GPADL_SUBCONN_PGMAX;
621 		else
622 			cnt = page_count;
623 		page_count -= cnt;
624 
625 		reqsz = __offsetof(struct vmbus_chanmsg_gpadl_subconn,
626 		    chm_gpa_page[cnt]);
627 		vmbus_msghc_reset(mh, reqsz);
628 
629 		subreq = vmbus_msghc_dataptr(mh);
630 		subreq->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_SUBCONN;
631 		subreq->chm_gpadl = gpadl;
632 		for (i = 0; i < cnt; ++i)
633 			subreq->chm_gpa_page[i] = page_id++;
634 
635 		vmbus_msghc_exec_noresult(mh);
636 	}
637 	KASSERT(page_count == 0, ("invalid page count %d", page_count));
638 
639 	msg = vmbus_msghc_wait_result(sc, mh);
640 	status = ((const struct vmbus_chanmsg_gpadl_connresp *)
641 	    msg->msg_data)->chm_status;
642 
643 	vmbus_msghc_put(sc, mh);
644 
645 	if (status != 0) {
646 		vmbus_chan_printf(chan, "gpadl_conn(chan%u) failed: %u\n",
647 		    chan->ch_id, status);
648 		return EIO;
649 	}
650 
651 	/* Done; commit the GPADL id. */
652 	*gpadl0 = gpadl;
653 	if (bootverbose) {
654 		vmbus_chan_printf(chan, "gpadl_conn(chan%u) succeeded\n",
655 		    chan->ch_id);
656 	}
657 	return 0;
658 }
659 
660 static bool
661 vmbus_chan_wait_revoke(const struct vmbus_channel *chan)
662 {
663 #define WAIT_COUNT	200	/* 200ms */
664 
665 	int i;
666 
667 	for (i = 0; i < WAIT_COUNT; ++i) {
668 		if (vmbus_chan_is_revoked(chan))
669 			return (true);
670 		/* Not sure about the context; use busy-wait. */
671 		DELAY(1000);
672 	}
673 	return (false);
674 
675 #undef WAIT_COUNT
676 }
677 
678 /*
679  * Disconnect the GPA from the target channel
680  */
681 int
682 vmbus_chan_gpadl_disconnect(struct vmbus_channel *chan, uint32_t gpadl)
683 {
684 	struct vmbus_softc *sc = chan->ch_vmbus;
685 	struct vmbus_msghc *mh;
686 	struct vmbus_chanmsg_gpadl_disconn *req;
687 	int error;
688 
689 	KASSERT(gpadl != 0, ("GPADL is zero"));
690 
691 	mh = vmbus_msghc_get(sc, sizeof(*req));
692 	if (mh == NULL) {
693 		vmbus_chan_printf(chan,
694 		    "can not get msg hypercall for gpadl_disconn(chan%u)\n",
695 		    chan->ch_id);
696 		return (EBUSY);
697 	}
698 
699 	req = vmbus_msghc_dataptr(mh);
700 	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_GPADL_DISCONN;
701 	req->chm_chanid = chan->ch_id;
702 	req->chm_gpadl = gpadl;
703 
704 	error = vmbus_msghc_exec(sc, mh);
705 	if (error) {
706 		vmbus_msghc_put(sc, mh);
707 
708 		if (vmbus_chan_wait_revoke(chan)) {
709 			/*
710 			 * Error is benign; this channel is revoked,
711 			 * so this GPADL will not be touched anymore.
712 			 */
713 			vmbus_chan_printf(chan,
714 			    "gpadl_disconn(revoked chan%u) msg hypercall "
715 			    "exec failed: %d\n", chan->ch_id, error);
716 			return (0);
717 		}
718 		vmbus_chan_printf(chan,
719 		    "gpadl_disconn(chan%u) msg hypercall exec failed: %d\n",
720 		    chan->ch_id, error);
721 		return (error);
722 	}
723 
724 	vmbus_msghc_wait_result(sc, mh);
725 	/* Discard result; no useful information */
726 	vmbus_msghc_put(sc, mh);
727 
728 	return (0);
729 }
730 
731 static void
732 vmbus_chan_detach(struct vmbus_channel *chan)
733 {
734 	int refs;
735 
736 	KASSERT(chan->ch_refs > 0, ("chan%u: invalid refcnt %d",
737 	    chan->ch_id, chan->ch_refs));
738 	refs = atomic_fetchadd_int(&chan->ch_refs, -1);
739 #ifdef INVARIANTS
740 	if (VMBUS_CHAN_ISPRIMARY(chan)) {
741 		KASSERT(refs == 1, ("chan%u: invalid refcnt %d for prichan",
742 		    chan->ch_id, refs + 1));
743 	}
744 #endif
745 	if (refs == 1) {
746 		/*
747 		 * Detach the target channel.
748 		 */
749 		if (bootverbose) {
750 			vmbus_chan_printf(chan, "chan%u detached\n",
751 			    chan->ch_id);
752 		}
753 		taskqueue_enqueue(chan->ch_mgmt_tq, &chan->ch_detach_task);
754 	}
755 }
756 
757 static void
758 vmbus_chan_clrchmap_task(void *xchan, int pending __unused)
759 {
760 	struct vmbus_channel *chan = xchan;
761 
762 	critical_enter();
763 	chan->ch_vmbus->vmbus_chmap[chan->ch_id] = NULL;
764 	critical_exit();
765 }
766 
767 static void
768 vmbus_chan_clear_chmap(struct vmbus_channel *chan)
769 {
770 	struct task chmap_task;
771 
772 	TASK_INIT(&chmap_task, 0, vmbus_chan_clrchmap_task, chan);
773 	taskqueue_enqueue(chan->ch_tq, &chmap_task);
774 	taskqueue_drain(chan->ch_tq, &chmap_task);
775 }
776 
777 static void
778 vmbus_chan_set_chmap(struct vmbus_channel *chan)
779 {
780 	__compiler_membar();
781 	chan->ch_vmbus->vmbus_chmap[chan->ch_id] = chan;
782 }
783 
784 static int
785 vmbus_chan_close_internal(struct vmbus_channel *chan)
786 {
787 	struct vmbus_softc *sc = chan->ch_vmbus;
788 	struct vmbus_msghc *mh;
789 	struct vmbus_chanmsg_chclose *req;
790 	uint32_t old_stflags;
791 	int error;
792 
793 	/*
794 	 * NOTE:
795 	 * Sub-channels are closed upon their primary channel closing,
796 	 * so they can be closed even before they are opened.
797 	 */
798 	for (;;) {
799 		old_stflags = chan->ch_stflags;
800 		if (atomic_cmpset_int(&chan->ch_stflags, old_stflags,
801 		    old_stflags & ~VMBUS_CHAN_ST_OPENED))
802 			break;
803 	}
804 	if ((old_stflags & VMBUS_CHAN_ST_OPENED) == 0) {
805 		/* Not opened yet; done */
806 		if (bootverbose) {
807 			vmbus_chan_printf(chan, "chan%u not opened\n",
808 			    chan->ch_id);
809 		}
810 		return (0);
811 	}
812 
813 	/*
814 	 * Free this channel's sysctl tree attached to its device's
815 	 * sysctl tree.
816 	 */
817 	sysctl_ctx_free(&chan->ch_sysctl_ctx);
818 
819 	/*
820 	 * NOTE:
821 	 * Order is critical.  This channel _must_ be uninstalled first,
822 	 * else the channel task may be enqueued by the IDT after it has
823 	 * been drained.
824 	 */
825 	vmbus_chan_clear_chmap(chan);
826 	taskqueue_drain(chan->ch_tq, &chan->ch_task);
827 	chan->ch_tq = NULL;
828 
829 	/*
830 	 * Close this channel.
831 	 */
832 	mh = vmbus_msghc_get(sc, sizeof(*req));
833 	if (mh == NULL) {
834 		vmbus_chan_printf(chan,
835 		    "can not get msg hypercall for chclose(chan%u)\n",
836 		    chan->ch_id);
837 		error = ENXIO;
838 		goto disconnect;
839 	}
840 
841 	req = vmbus_msghc_dataptr(mh);
842 	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHCLOSE;
843 	req->chm_chanid = chan->ch_id;
844 
845 	error = vmbus_msghc_exec_noresult(mh);
846 	vmbus_msghc_put(sc, mh);
847 
848 	if (error) {
849 		vmbus_chan_printf(chan,
850 		    "chclose(chan%u) msg hypercall exec failed: %d\n",
851 		    chan->ch_id, error);
852 		goto disconnect;
853 	}
854 
855 	if (bootverbose)
856 		vmbus_chan_printf(chan, "chan%u closed\n", chan->ch_id);
857 
858 disconnect:
859 	/*
860 	 * Disconnect the TX+RX bufrings from this channel.
861 	 */
862 	if (chan->ch_bufring_gpadl != 0) {
863 		int error1;
864 
865 		error1 = vmbus_chan_gpadl_disconnect(chan,
866 		    chan->ch_bufring_gpadl);
867 		if (error1) {
868 			/*
869 			 * XXX
870 			 * The bufring GPADL is still connected; abandon
871 			 * this bufring, instead of having mysterious
872 			 * crash or trashed data later on.
873 			 */
874 			vmbus_chan_printf(chan, "chan%u bufring GPADL "
875 			    "is still connected after close\n", chan->ch_id);
876 			chan->ch_bufring = NULL;
877 			/*
878 			 * Give caller a hint that the bufring GPADL is
879 			 * still connected.
880 			 */
881 			error = EISCONN;
882 		}
883 		chan->ch_bufring_gpadl = 0;
884 	}
885 
886 	/*
887 	 * Destroy the TX+RX bufrings.
888 	 */
889 	if (chan->ch_bufring != NULL) {
890 		hyperv_dmamem_free(&chan->ch_bufring_dma, chan->ch_bufring);
891 		chan->ch_bufring = NULL;
892 	}
893 	return (error);
894 }
895 
896 int
897 vmbus_chan_close_direct(struct vmbus_channel *chan)
898 {
899 	int error;
900 
901 #ifdef INVARIANTS
902 	if (VMBUS_CHAN_ISPRIMARY(chan)) {
903 		struct vmbus_channel *subchan;
904 
905 		/*
906 		 * All sub-channels _must_ have been closed, or are _not_
907 		 * opened at all.
908 		 */
909 		mtx_lock(&chan->ch_subchan_lock);
910 		TAILQ_FOREACH(subchan, &chan->ch_subchans, ch_sublink) {
911 			KASSERT(
912 			   (subchan->ch_stflags & VMBUS_CHAN_ST_OPENED) == 0,
913 			   ("chan%u: subchan%u is still opened",
914 			    chan->ch_id, subchan->ch_subidx));
915 		}
916 		mtx_unlock(&chan->ch_subchan_lock);
917 	}
918 #endif
919 
920 	error = vmbus_chan_close_internal(chan);
921 	if (!VMBUS_CHAN_ISPRIMARY(chan)) {
922 		/*
923 		 * This sub-channel is referenced, when it is linked to
924 		 * the primary channel; drop that reference now.
925 		 */
926 		vmbus_chan_detach(chan);
927 	}
928 	return (error);
929 }
930 
931 /*
932  * Caller should make sure that all sub-channels have
933  * been added to 'chan' and all to-be-closed channels
934  * are not being opened.
935  */
936 void
937 vmbus_chan_close(struct vmbus_channel *chan)
938 {
939 	int subchan_cnt;
940 
941 	if (!VMBUS_CHAN_ISPRIMARY(chan)) {
942 		/*
943 		 * Sub-channel is closed when its primary channel
944 		 * is closed; done.
945 		 */
946 		return;
947 	}
948 
949 	/*
950 	 * Close all sub-channels, if any.
951 	 */
952 	subchan_cnt = chan->ch_subchan_cnt;
953 	if (subchan_cnt > 0) {
954 		struct vmbus_channel **subchan;
955 		int i;
956 
957 		subchan = vmbus_subchan_get(chan, subchan_cnt);
958 		for (i = 0; i < subchan_cnt; ++i) {
959 			vmbus_chan_close_internal(subchan[i]);
960 			/*
961 			 * This sub-channel is referenced, when it is
962 			 * linked to the primary channel; drop that
963 			 * reference now.
964 			 */
965 			vmbus_chan_detach(subchan[i]);
966 		}
967 		vmbus_subchan_rel(subchan, subchan_cnt);
968 	}
969 
970 	/* Then close the primary channel. */
971 	vmbus_chan_close_internal(chan);
972 }
973 
974 void
975 vmbus_chan_intr_drain(struct vmbus_channel *chan)
976 {
977 
978 	taskqueue_drain(chan->ch_tq, &chan->ch_task);
979 }
980 
981 int
982 vmbus_chan_send(struct vmbus_channel *chan, uint16_t type, uint16_t flags,
983     void *data, int dlen, uint64_t xactid)
984 {
985 	struct vmbus_chanpkt pkt;
986 	int pktlen, pad_pktlen, hlen, error;
987 	uint64_t pad = 0;
988 	struct iovec iov[3];
989 	boolean_t send_evt;
990 
991 	hlen = sizeof(pkt);
992 	pktlen = hlen + dlen;
993 	pad_pktlen = VMBUS_CHANPKT_TOTLEN(pktlen);
994 	KASSERT(pad_pktlen <= vmbus_txbr_maxpktsz(&chan->ch_txbr),
995 	    ("invalid packet size %d", pad_pktlen));
996 
997 	pkt.cp_hdr.cph_type = type;
998 	pkt.cp_hdr.cph_flags = flags;
999 	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_hlen, hlen);
1000 	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_tlen, pad_pktlen);
1001 	pkt.cp_hdr.cph_xactid = xactid;
1002 
1003 	iov[0].iov_base = &pkt;
1004 	iov[0].iov_len = hlen;
1005 	iov[1].iov_base = data;
1006 	iov[1].iov_len = dlen;
1007 	iov[2].iov_base = &pad;
1008 	iov[2].iov_len = pad_pktlen - pktlen;
1009 
1010 	error = vmbus_txbr_write(&chan->ch_txbr, iov, 3, &send_evt);
1011 	if (!error && send_evt)
1012 		vmbus_chan_signal_tx(chan);
1013 	return error;
1014 }
1015 
1016 int
1017 vmbus_chan_send_sglist(struct vmbus_channel *chan,
1018     struct vmbus_gpa sg[], int sglen, void *data, int dlen, uint64_t xactid)
1019 {
1020 	struct vmbus_chanpkt_sglist pkt;
1021 	int pktlen, pad_pktlen, hlen, error;
1022 	struct iovec iov[4];
1023 	boolean_t send_evt;
1024 	uint64_t pad = 0;
1025 
1026 	hlen = __offsetof(struct vmbus_chanpkt_sglist, cp_gpa[sglen]);
1027 	pktlen = hlen + dlen;
1028 	pad_pktlen = VMBUS_CHANPKT_TOTLEN(pktlen);
1029 	KASSERT(pad_pktlen <= vmbus_txbr_maxpktsz(&chan->ch_txbr),
1030 	    ("invalid packet size %d", pad_pktlen));
1031 
1032 	pkt.cp_hdr.cph_type = VMBUS_CHANPKT_TYPE_GPA;
1033 	pkt.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
1034 	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_hlen, hlen);
1035 	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_tlen, pad_pktlen);
1036 	pkt.cp_hdr.cph_xactid = xactid;
1037 	pkt.cp_rsvd = 0;
1038 	pkt.cp_gpa_cnt = sglen;
1039 
1040 	iov[0].iov_base = &pkt;
1041 	iov[0].iov_len = sizeof(pkt);
1042 	iov[1].iov_base = sg;
1043 	iov[1].iov_len = sizeof(struct vmbus_gpa) * sglen;
1044 	iov[2].iov_base = data;
1045 	iov[2].iov_len = dlen;
1046 	iov[3].iov_base = &pad;
1047 	iov[3].iov_len = pad_pktlen - pktlen;
1048 
1049 	error = vmbus_txbr_write(&chan->ch_txbr, iov, 4, &send_evt);
1050 	if (!error && send_evt)
1051 		vmbus_chan_signal_tx(chan);
1052 	return error;
1053 }
1054 
1055 int
1056 vmbus_chan_send_prplist(struct vmbus_channel *chan,
1057     struct vmbus_gpa_range *prp, int prp_cnt, void *data, int dlen,
1058     uint64_t xactid)
1059 {
1060 	struct vmbus_chanpkt_prplist pkt;
1061 	int pktlen, pad_pktlen, hlen, error;
1062 	struct iovec iov[4];
1063 	boolean_t send_evt;
1064 	uint64_t pad = 0;
1065 
1066 	hlen = __offsetof(struct vmbus_chanpkt_prplist,
1067 	    cp_range[0].gpa_page[prp_cnt]);
1068 	pktlen = hlen + dlen;
1069 	pad_pktlen = VMBUS_CHANPKT_TOTLEN(pktlen);
1070 	KASSERT(pad_pktlen <= vmbus_txbr_maxpktsz(&chan->ch_txbr),
1071 	    ("invalid packet size %d", pad_pktlen));
1072 
1073 	pkt.cp_hdr.cph_type = VMBUS_CHANPKT_TYPE_GPA;
1074 	pkt.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
1075 	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_hlen, hlen);
1076 	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_tlen, pad_pktlen);
1077 	pkt.cp_hdr.cph_xactid = xactid;
1078 	pkt.cp_rsvd = 0;
1079 	pkt.cp_range_cnt = 1;
1080 
1081 	iov[0].iov_base = &pkt;
1082 	iov[0].iov_len = sizeof(pkt);
1083 	iov[1].iov_base = prp;
1084 	iov[1].iov_len = __offsetof(struct vmbus_gpa_range, gpa_page[prp_cnt]);
1085 	iov[2].iov_base = data;
1086 	iov[2].iov_len = dlen;
1087 	iov[3].iov_base = &pad;
1088 	iov[3].iov_len = pad_pktlen - pktlen;
1089 
1090 	error = vmbus_txbr_write(&chan->ch_txbr, iov, 4, &send_evt);
1091 	if (!error && send_evt)
1092 		vmbus_chan_signal_tx(chan);
1093 	return error;
1094 }
1095 
1096 int
1097 vmbus_chan_recv(struct vmbus_channel *chan, void *data, int *dlen0,
1098     uint64_t *xactid)
1099 {
1100 	struct vmbus_chanpkt_hdr pkt;
1101 	int error, dlen, hlen;
1102 
1103 	error = vmbus_rxbr_peek(&chan->ch_rxbr, &pkt, sizeof(pkt));
1104 	if (error)
1105 		return (error);
1106 
1107 	if (__predict_false(pkt.cph_hlen < VMBUS_CHANPKT_HLEN_MIN)) {
1108 		vmbus_chan_printf(chan, "invalid hlen %u\n", pkt.cph_hlen);
1109 		/* XXX this channel is dead actually. */
1110 		return (EIO);
1111 	}
1112 	if (__predict_false(pkt.cph_hlen > pkt.cph_tlen)) {
1113 		vmbus_chan_printf(chan, "invalid hlen %u and tlen %u\n",
1114 		    pkt.cph_hlen, pkt.cph_tlen);
1115 		/* XXX this channel is dead actually. */
1116 		return (EIO);
1117 	}
1118 
1119 	hlen = VMBUS_CHANPKT_GETLEN(pkt.cph_hlen);
1120 	dlen = VMBUS_CHANPKT_GETLEN(pkt.cph_tlen) - hlen;
1121 
1122 	if (*dlen0 < dlen) {
1123 		/* Return the size of this packet's data. */
1124 		*dlen0 = dlen;
1125 		return (ENOBUFS);
1126 	}
1127 
1128 	*xactid = pkt.cph_xactid;
1129 	*dlen0 = dlen;
1130 
1131 	/* Skip packet header */
1132 	error = vmbus_rxbr_read(&chan->ch_rxbr, data, dlen, hlen);
1133 	KASSERT(!error, ("vmbus_rxbr_read failed"));
1134 
1135 	return (0);
1136 }
1137 
1138 int
1139 vmbus_chan_recv_pkt(struct vmbus_channel *chan,
1140     struct vmbus_chanpkt_hdr *pkt, int *pktlen0)
1141 {
1142 	int error, pktlen, pkt_hlen;
1143 
1144 	pkt_hlen = sizeof(*pkt);
1145 	error = vmbus_rxbr_peek(&chan->ch_rxbr, pkt, pkt_hlen);
1146 	if (error)
1147 		return (error);
1148 
1149 	if (__predict_false(pkt->cph_hlen < VMBUS_CHANPKT_HLEN_MIN)) {
1150 		vmbus_chan_printf(chan, "invalid hlen %u\n", pkt->cph_hlen);
1151 		/* XXX this channel is dead actually. */
1152 		return (EIO);
1153 	}
1154 	if (__predict_false(pkt->cph_hlen > pkt->cph_tlen)) {
1155 		vmbus_chan_printf(chan, "invalid hlen %u and tlen %u\n",
1156 		    pkt->cph_hlen, pkt->cph_tlen);
1157 		/* XXX this channel is dead actually. */
1158 		return (EIO);
1159 	}
1160 
1161 	pktlen = VMBUS_CHANPKT_GETLEN(pkt->cph_tlen);
1162 	if (*pktlen0 < pktlen) {
1163 		/* Return the size of this packet. */
1164 		*pktlen0 = pktlen;
1165 		return (ENOBUFS);
1166 	}
1167 	*pktlen0 = pktlen;
1168 
1169 	/*
1170 	 * Skip the fixed-size packet header, which has been filled
1171 	 * by the above vmbus_rxbr_peek().
1172 	 */
1173 	error = vmbus_rxbr_read(&chan->ch_rxbr, pkt + 1,
1174 	    pktlen - pkt_hlen, pkt_hlen);
1175 	KASSERT(!error, ("vmbus_rxbr_read failed"));
1176 
1177 	return (0);
1178 }
1179 
1180 static void
1181 vmbus_chan_task(void *xchan, int pending __unused)
1182 {
1183 	struct vmbus_channel *chan = xchan;
1184 	vmbus_chan_callback_t cb = chan->ch_cb;
1185 	void *cbarg = chan->ch_cbarg;
1186 
1187 	/*
1188 	 * Optimize host to guest signaling by ensuring:
1189 	 * 1. While reading the channel, we disable interrupts from
1190 	 *    host.
1191 	 * 2. Ensure that we process all posted messages from the host
1192 	 *    before returning from this callback.
1193 	 * 3. Once we return, enable signaling from the host. Once this
1194 	 *    state is set we check to see if additional packets are
1195 	 *    available to read. In this case we repeat the process.
1196 	 *
1197 	 * NOTE: Interrupt has been disabled in the ISR.
1198 	 */
1199 	for (;;) {
1200 		uint32_t left;
1201 
1202 		cb(chan, cbarg);
1203 
1204 		left = vmbus_rxbr_intr_unmask(&chan->ch_rxbr);
1205 		if (left == 0) {
1206 			/* No more data in RX bufring; done */
1207 			break;
1208 		}
1209 		vmbus_rxbr_intr_mask(&chan->ch_rxbr);
1210 	}
1211 }
1212 
1213 static void
1214 vmbus_chan_task_nobatch(void *xchan, int pending __unused)
1215 {
1216 	struct vmbus_channel *chan = xchan;
1217 
1218 	chan->ch_cb(chan, chan->ch_cbarg);
1219 }
1220 
1221 static __inline void
1222 vmbus_event_flags_proc(struct vmbus_softc *sc, volatile u_long *event_flags,
1223     int flag_cnt)
1224 {
1225 	int f;
1226 
1227 	for (f = 0; f < flag_cnt; ++f) {
1228 		uint32_t chid_base;
1229 		u_long flags;
1230 		int chid_ofs;
1231 
1232 		if (event_flags[f] == 0)
1233 			continue;
1234 
1235 		flags = atomic_swap_long(&event_flags[f], 0);
1236 		chid_base = f << VMBUS_EVTFLAG_SHIFT;
1237 
1238 		while ((chid_ofs = ffsl(flags)) != 0) {
1239 			struct vmbus_channel *chan;
1240 
1241 			--chid_ofs; /* NOTE: ffsl is 1-based */
1242 			flags &= ~(1UL << chid_ofs);
1243 
1244 			chan = sc->vmbus_chmap[chid_base + chid_ofs];
1245 			if (__predict_false(chan == NULL)) {
1246 				/* Channel is closed. */
1247 				continue;
1248 			}
1249 			__compiler_membar();
1250 
1251 			if (chan->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD)
1252 				vmbus_rxbr_intr_mask(&chan->ch_rxbr);
1253 			taskqueue_enqueue(chan->ch_tq, &chan->ch_task);
1254 		}
1255 	}
1256 }
1257 
1258 void
1259 vmbus_event_proc(struct vmbus_softc *sc, int cpu)
1260 {
1261 	struct vmbus_evtflags *eventf;
1262 
1263 	/*
1264 	 * On Host with Win8 or above, the event page can be checked directly
1265 	 * to get the id of the channel that has the pending interrupt.
1266 	 */
1267 	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
1268 	vmbus_event_flags_proc(sc, eventf->evt_flags,
1269 	    VMBUS_PCPU_GET(sc, event_flags_cnt, cpu));
1270 }
1271 
1272 void
1273 vmbus_event_proc_compat(struct vmbus_softc *sc, int cpu)
1274 {
1275 	struct vmbus_evtflags *eventf;
1276 
1277 	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
1278 	if (atomic_testandclear_long(&eventf->evt_flags[0], 0)) {
1279 		vmbus_event_flags_proc(sc, sc->vmbus_rx_evtflags,
1280 		    VMBUS_CHAN_MAX_COMPAT >> VMBUS_EVTFLAG_SHIFT);
1281 	}
1282 }
1283 
1284 static void
1285 vmbus_chan_update_evtflagcnt(struct vmbus_softc *sc,
1286     const struct vmbus_channel *chan)
1287 {
1288 	volatile int *flag_cnt_ptr;
1289 	int flag_cnt;
1290 
1291 	flag_cnt = (chan->ch_id / VMBUS_EVTFLAG_LEN) + 1;
1292 	flag_cnt_ptr = VMBUS_PCPU_PTR(sc, event_flags_cnt, chan->ch_cpuid);
1293 
1294 	for (;;) {
1295 		int old_flag_cnt;
1296 
1297 		old_flag_cnt = *flag_cnt_ptr;
1298 		if (old_flag_cnt >= flag_cnt)
1299 			break;
1300 		if (atomic_cmpset_int(flag_cnt_ptr, old_flag_cnt, flag_cnt)) {
1301 			if (bootverbose) {
1302 				vmbus_chan_printf(chan,
1303 				    "chan%u update cpu%d flag_cnt to %d\n",
1304 				    chan->ch_id, chan->ch_cpuid, flag_cnt);
1305 			}
1306 			break;
1307 		}
1308 	}
1309 }
1310 
1311 static struct vmbus_channel *
1312 vmbus_chan_alloc(struct vmbus_softc *sc)
1313 {
1314 	struct vmbus_channel *chan;
1315 
1316 	chan = malloc(sizeof(*chan), M_DEVBUF, M_WAITOK | M_ZERO);
1317 
1318 	chan->ch_monprm = hyperv_dmamem_alloc(bus_get_dma_tag(sc->vmbus_dev),
1319 	    HYPERCALL_PARAM_ALIGN, 0, sizeof(struct hyperv_mon_param),
1320 	    &chan->ch_monprm_dma, BUS_DMA_WAITOK | BUS_DMA_ZERO);
1321 	if (chan->ch_monprm == NULL) {
1322 		device_printf(sc->vmbus_dev, "monprm alloc failed\n");
1323 		free(chan, M_DEVBUF);
1324 		return NULL;
1325 	}
1326 
1327 	chan->ch_refs = 1;
1328 	chan->ch_vmbus = sc;
1329 	mtx_init(&chan->ch_subchan_lock, "vmbus subchan", NULL, MTX_DEF);
1330 	sx_init(&chan->ch_orphan_lock, "vmbus chorphan");
1331 	TAILQ_INIT(&chan->ch_subchans);
1332 	vmbus_rxbr_init(&chan->ch_rxbr);
1333 	vmbus_txbr_init(&chan->ch_txbr);
1334 
1335 	return chan;
1336 }
1337 
1338 static void
1339 vmbus_chan_free(struct vmbus_channel *chan)
1340 {
1341 
1342 	KASSERT(TAILQ_EMPTY(&chan->ch_subchans) && chan->ch_subchan_cnt == 0,
1343 	    ("still owns sub-channels"));
1344 	KASSERT((chan->ch_stflags &
1345 	    (VMBUS_CHAN_ST_OPENED |
1346 	     VMBUS_CHAN_ST_ONPRIL |
1347 	     VMBUS_CHAN_ST_ONSUBL |
1348 	     VMBUS_CHAN_ST_ONLIST)) == 0, ("free busy channel"));
1349 	KASSERT(chan->ch_orphan_xact == NULL,
1350 	    ("still has orphan xact installed"));
1351 	KASSERT(chan->ch_refs == 0, ("chan%u: invalid refcnt %d",
1352 	    chan->ch_id, chan->ch_refs));
1353 
1354 	hyperv_dmamem_free(&chan->ch_monprm_dma, chan->ch_monprm);
1355 	mtx_destroy(&chan->ch_subchan_lock);
1356 	sx_destroy(&chan->ch_orphan_lock);
1357 	vmbus_rxbr_deinit(&chan->ch_rxbr);
1358 	vmbus_txbr_deinit(&chan->ch_txbr);
1359 	free(chan, M_DEVBUF);
1360 }
1361 
1362 static int
1363 vmbus_chan_add(struct vmbus_channel *newchan)
1364 {
1365 	struct vmbus_softc *sc = newchan->ch_vmbus;
1366 	struct vmbus_channel *prichan;
1367 
1368 	if (newchan->ch_id == 0) {
1369 		/*
1370 		 * XXX
1371 		 * Chan0 will neither be processed nor should be offered;
1372 		 * skip it.
1373 		 */
1374 		device_printf(sc->vmbus_dev, "got chan0 offer, discard\n");
1375 		return EINVAL;
1376 	} else if (newchan->ch_id >= VMBUS_CHAN_MAX) {
1377 		device_printf(sc->vmbus_dev, "invalid chan%u offer\n",
1378 		    newchan->ch_id);
1379 		return EINVAL;
1380 	}
1381 
1382 	mtx_lock(&sc->vmbus_prichan_lock);
1383 	TAILQ_FOREACH(prichan, &sc->vmbus_prichans, ch_prilink) {
1384 		/*
1385 		 * Sub-channel will have the same type GUID and instance
1386 		 * GUID as its primary channel.
1387 		 */
1388 		if (memcmp(&prichan->ch_guid_type, &newchan->ch_guid_type,
1389 		    sizeof(struct hyperv_guid)) == 0 &&
1390 		    memcmp(&prichan->ch_guid_inst, &newchan->ch_guid_inst,
1391 		    sizeof(struct hyperv_guid)) == 0)
1392 			break;
1393 	}
1394 	if (VMBUS_CHAN_ISPRIMARY(newchan)) {
1395 		if (prichan == NULL) {
1396 			/* Install the new primary channel */
1397 			vmbus_chan_ins_prilist(sc, newchan);
1398 			mtx_unlock(&sc->vmbus_prichan_lock);
1399 			goto done;
1400 		} else {
1401 			mtx_unlock(&sc->vmbus_prichan_lock);
1402 			device_printf(sc->vmbus_dev,
1403 			    "duplicated primary chan%u\n", newchan->ch_id);
1404 			return EINVAL;
1405 		}
1406 	} else { /* Sub-channel */
1407 		if (prichan == NULL) {
1408 			mtx_unlock(&sc->vmbus_prichan_lock);
1409 			device_printf(sc->vmbus_dev,
1410 			    "no primary chan for chan%u\n", newchan->ch_id);
1411 			return EINVAL;
1412 		}
1413 		/*
1414 		 * Found the primary channel for this sub-channel and
1415 		 * move on.
1416 		 *
1417 		 * XXX refcnt prichan
1418 		 */
1419 	}
1420 	mtx_unlock(&sc->vmbus_prichan_lock);
1421 
1422 	/*
1423 	 * This is a sub-channel; link it with the primary channel.
1424 	 */
1425 	KASSERT(!VMBUS_CHAN_ISPRIMARY(newchan),
1426 	    ("new channel is not sub-channel"));
1427 	KASSERT(prichan != NULL, ("no primary channel"));
1428 
1429 	/*
1430 	 * Reference count this sub-channel; it will be dereferenced
1431 	 * when this sub-channel is closed.
1432 	 */
1433 	KASSERT(newchan->ch_refs == 1, ("chan%u: invalid refcnt %d",
1434 	    newchan->ch_id, newchan->ch_refs));
1435 	atomic_add_int(&newchan->ch_refs, 1);
1436 
1437 	newchan->ch_prichan = prichan;
1438 	newchan->ch_dev = prichan->ch_dev;
1439 
1440 	mtx_lock(&prichan->ch_subchan_lock);
1441 	vmbus_chan_ins_sublist(prichan, newchan);
1442 	mtx_unlock(&prichan->ch_subchan_lock);
1443 	/*
1444 	 * Notify anyone that is interested in this sub-channel,
1445 	 * after this sub-channel is setup.
1446 	 */
1447 	wakeup(prichan);
1448 done:
1449 	/*
1450 	 * Hook this channel up for later revocation.
1451 	 */
1452 	mtx_lock(&sc->vmbus_chan_lock);
1453 	vmbus_chan_ins_list(sc, newchan);
1454 	mtx_unlock(&sc->vmbus_chan_lock);
1455 
1456 	if (bootverbose) {
1457 		vmbus_chan_printf(newchan, "chan%u subidx%u offer\n",
1458 		    newchan->ch_id, newchan->ch_subidx);
1459 	}
1460 
1461 	/* Select default cpu for this channel. */
1462 	vmbus_chan_cpu_default(newchan);
1463 
1464 	return 0;
1465 }
1466 
1467 void
1468 vmbus_chan_cpu_set(struct vmbus_channel *chan, int cpu)
1469 {
1470 	KASSERT(cpu >= 0 && cpu < mp_ncpus, ("invalid cpu %d", cpu));
1471 
1472 	if (chan->ch_vmbus->vmbus_version == VMBUS_VERSION_WS2008 ||
1473 	    chan->ch_vmbus->vmbus_version == VMBUS_VERSION_WIN7) {
1474 		/* Only cpu0 is supported */
1475 		cpu = 0;
1476 	}
1477 
1478 	chan->ch_cpuid = cpu;
1479 	chan->ch_vcpuid = VMBUS_PCPU_GET(chan->ch_vmbus, vcpuid, cpu);
1480 
1481 	if (bootverbose) {
1482 		vmbus_chan_printf(chan,
1483 		    "chan%u assigned to cpu%u [vcpu%u]\n",
1484 		    chan->ch_id, chan->ch_cpuid, chan->ch_vcpuid);
1485 	}
1486 }
1487 
1488 void
1489 vmbus_chan_cpu_rr(struct vmbus_channel *chan)
1490 {
1491 	static uint32_t vmbus_chan_nextcpu;
1492 	int cpu;
1493 
1494 	cpu = atomic_fetchadd_int(&vmbus_chan_nextcpu, 1) % mp_ncpus;
1495 	vmbus_chan_cpu_set(chan, cpu);
1496 }
1497 
1498 static void
1499 vmbus_chan_cpu_default(struct vmbus_channel *chan)
1500 {
1501 	/*
1502 	 * By default, pin the channel to cpu0.  Devices having
1503 	 * special channel-cpu mapping requirement should call
1504 	 * vmbus_chan_cpu_{set,rr}().
1505 	 */
1506 	vmbus_chan_cpu_set(chan, 0);
1507 }
1508 
1509 static void
1510 vmbus_chan_msgproc_choffer(struct vmbus_softc *sc,
1511     const struct vmbus_message *msg)
1512 {
1513 	const struct vmbus_chanmsg_choffer *offer;
1514 	struct vmbus_channel *chan;
1515 	task_fn_t *detach_fn, *attach_fn;
1516 	int error;
1517 
1518 	offer = (const struct vmbus_chanmsg_choffer *)msg->msg_data;
1519 
1520 	chan = vmbus_chan_alloc(sc);
1521 	if (chan == NULL) {
1522 		device_printf(sc->vmbus_dev, "allocate chan%u failed\n",
1523 		    offer->chm_chanid);
1524 		return;
1525 	}
1526 
1527 	chan->ch_id = offer->chm_chanid;
1528 	chan->ch_subidx = offer->chm_subidx;
1529 	chan->ch_guid_type = offer->chm_chtype;
1530 	chan->ch_guid_inst = offer->chm_chinst;
1531 
1532 	/* Batch reading is on by default */
1533 	chan->ch_flags |= VMBUS_CHAN_FLAG_BATCHREAD;
1534 
1535 	chan->ch_monprm->mp_connid = VMBUS_CONNID_EVENT;
1536 	if (sc->vmbus_version != VMBUS_VERSION_WS2008)
1537 		chan->ch_monprm->mp_connid = offer->chm_connid;
1538 
1539 	if (offer->chm_flags1 & VMBUS_CHOFFER_FLAG1_HASMNF) {
1540 		int trig_idx;
1541 
1542 		/*
1543 		 * Setup MNF stuffs.
1544 		 */
1545 		chan->ch_txflags |= VMBUS_CHAN_TXF_HASMNF;
1546 
1547 		trig_idx = offer->chm_montrig / VMBUS_MONTRIG_LEN;
1548 		if (trig_idx >= VMBUS_MONTRIGS_MAX)
1549 			panic("invalid monitor trigger %u", offer->chm_montrig);
1550 		chan->ch_montrig =
1551 		    &sc->vmbus_mnf2->mnf_trigs[trig_idx].mt_pending;
1552 
1553 		chan->ch_montrig_mask =
1554 		    1 << (offer->chm_montrig % VMBUS_MONTRIG_LEN);
1555 	}
1556 
1557 	/*
1558 	 * Setup event flag.
1559 	 */
1560 	chan->ch_evtflag =
1561 	    &sc->vmbus_tx_evtflags[chan->ch_id >> VMBUS_EVTFLAG_SHIFT];
1562 	chan->ch_evtflag_mask = 1UL << (chan->ch_id & VMBUS_EVTFLAG_MASK);
1563 
1564 	/*
1565 	 * Setup attach and detach tasks.
1566 	 */
1567 	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1568 		chan->ch_mgmt_tq = sc->vmbus_devtq;
1569 		attach_fn = vmbus_prichan_attach_task;
1570 		detach_fn = vmbus_prichan_detach_task;
1571 	} else {
1572 		chan->ch_mgmt_tq = sc->vmbus_subchtq;
1573 		attach_fn = vmbus_subchan_attach_task;
1574 		detach_fn = vmbus_subchan_detach_task;
1575 	}
1576 	TASK_INIT(&chan->ch_attach_task, 0, attach_fn, chan);
1577 	TASK_INIT(&chan->ch_detach_task, 0, detach_fn, chan);
1578 
1579 	error = vmbus_chan_add(chan);
1580 	if (error) {
1581 		device_printf(sc->vmbus_dev, "add chan%u failed: %d\n",
1582 		    chan->ch_id, error);
1583 		atomic_subtract_int(&chan->ch_refs, 1);
1584 		vmbus_chan_free(chan);
1585 		return;
1586 	}
1587 	taskqueue_enqueue(chan->ch_mgmt_tq, &chan->ch_attach_task);
1588 }
1589 
1590 static void
1591 vmbus_chan_msgproc_chrescind(struct vmbus_softc *sc,
1592     const struct vmbus_message *msg)
1593 {
1594 	const struct vmbus_chanmsg_chrescind *note;
1595 	struct vmbus_channel *chan;
1596 
1597 	note = (const struct vmbus_chanmsg_chrescind *)msg->msg_data;
1598 	if (note->chm_chanid > VMBUS_CHAN_MAX) {
1599 		device_printf(sc->vmbus_dev, "invalid revoked chan%u\n",
1600 		    note->chm_chanid);
1601 		return;
1602 	}
1603 
1604 	/*
1605 	 * Find and remove the target channel from the channel list.
1606 	 */
1607 	mtx_lock(&sc->vmbus_chan_lock);
1608 	TAILQ_FOREACH(chan, &sc->vmbus_chans, ch_link) {
1609 		if (chan->ch_id == note->chm_chanid)
1610 			break;
1611 	}
1612 	if (chan == NULL) {
1613 		mtx_unlock(&sc->vmbus_chan_lock);
1614 		device_printf(sc->vmbus_dev, "chan%u is not offered\n",
1615 		    note->chm_chanid);
1616 		return;
1617 	}
1618 	vmbus_chan_rem_list(sc, chan);
1619 	mtx_unlock(&sc->vmbus_chan_lock);
1620 
1621 	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1622 		/*
1623 		 * The target channel is a primary channel; remove the
1624 		 * target channel from the primary channel list now,
1625 		 * instead of later, so that it will not be found by
1626 		 * other sub-channel offers, which are processed in
1627 		 * this thread.
1628 		 */
1629 		mtx_lock(&sc->vmbus_prichan_lock);
1630 		vmbus_chan_rem_prilist(sc, chan);
1631 		mtx_unlock(&sc->vmbus_prichan_lock);
1632 	}
1633 
1634 	/*
1635 	 * NOTE:
1636 	 * The following processing order is critical:
1637 	 * Set the REVOKED state flag before orphaning the installed xact.
1638 	 */
1639 
1640 	if (atomic_testandset_int(&chan->ch_stflags,
1641 	    VMBUS_CHAN_ST_REVOKED_SHIFT))
1642 		panic("channel has already been revoked");
1643 
1644 	sx_xlock(&chan->ch_orphan_lock);
1645 	if (chan->ch_orphan_xact != NULL)
1646 		vmbus_xact_ctx_orphan(chan->ch_orphan_xact);
1647 	sx_xunlock(&chan->ch_orphan_lock);
1648 
1649 	if (bootverbose)
1650 		vmbus_chan_printf(chan, "chan%u revoked\n", note->chm_chanid);
1651 	vmbus_chan_detach(chan);
1652 }
1653 
1654 static int
1655 vmbus_chan_release(struct vmbus_channel *chan)
1656 {
1657 	struct vmbus_softc *sc = chan->ch_vmbus;
1658 	struct vmbus_chanmsg_chfree *req;
1659 	struct vmbus_msghc *mh;
1660 	int error;
1661 
1662 	mh = vmbus_msghc_get(sc, sizeof(*req));
1663 	if (mh == NULL) {
1664 		vmbus_chan_printf(chan,
1665 		    "can not get msg hypercall for chfree(chan%u)\n",
1666 		    chan->ch_id);
1667 		return (ENXIO);
1668 	}
1669 
1670 	req = vmbus_msghc_dataptr(mh);
1671 	req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHFREE;
1672 	req->chm_chanid = chan->ch_id;
1673 
1674 	error = vmbus_msghc_exec_noresult(mh);
1675 	vmbus_msghc_put(sc, mh);
1676 
1677 	if (error) {
1678 		vmbus_chan_printf(chan,
1679 		    "chfree(chan%u) msg hypercall exec failed: %d\n",
1680 		    chan->ch_id, error);
1681 	} else {
1682 		if (bootverbose)
1683 			vmbus_chan_printf(chan, "chan%u freed\n", chan->ch_id);
1684 	}
1685 	return (error);
1686 }
1687 
1688 static void
1689 vmbus_prichan_detach_task(void *xchan, int pending __unused)
1690 {
1691 	struct vmbus_channel *chan = xchan;
1692 
1693 	KASSERT(VMBUS_CHAN_ISPRIMARY(chan),
1694 	    ("chan%u is not primary channel", chan->ch_id));
1695 
1696 	/* Delete and detach the device associated with this channel. */
1697 	vmbus_delete_child(chan);
1698 
1699 	/* Release this channel (back to vmbus). */
1700 	vmbus_chan_release(chan);
1701 
1702 	/* Free this channel's resource. */
1703 	vmbus_chan_free(chan);
1704 }
1705 
1706 static void
1707 vmbus_subchan_detach_task(void *xchan, int pending __unused)
1708 {
1709 	struct vmbus_channel *chan = xchan;
1710 	struct vmbus_channel *pri_chan = chan->ch_prichan;
1711 
1712 	KASSERT(!VMBUS_CHAN_ISPRIMARY(chan),
1713 	    ("chan%u is primary channel", chan->ch_id));
1714 
1715 	/* Release this channel (back to vmbus). */
1716 	vmbus_chan_release(chan);
1717 
1718 	/* Unlink from its primary channel's sub-channel list. */
1719 	mtx_lock(&pri_chan->ch_subchan_lock);
1720 	vmbus_chan_rem_sublist(pri_chan, chan);
1721 	mtx_unlock(&pri_chan->ch_subchan_lock);
1722 	/* Notify anyone that is waiting for this sub-channel to vanish. */
1723 	wakeup(pri_chan);
1724 
1725 	/* Free this channel's resource. */
1726 	vmbus_chan_free(chan);
1727 }
1728 
1729 static void
1730 vmbus_prichan_attach_task(void *xchan, int pending __unused)
1731 {
1732 
1733 	/*
1734 	 * Add device for this primary channel.
1735 	 */
1736 	vmbus_add_child(xchan);
1737 }
1738 
1739 static void
1740 vmbus_subchan_attach_task(void *xchan __unused, int pending __unused)
1741 {
1742 
1743 	/* Nothing */
1744 }
1745 
1746 void
1747 vmbus_chan_destroy_all(struct vmbus_softc *sc)
1748 {
1749 
1750 	/*
1751 	 * Detach all devices and destroy the corresponding primary
1752 	 * channels.
1753 	 */
1754 	for (;;) {
1755 		struct vmbus_channel *chan;
1756 
1757 		mtx_lock(&sc->vmbus_chan_lock);
1758 		TAILQ_FOREACH(chan, &sc->vmbus_chans, ch_link) {
1759 			if (VMBUS_CHAN_ISPRIMARY(chan))
1760 				break;
1761 		}
1762 		if (chan == NULL) {
1763 			/* No more primary channels; done. */
1764 			mtx_unlock(&sc->vmbus_chan_lock);
1765 			break;
1766 		}
1767 		vmbus_chan_rem_list(sc, chan);
1768 		mtx_unlock(&sc->vmbus_chan_lock);
1769 
1770 		mtx_lock(&sc->vmbus_prichan_lock);
1771 		vmbus_chan_rem_prilist(sc, chan);
1772 		mtx_unlock(&sc->vmbus_prichan_lock);
1773 
1774 		taskqueue_enqueue(chan->ch_mgmt_tq, &chan->ch_detach_task);
1775 	}
1776 }
1777 
1778 struct vmbus_channel **
1779 vmbus_subchan_get(struct vmbus_channel *pri_chan, int subchan_cnt)
1780 {
1781 	struct vmbus_channel **ret, *chan;
1782 	int i;
1783 
1784 	KASSERT(subchan_cnt > 0, ("invalid sub-channel count %d", subchan_cnt));
1785 
1786 	ret = malloc(subchan_cnt * sizeof(struct vmbus_channel *), M_TEMP,
1787 	    M_WAITOK);
1788 
1789 	mtx_lock(&pri_chan->ch_subchan_lock);
1790 
1791 	while (pri_chan->ch_subchan_cnt < subchan_cnt)
1792 		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "subch", 0);
1793 
1794 	i = 0;
1795 	TAILQ_FOREACH(chan, &pri_chan->ch_subchans, ch_sublink) {
1796 		/* TODO: refcnt chan */
1797 		ret[i] = chan;
1798 
1799 		++i;
1800 		if (i == subchan_cnt)
1801 			break;
1802 	}
1803 	KASSERT(i == subchan_cnt, ("invalid subchan count %d, should be %d",
1804 	    pri_chan->ch_subchan_cnt, subchan_cnt));
1805 
1806 	mtx_unlock(&pri_chan->ch_subchan_lock);
1807 
1808 	return ret;
1809 }
1810 
1811 void
1812 vmbus_subchan_rel(struct vmbus_channel **subchan, int subchan_cnt __unused)
1813 {
1814 
1815 	free(subchan, M_TEMP);
1816 }
1817 
1818 void
1819 vmbus_subchan_drain(struct vmbus_channel *pri_chan)
1820 {
1821 	mtx_lock(&pri_chan->ch_subchan_lock);
1822 	while (pri_chan->ch_subchan_cnt > 0)
1823 		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "dsubch", 0);
1824 	mtx_unlock(&pri_chan->ch_subchan_lock);
1825 }
1826 
1827 void
1828 vmbus_chan_msgproc(struct vmbus_softc *sc, const struct vmbus_message *msg)
1829 {
1830 	vmbus_chanmsg_proc_t msg_proc;
1831 	uint32_t msg_type;
1832 
1833 	msg_type = ((const struct vmbus_chanmsg_hdr *)msg->msg_data)->chm_type;
1834 	KASSERT(msg_type < VMBUS_CHANMSG_TYPE_MAX,
1835 	    ("invalid message type %u", msg_type));
1836 
1837 	msg_proc = vmbus_chan_msgprocs[msg_type];
1838 	if (msg_proc != NULL)
1839 		msg_proc(sc, msg);
1840 }
1841 
1842 void
1843 vmbus_chan_set_readbatch(struct vmbus_channel *chan, bool on)
1844 {
1845 	if (!on)
1846 		chan->ch_flags &= ~VMBUS_CHAN_FLAG_BATCHREAD;
1847 	else
1848 		chan->ch_flags |= VMBUS_CHAN_FLAG_BATCHREAD;
1849 }
1850 
1851 uint32_t
1852 vmbus_chan_id(const struct vmbus_channel *chan)
1853 {
1854 	return chan->ch_id;
1855 }
1856 
1857 uint32_t
1858 vmbus_chan_subidx(const struct vmbus_channel *chan)
1859 {
1860 	return chan->ch_subidx;
1861 }
1862 
1863 bool
1864 vmbus_chan_is_primary(const struct vmbus_channel *chan)
1865 {
1866 	if (VMBUS_CHAN_ISPRIMARY(chan))
1867 		return true;
1868 	else
1869 		return false;
1870 }
1871 
1872 const struct hyperv_guid *
1873 vmbus_chan_guid_inst(const struct vmbus_channel *chan)
1874 {
1875 	return &chan->ch_guid_inst;
1876 }
1877 
1878 int
1879 vmbus_chan_prplist_nelem(int br_size, int prpcnt_max, int dlen_max)
1880 {
1881 	int elem_size;
1882 
1883 	elem_size = __offsetof(struct vmbus_chanpkt_prplist,
1884 	    cp_range[0].gpa_page[prpcnt_max]);
1885 	elem_size += dlen_max;
1886 	elem_size = VMBUS_CHANPKT_TOTLEN(elem_size);
1887 
1888 	return (vmbus_br_nelem(br_size, elem_size));
1889 }
1890 
1891 bool
1892 vmbus_chan_tx_empty(const struct vmbus_channel *chan)
1893 {
1894 
1895 	return (vmbus_txbr_empty(&chan->ch_txbr));
1896 }
1897 
1898 bool
1899 vmbus_chan_rx_empty(const struct vmbus_channel *chan)
1900 {
1901 
1902 	return (vmbus_rxbr_empty(&chan->ch_rxbr));
1903 }
1904 
1905 static int
1906 vmbus_chan_printf(const struct vmbus_channel *chan, const char *fmt, ...)
1907 {
1908 	va_list ap;
1909 	device_t dev;
1910 	int retval;
1911 
1912 	if (chan->ch_dev == NULL || !device_is_alive(chan->ch_dev))
1913 		dev = chan->ch_vmbus->vmbus_dev;
1914 	else
1915 		dev = chan->ch_dev;
1916 
1917 	retval = device_print_prettyname(dev);
1918 	va_start(ap, fmt);
1919 	retval += vprintf(fmt, ap);
1920 	va_end(ap);
1921 
1922 	return (retval);
1923 }
1924 
1925 void
1926 vmbus_chan_run_task(struct vmbus_channel *chan, struct task *task)
1927 {
1928 
1929 	taskqueue_enqueue(chan->ch_tq, task);
1930 	taskqueue_drain(chan->ch_tq, task);
1931 }
1932 
1933 struct taskqueue *
1934 vmbus_chan_mgmt_tq(const struct vmbus_channel *chan)
1935 {
1936 
1937 	return (chan->ch_mgmt_tq);
1938 }
1939 
1940 bool
1941 vmbus_chan_is_revoked(const struct vmbus_channel *chan)
1942 {
1943 
1944 	if (chan->ch_stflags & VMBUS_CHAN_ST_REVOKED)
1945 		return (true);
1946 	return (false);
1947 }
1948 
1949 void
1950 vmbus_chan_set_orphan(struct vmbus_channel *chan, struct vmbus_xact_ctx *xact)
1951 {
1952 
1953 	sx_xlock(&chan->ch_orphan_lock);
1954 	chan->ch_orphan_xact = xact;
1955 	sx_xunlock(&chan->ch_orphan_lock);
1956 }
1957 
1958 void
1959 vmbus_chan_unset_orphan(struct vmbus_channel *chan)
1960 {
1961 
1962 	sx_xlock(&chan->ch_orphan_lock);
1963 	chan->ch_orphan_xact = NULL;
1964 	sx_xunlock(&chan->ch_orphan_lock);
1965 }
1966 
1967 const void *
1968 vmbus_chan_xact_wait(const struct vmbus_channel *chan,
1969     struct vmbus_xact *xact, size_t *resp_len, bool can_sleep)
1970 {
1971 	const void *ret;
1972 
1973 	if (can_sleep)
1974 		ret = vmbus_xact_wait(xact, resp_len);
1975 	else
1976 		ret = vmbus_xact_busywait(xact, resp_len);
1977 	if (vmbus_chan_is_revoked(chan)) {
1978 		/*
1979 		 * This xact probably is interrupted, and the
1980 		 * interruption can race the reply reception,
1981 		 * so we have to make sure that there are nothing
1982 		 * left on the RX bufring, i.e. this xact will
1983 		 * not be touched, once this function returns.
1984 		 *
1985 		 * Since the hypervisor will not put more data
1986 		 * onto the RX bufring once the channel is revoked,
1987 		 * the following loop will be terminated, once all
1988 		 * data are drained by the driver's channel
1989 		 * callback.
1990 		 */
1991 		while (!vmbus_chan_rx_empty(chan)) {
1992 			if (can_sleep)
1993 				pause("chxact", 1);
1994 			else
1995 				DELAY(1000);
1996 		}
1997 	}
1998 	return (ret);
1999 }
2000