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