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