vmbus_chan.c revision 307461
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: stable/11/sys/dev/hyperv/vmbus/vmbus_chan.c 307461 2016-10-17 03:24:03Z sephe $");
31
32#include <sys/param.h>
33#include <sys/kernel.h>
34#include <sys/malloc.h>
35#include <sys/systm.h>
36#include <sys/mbuf.h>
37#include <sys/lock.h>
38#include <sys/mutex.h>
39#include <sys/sysctl.h>
40
41#include <machine/atomic.h>
42#include <machine/bus.h>
43
44#include <vm/vm.h>
45#include <vm/vm_param.h>
46#include <vm/pmap.h>
47
48#include <dev/hyperv/include/hyperv_busdma.h>
49#include <dev/hyperv/vmbus/hv_vmbus_priv.h>
50#include <dev/hyperv/vmbus/hyperv_var.h>
51#include <dev/hyperv/vmbus/vmbus_reg.h>
52#include <dev/hyperv/vmbus/vmbus_var.h>
53
54static void	vmbus_chan_update_evtflagcnt(struct vmbus_softc *,
55		    const struct vmbus_channel *);
56
57static void	vmbus_chan_task(void *, int);
58static void	vmbus_chan_task_nobatch(void *, int);
59static void	vmbus_chan_detach_task(void *, int);
60
61static void	vmbus_chan_msgproc_choffer(struct vmbus_softc *,
62		    const struct vmbus_message *);
63static void	vmbus_chan_msgproc_chrescind(struct vmbus_softc *,
64		    const struct vmbus_message *);
65
66/*
67 * Vmbus channel message processing.
68 */
69static const vmbus_chanmsg_proc_t
70vmbus_chan_msgprocs[VMBUS_CHANMSG_TYPE_MAX] = {
71	VMBUS_CHANMSG_PROC(CHOFFER,	vmbus_chan_msgproc_choffer),
72	VMBUS_CHANMSG_PROC(CHRESCIND,	vmbus_chan_msgproc_chrescind),
73
74	VMBUS_CHANMSG_PROC_WAKEUP(CHOPEN_RESP),
75	VMBUS_CHANMSG_PROC_WAKEUP(GPADL_CONNRESP),
76	VMBUS_CHANMSG_PROC_WAKEUP(GPADL_DISCONNRESP)
77};
78
79/*
80 * Notify host that there are data pending on our TX bufring.
81 */
82static __inline void
83vmbus_chan_signal_tx(const struct vmbus_channel *chan)
84{
85	atomic_set_long(chan->ch_evtflag, chan->ch_evtflag_mask);
86	if (chan->ch_txflags & VMBUS_CHAN_TXF_HASMNF)
87		atomic_set_int(chan->ch_montrig, chan->ch_montrig_mask);
88	else
89		hypercall_signal_event(chan->ch_monprm_dma.hv_paddr);
90}
91
92static int
93vmbus_chan_sysctl_mnf(SYSCTL_HANDLER_ARGS)
94{
95	struct vmbus_channel *chan = arg1;
96	int mnf = 0;
97
98	if (chan->ch_txflags & VMBUS_CHAN_TXF_HASMNF)
99		mnf = 1;
100	return sysctl_handle_int(oidp, &mnf, 0, req);
101}
102
103static void
104vmbus_chan_sysctl_create(struct vmbus_channel *chan)
105{
106	struct sysctl_oid *ch_tree, *chid_tree, *br_tree;
107	struct sysctl_ctx_list *ctx;
108	uint32_t ch_id;
109	char name[16];
110
111	/*
112	 * Add sysctl nodes related to this channel to this
113	 * channel's sysctl ctx, so that they can be destroyed
114	 * independently upon close of this channel, which can
115	 * happen even if the device is not detached.
116	 */
117	ctx = &chan->ch_sysctl_ctx;
118	sysctl_ctx_init(ctx);
119
120	/*
121	 * Create dev.NAME.UNIT.channel tree.
122	 */
123	ch_tree = SYSCTL_ADD_NODE(ctx,
124	    SYSCTL_CHILDREN(device_get_sysctl_tree(chan->ch_dev)),
125	    OID_AUTO, "channel", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
126	if (ch_tree == NULL)
127		return;
128
129	/*
130	 * Create dev.NAME.UNIT.channel.CHANID tree.
131	 */
132	if (VMBUS_CHAN_ISPRIMARY(chan))
133		ch_id = chan->ch_id;
134	else
135		ch_id = chan->ch_prichan->ch_id;
136	snprintf(name, sizeof(name), "%d", ch_id);
137	chid_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(ch_tree),
138	    OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
139	if (chid_tree == NULL)
140		return;
141
142	if (!VMBUS_CHAN_ISPRIMARY(chan)) {
143		/*
144		 * Create dev.NAME.UNIT.channel.CHANID.sub tree.
145		 */
146		ch_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(chid_tree),
147		    OID_AUTO, "sub", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
148		if (ch_tree == NULL)
149			return;
150
151		/*
152		 * Create dev.NAME.UNIT.channel.CHANID.sub.SUBIDX tree.
153		 *
154		 * NOTE:
155		 * chid_tree is changed to this new sysctl tree.
156		 */
157		snprintf(name, sizeof(name), "%d", chan->ch_subidx);
158		chid_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(ch_tree),
159		    OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
160		if (chid_tree == NULL)
161			return;
162
163		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
164		    "chanid", CTLFLAG_RD, &chan->ch_id, 0, "channel id");
165	}
166
167	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
168	    "cpu", CTLFLAG_RD, &chan->ch_cpuid, 0, "owner CPU id");
169	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
170	    "mnf", CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
171	    chan, 0, vmbus_chan_sysctl_mnf, "I",
172	    "has monitor notification facilities");
173
174	/*
175	 * Create sysctl tree for RX bufring.
176	 */
177	br_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
178	    "in", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
179	if (br_tree != NULL) {
180		hv_ring_buffer_stat(ctx, SYSCTL_CHILDREN(br_tree),
181		    &chan->ch_rxbr, "inbound ring buffer stats");
182	}
183
184	/*
185	 * Create sysctl tree for TX bufring.
186	 */
187	br_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(chid_tree), OID_AUTO,
188	    "out", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
189	if (br_tree != NULL) {
190		hv_ring_buffer_stat(ctx, SYSCTL_CHILDREN(br_tree),
191		    &chan->ch_txbr, "outbound ring buffer stats");
192	}
193}
194
195int
196vmbus_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	hv_vmbus_ring_buffer_init(&chan->ch_txbr, br, txbr_size);
249	/* RX bufring immediately follows TX bufring */
250	hv_vmbus_ring_buffer_init(&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
314failed:
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
327int
328vmbus_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 */
457int
458vmbus_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
494static void
495vmbus_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	hv_ring_buffer_cleanup(&chan->ch_txbr);
559	hv_ring_buffer_cleanup(&chan->ch_rxbr);
560	if (chan->ch_bufring != NULL) {
561		hyperv_dmamem_free(&chan->ch_bufring_dma, chan->ch_bufring);
562		chan->ch_bufring = NULL;
563	}
564}
565
566/*
567 * Caller should make sure that all sub-channels have
568 * been added to 'chan' and all to-be-closed channels
569 * are not being opened.
570 */
571void
572vmbus_chan_close(struct vmbus_channel *chan)
573{
574	int subchan_cnt;
575
576	if (!VMBUS_CHAN_ISPRIMARY(chan)) {
577		/*
578		 * Sub-channel is closed when its primary channel
579		 * is closed; done.
580		 */
581		return;
582	}
583
584	/*
585	 * Close all sub-channels, if any.
586	 */
587	subchan_cnt = chan->ch_subchan_cnt;
588	if (subchan_cnt > 0) {
589		struct vmbus_channel **subchan;
590		int i;
591
592		subchan = vmbus_subchan_get(chan, subchan_cnt);
593		for (i = 0; i < subchan_cnt; ++i)
594			vmbus_chan_close_internal(subchan[i]);
595		vmbus_subchan_rel(subchan, subchan_cnt);
596	}
597
598	/* Then close the primary channel. */
599	vmbus_chan_close_internal(chan);
600}
601
602int
603vmbus_chan_send(struct vmbus_channel *chan, uint16_t type, uint16_t flags,
604    void *data, int dlen, uint64_t xactid)
605{
606	struct vmbus_chanpkt pkt;
607	int pktlen, pad_pktlen, hlen, error;
608	uint64_t pad = 0;
609	struct iovec iov[3];
610	boolean_t send_evt;
611
612	hlen = sizeof(pkt);
613	pktlen = hlen + dlen;
614	pad_pktlen = VMBUS_CHANPKT_TOTLEN(pktlen);
615
616	pkt.cp_hdr.cph_type = type;
617	pkt.cp_hdr.cph_flags = flags;
618	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_hlen, hlen);
619	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_tlen, pad_pktlen);
620	pkt.cp_hdr.cph_xactid = xactid;
621
622	iov[0].iov_base = &pkt;
623	iov[0].iov_len = hlen;
624	iov[1].iov_base = data;
625	iov[1].iov_len = dlen;
626	iov[2].iov_base = &pad;
627	iov[2].iov_len = pad_pktlen - pktlen;
628
629	error = hv_ring_buffer_write(&chan->ch_txbr, iov, 3, &send_evt);
630	if (!error && send_evt)
631		vmbus_chan_signal_tx(chan);
632	return error;
633}
634
635int
636vmbus_chan_send_sglist(struct vmbus_channel *chan,
637    struct vmbus_gpa sg[], int sglen, void *data, int dlen, uint64_t xactid)
638{
639	struct vmbus_chanpkt_sglist pkt;
640	int pktlen, pad_pktlen, hlen, error;
641	struct iovec iov[4];
642	boolean_t send_evt;
643	uint64_t pad = 0;
644
645	KASSERT(sglen < VMBUS_CHAN_SGLIST_MAX,
646	    ("invalid sglist len %d", sglen));
647
648	hlen = __offsetof(struct vmbus_chanpkt_sglist, cp_gpa[sglen]);
649	pktlen = hlen + dlen;
650	pad_pktlen = VMBUS_CHANPKT_TOTLEN(pktlen);
651
652	pkt.cp_hdr.cph_type = VMBUS_CHANPKT_TYPE_GPA;
653	pkt.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
654	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_hlen, hlen);
655	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_tlen, pad_pktlen);
656	pkt.cp_hdr.cph_xactid = xactid;
657	pkt.cp_rsvd = 0;
658	pkt.cp_gpa_cnt = sglen;
659
660	iov[0].iov_base = &pkt;
661	iov[0].iov_len = sizeof(pkt);
662	iov[1].iov_base = sg;
663	iov[1].iov_len = sizeof(struct vmbus_gpa) * sglen;
664	iov[2].iov_base = data;
665	iov[2].iov_len = dlen;
666	iov[3].iov_base = &pad;
667	iov[3].iov_len = pad_pktlen - pktlen;
668
669	error = hv_ring_buffer_write(&chan->ch_txbr, iov, 4, &send_evt);
670	if (!error && send_evt)
671		vmbus_chan_signal_tx(chan);
672	return error;
673}
674
675int
676vmbus_chan_send_prplist(struct vmbus_channel *chan,
677    struct vmbus_gpa_range *prp, int prp_cnt, void *data, int dlen,
678    uint64_t xactid)
679{
680	struct vmbus_chanpkt_prplist pkt;
681	int pktlen, pad_pktlen, hlen, error;
682	struct iovec iov[4];
683	boolean_t send_evt;
684	uint64_t pad = 0;
685
686	KASSERT(prp_cnt < VMBUS_CHAN_PRPLIST_MAX,
687	    ("invalid prplist entry count %d", prp_cnt));
688
689	hlen = __offsetof(struct vmbus_chanpkt_prplist,
690	    cp_range[0].gpa_page[prp_cnt]);
691	pktlen = hlen + dlen;
692	pad_pktlen = VMBUS_CHANPKT_TOTLEN(pktlen);
693
694	pkt.cp_hdr.cph_type = VMBUS_CHANPKT_TYPE_GPA;
695	pkt.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
696	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_hlen, hlen);
697	VMBUS_CHANPKT_SETLEN(pkt.cp_hdr.cph_tlen, pad_pktlen);
698	pkt.cp_hdr.cph_xactid = xactid;
699	pkt.cp_rsvd = 0;
700	pkt.cp_range_cnt = 1;
701
702	iov[0].iov_base = &pkt;
703	iov[0].iov_len = sizeof(pkt);
704	iov[1].iov_base = prp;
705	iov[1].iov_len = __offsetof(struct vmbus_gpa_range, gpa_page[prp_cnt]);
706	iov[2].iov_base = data;
707	iov[2].iov_len = dlen;
708	iov[3].iov_base = &pad;
709	iov[3].iov_len = pad_pktlen - pktlen;
710
711	error = hv_ring_buffer_write(&chan->ch_txbr, iov, 4, &send_evt);
712	if (!error && send_evt)
713		vmbus_chan_signal_tx(chan);
714	return error;
715}
716
717int
718vmbus_chan_recv(struct vmbus_channel *chan, void *data, int *dlen0,
719    uint64_t *xactid)
720{
721	struct vmbus_chanpkt_hdr pkt;
722	int error, dlen, hlen;
723
724	error = hv_ring_buffer_peek(&chan->ch_rxbr, &pkt, sizeof(pkt));
725	if (error)
726		return error;
727
728	hlen = VMBUS_CHANPKT_GETLEN(pkt.cph_hlen);
729	dlen = VMBUS_CHANPKT_GETLEN(pkt.cph_tlen) - hlen;
730
731	if (*dlen0 < dlen) {
732		/* Return the size of this packet's data. */
733		*dlen0 = dlen;
734		return ENOBUFS;
735	}
736
737	*xactid = pkt.cph_xactid;
738	*dlen0 = dlen;
739
740	/* Skip packet header */
741	error = hv_ring_buffer_read(&chan->ch_rxbr, data, dlen, hlen);
742	KASSERT(!error, ("hv_ring_buffer_read failed"));
743
744	return 0;
745}
746
747int
748vmbus_chan_recv_pkt(struct vmbus_channel *chan,
749    struct vmbus_chanpkt_hdr *pkt0, int *pktlen0)
750{
751	struct vmbus_chanpkt_hdr pkt;
752	int error, pktlen;
753
754	error = hv_ring_buffer_peek(&chan->ch_rxbr, &pkt, sizeof(pkt));
755	if (error)
756		return error;
757
758	pktlen = VMBUS_CHANPKT_GETLEN(pkt.cph_tlen);
759	if (*pktlen0 < pktlen) {
760		/* Return the size of this packet. */
761		*pktlen0 = pktlen;
762		return ENOBUFS;
763	}
764	*pktlen0 = pktlen;
765
766	/* Include packet header */
767	error = hv_ring_buffer_read(&chan->ch_rxbr, pkt0, pktlen, 0);
768	KASSERT(!error, ("hv_ring_buffer_read failed"));
769
770	return 0;
771}
772
773static void
774vmbus_chan_task(void *xchan, int pending __unused)
775{
776	struct vmbus_channel *chan = xchan;
777	vmbus_chan_callback_t cb = chan->ch_cb;
778	void *cbarg = chan->ch_cbarg;
779
780	/*
781	 * Optimize host to guest signaling by ensuring:
782	 * 1. While reading the channel, we disable interrupts from
783	 *    host.
784	 * 2. Ensure that we process all posted messages from the host
785	 *    before returning from this callback.
786	 * 3. Once we return, enable signaling from the host. Once this
787	 *    state is set we check to see if additional packets are
788	 *    available to read. In this case we repeat the process.
789	 *
790	 * NOTE: Interrupt has been disabled in the ISR.
791	 */
792	for (;;) {
793		uint32_t left;
794
795		cb(chan, cbarg);
796
797		left = hv_ring_buffer_read_end(&chan->ch_rxbr);
798		if (left == 0) {
799			/* No more data in RX bufring; done */
800			break;
801		}
802		hv_ring_buffer_read_begin(&chan->ch_rxbr);
803	}
804}
805
806static void
807vmbus_chan_task_nobatch(void *xchan, int pending __unused)
808{
809	struct vmbus_channel *chan = xchan;
810
811	chan->ch_cb(chan, chan->ch_cbarg);
812}
813
814static __inline void
815vmbus_event_flags_proc(struct vmbus_softc *sc, volatile u_long *event_flags,
816    int flag_cnt)
817{
818	int f;
819
820	for (f = 0; f < flag_cnt; ++f) {
821		uint32_t chid_base;
822		u_long flags;
823		int chid_ofs;
824
825		if (event_flags[f] == 0)
826			continue;
827
828		flags = atomic_swap_long(&event_flags[f], 0);
829		chid_base = f << VMBUS_EVTFLAG_SHIFT;
830
831		while ((chid_ofs = ffsl(flags)) != 0) {
832			struct vmbus_channel *chan;
833
834			--chid_ofs; /* NOTE: ffsl is 1-based */
835			flags &= ~(1UL << chid_ofs);
836
837			chan = sc->vmbus_chmap[chid_base + chid_ofs];
838
839			/* if channel is closed or closing */
840			if (chan == NULL || chan->ch_tq == NULL)
841				continue;
842
843			if (chan->ch_flags & VMBUS_CHAN_FLAG_BATCHREAD)
844				hv_ring_buffer_read_begin(&chan->ch_rxbr);
845			taskqueue_enqueue(chan->ch_tq, &chan->ch_task);
846		}
847	}
848}
849
850void
851vmbus_event_proc(struct vmbus_softc *sc, int cpu)
852{
853	struct vmbus_evtflags *eventf;
854
855	/*
856	 * On Host with Win8 or above, the event page can be checked directly
857	 * to get the id of the channel that has the pending interrupt.
858	 */
859	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
860	vmbus_event_flags_proc(sc, eventf->evt_flags,
861	    VMBUS_PCPU_GET(sc, event_flags_cnt, cpu));
862}
863
864void
865vmbus_event_proc_compat(struct vmbus_softc *sc, int cpu)
866{
867	struct vmbus_evtflags *eventf;
868
869	eventf = VMBUS_PCPU_GET(sc, event_flags, cpu) + VMBUS_SINT_MESSAGE;
870	if (atomic_testandclear_long(&eventf->evt_flags[0], 0)) {
871		vmbus_event_flags_proc(sc, sc->vmbus_rx_evtflags,
872		    VMBUS_CHAN_MAX_COMPAT >> VMBUS_EVTFLAG_SHIFT);
873	}
874}
875
876static void
877vmbus_chan_update_evtflagcnt(struct vmbus_softc *sc,
878    const struct vmbus_channel *chan)
879{
880	volatile int *flag_cnt_ptr;
881	int flag_cnt;
882
883	flag_cnt = (chan->ch_id / VMBUS_EVTFLAG_LEN) + 1;
884	flag_cnt_ptr = VMBUS_PCPU_PTR(sc, event_flags_cnt, chan->ch_cpuid);
885
886	for (;;) {
887		int old_flag_cnt;
888
889		old_flag_cnt = *flag_cnt_ptr;
890		if (old_flag_cnt >= flag_cnt)
891			break;
892		if (atomic_cmpset_int(flag_cnt_ptr, old_flag_cnt, flag_cnt)) {
893			if (bootverbose) {
894				device_printf(sc->vmbus_dev,
895				    "channel%u update cpu%d flag_cnt to %d\n",
896				    chan->ch_id, chan->ch_cpuid, flag_cnt);
897			}
898			break;
899		}
900	}
901}
902
903static struct vmbus_channel *
904vmbus_chan_alloc(struct vmbus_softc *sc)
905{
906	struct vmbus_channel *chan;
907
908	chan = malloc(sizeof(*chan), M_DEVBUF, M_WAITOK | M_ZERO);
909
910	chan->ch_monprm = hyperv_dmamem_alloc(bus_get_dma_tag(sc->vmbus_dev),
911	    HYPERCALL_PARAM_ALIGN, 0, sizeof(struct hyperv_mon_param),
912	    &chan->ch_monprm_dma, BUS_DMA_WAITOK | BUS_DMA_ZERO);
913	if (chan->ch_monprm == NULL) {
914		device_printf(sc->vmbus_dev, "monprm alloc failed\n");
915		free(chan, M_DEVBUF);
916		return NULL;
917	}
918
919	chan->ch_vmbus = sc;
920	mtx_init(&chan->ch_subchan_lock, "vmbus subchan", NULL, MTX_DEF);
921	TAILQ_INIT(&chan->ch_subchans);
922	TASK_INIT(&chan->ch_detach_task, 0, vmbus_chan_detach_task, chan);
923
924	return chan;
925}
926
927static void
928vmbus_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	free(chan, M_DEVBUF);
936}
937
938static int
939vmbus_chan_add(struct vmbus_channel *newchan)
940{
941	struct vmbus_softc *sc = newchan->ch_vmbus;
942	struct vmbus_channel *prichan;
943
944	if (newchan->ch_id == 0) {
945		/*
946		 * XXX
947		 * Chan0 will neither be processed nor should be offered;
948		 * skip it.
949		 */
950		device_printf(sc->vmbus_dev, "got chan0 offer, discard\n");
951		return EINVAL;
952	} else if (newchan->ch_id >= VMBUS_CHAN_MAX) {
953		device_printf(sc->vmbus_dev, "invalid chan%u offer\n",
954		    newchan->ch_id);
955		return EINVAL;
956	}
957	sc->vmbus_chmap[newchan->ch_id] = newchan;
958
959	if (bootverbose) {
960		device_printf(sc->vmbus_dev, "chan%u subidx%u offer\n",
961		    newchan->ch_id, newchan->ch_subidx);
962	}
963
964	mtx_lock(&sc->vmbus_prichan_lock);
965	TAILQ_FOREACH(prichan, &sc->vmbus_prichans, ch_prilink) {
966		/*
967		 * Sub-channel will have the same type GUID and instance
968		 * GUID as its primary channel.
969		 */
970		if (memcmp(&prichan->ch_guid_type, &newchan->ch_guid_type,
971		    sizeof(struct hyperv_guid)) == 0 &&
972		    memcmp(&prichan->ch_guid_inst, &newchan->ch_guid_inst,
973		    sizeof(struct hyperv_guid)) == 0)
974			break;
975	}
976	if (VMBUS_CHAN_ISPRIMARY(newchan)) {
977		if (prichan == NULL) {
978			/* Install the new primary channel */
979			TAILQ_INSERT_TAIL(&sc->vmbus_prichans, newchan,
980			    ch_prilink);
981			mtx_unlock(&sc->vmbus_prichan_lock);
982			return 0;
983		} else {
984			mtx_unlock(&sc->vmbus_prichan_lock);
985			device_printf(sc->vmbus_dev, "duplicated primary "
986			    "chan%u\n", newchan->ch_id);
987			return EINVAL;
988		}
989	} else { /* Sub-channel */
990		if (prichan == NULL) {
991			mtx_unlock(&sc->vmbus_prichan_lock);
992			device_printf(sc->vmbus_dev, "no primary chan for "
993			    "chan%u\n", newchan->ch_id);
994			return EINVAL;
995		}
996		/*
997		 * Found the primary channel for this sub-channel and
998		 * move on.
999		 *
1000		 * XXX refcnt prichan
1001		 */
1002	}
1003	mtx_unlock(&sc->vmbus_prichan_lock);
1004
1005	/*
1006	 * This is a sub-channel; link it with the primary channel.
1007	 */
1008	KASSERT(!VMBUS_CHAN_ISPRIMARY(newchan),
1009	    ("new channel is not sub-channel"));
1010	KASSERT(prichan != NULL, ("no primary channel"));
1011
1012	newchan->ch_prichan = prichan;
1013	newchan->ch_dev = prichan->ch_dev;
1014
1015	mtx_lock(&prichan->ch_subchan_lock);
1016	TAILQ_INSERT_TAIL(&prichan->ch_subchans, newchan, ch_sublink);
1017	/*
1018	 * Bump up sub-channel count and notify anyone that is
1019	 * interested in this sub-channel, after this sub-channel
1020	 * is setup.
1021	 */
1022	prichan->ch_subchan_cnt++;
1023	mtx_unlock(&prichan->ch_subchan_lock);
1024	wakeup(prichan);
1025
1026	return 0;
1027}
1028
1029void
1030vmbus_chan_cpu_set(struct vmbus_channel *chan, int cpu)
1031{
1032	KASSERT(cpu >= 0 && cpu < mp_ncpus, ("invalid cpu %d", cpu));
1033
1034	if (chan->ch_vmbus->vmbus_version == VMBUS_VERSION_WS2008 ||
1035	    chan->ch_vmbus->vmbus_version == VMBUS_VERSION_WIN7) {
1036		/* Only cpu0 is supported */
1037		cpu = 0;
1038	}
1039
1040	chan->ch_cpuid = cpu;
1041	chan->ch_vcpuid = VMBUS_PCPU_GET(chan->ch_vmbus, vcpuid, cpu);
1042
1043	if (bootverbose) {
1044		printf("vmbus_chan%u: assigned to cpu%u [vcpu%u]\n",
1045		    chan->ch_id, chan->ch_cpuid, chan->ch_vcpuid);
1046	}
1047}
1048
1049void
1050vmbus_chan_cpu_rr(struct vmbus_channel *chan)
1051{
1052	static uint32_t vmbus_chan_nextcpu;
1053	int cpu;
1054
1055	cpu = atomic_fetchadd_int(&vmbus_chan_nextcpu, 1) % mp_ncpus;
1056	vmbus_chan_cpu_set(chan, cpu);
1057}
1058
1059static void
1060vmbus_chan_cpu_default(struct vmbus_channel *chan)
1061{
1062	/*
1063	 * By default, pin the channel to cpu0.  Devices having
1064	 * special channel-cpu mapping requirement should call
1065	 * vmbus_chan_cpu_{set,rr}().
1066	 */
1067	vmbus_chan_cpu_set(chan, 0);
1068}
1069
1070static void
1071vmbus_chan_msgproc_choffer(struct vmbus_softc *sc,
1072    const struct vmbus_message *msg)
1073{
1074	const struct vmbus_chanmsg_choffer *offer;
1075	struct vmbus_channel *chan;
1076	int error;
1077
1078	offer = (const struct vmbus_chanmsg_choffer *)msg->msg_data;
1079
1080	chan = vmbus_chan_alloc(sc);
1081	if (chan == NULL) {
1082		device_printf(sc->vmbus_dev, "allocate chan%u failed\n",
1083		    offer->chm_chanid);
1084		return;
1085	}
1086
1087	chan->ch_id = offer->chm_chanid;
1088	chan->ch_subidx = offer->chm_subidx;
1089	chan->ch_guid_type = offer->chm_chtype;
1090	chan->ch_guid_inst = offer->chm_chinst;
1091
1092	/* Batch reading is on by default */
1093	chan->ch_flags |= VMBUS_CHAN_FLAG_BATCHREAD;
1094
1095	chan->ch_monprm->mp_connid = VMBUS_CONNID_EVENT;
1096	if (sc->vmbus_version != VMBUS_VERSION_WS2008)
1097		chan->ch_monprm->mp_connid = offer->chm_connid;
1098
1099	if (offer->chm_flags1 & VMBUS_CHOFFER_FLAG1_HASMNF) {
1100		int trig_idx;
1101
1102		/*
1103		 * Setup MNF stuffs.
1104		 */
1105		chan->ch_txflags |= VMBUS_CHAN_TXF_HASMNF;
1106
1107		trig_idx = offer->chm_montrig / VMBUS_MONTRIG_LEN;
1108		if (trig_idx >= VMBUS_MONTRIGS_MAX)
1109			panic("invalid monitor trigger %u", offer->chm_montrig);
1110		chan->ch_montrig =
1111		    &sc->vmbus_mnf2->mnf_trigs[trig_idx].mt_pending;
1112
1113		chan->ch_montrig_mask =
1114		    1 << (offer->chm_montrig % VMBUS_MONTRIG_LEN);
1115	}
1116
1117	/*
1118	 * Setup event flag.
1119	 */
1120	chan->ch_evtflag =
1121	    &sc->vmbus_tx_evtflags[chan->ch_id >> VMBUS_EVTFLAG_SHIFT];
1122	chan->ch_evtflag_mask = 1UL << (chan->ch_id & VMBUS_EVTFLAG_MASK);
1123
1124	/* Select default cpu for this channel. */
1125	vmbus_chan_cpu_default(chan);
1126
1127	error = vmbus_chan_add(chan);
1128	if (error) {
1129		device_printf(sc->vmbus_dev, "add chan%u failed: %d\n",
1130		    chan->ch_id, error);
1131		vmbus_chan_free(chan);
1132		return;
1133	}
1134
1135	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1136		/*
1137		 * Add device for this primary channel.
1138		 *
1139		 * NOTE:
1140		 * Error is ignored here; don't have much to do if error
1141		 * really happens.
1142		 */
1143		vmbus_add_child(chan);
1144	}
1145}
1146
1147/*
1148 * XXX pretty broken; need rework.
1149 */
1150static void
1151vmbus_chan_msgproc_chrescind(struct vmbus_softc *sc,
1152    const struct vmbus_message *msg)
1153{
1154	const struct vmbus_chanmsg_chrescind *note;
1155	struct vmbus_channel *chan;
1156
1157	note = (const struct vmbus_chanmsg_chrescind *)msg->msg_data;
1158	if (note->chm_chanid > VMBUS_CHAN_MAX) {
1159		device_printf(sc->vmbus_dev, "invalid rescinded chan%u\n",
1160		    note->chm_chanid);
1161		return;
1162	}
1163
1164	if (bootverbose) {
1165		device_printf(sc->vmbus_dev, "chan%u rescinded\n",
1166		    note->chm_chanid);
1167	}
1168
1169	chan = sc->vmbus_chmap[note->chm_chanid];
1170	if (chan == NULL)
1171		return;
1172	sc->vmbus_chmap[note->chm_chanid] = NULL;
1173
1174	taskqueue_enqueue(taskqueue_thread, &chan->ch_detach_task);
1175}
1176
1177static void
1178vmbus_chan_detach_task(void *xchan, int pending __unused)
1179{
1180	struct vmbus_channel *chan = xchan;
1181
1182	if (VMBUS_CHAN_ISPRIMARY(chan)) {
1183		/* Only primary channel owns the device */
1184		vmbus_delete_child(chan);
1185		/* NOTE: DO NOT free primary channel for now */
1186	} else {
1187		struct vmbus_softc *sc = chan->ch_vmbus;
1188		struct vmbus_channel *pri_chan = chan->ch_prichan;
1189		struct vmbus_chanmsg_chfree *req;
1190		struct vmbus_msghc *mh;
1191		int error;
1192
1193		mh = vmbus_msghc_get(sc, sizeof(*req));
1194		if (mh == NULL) {
1195			device_printf(sc->vmbus_dev,
1196			    "can not get msg hypercall for chfree(chan%u)\n",
1197			    chan->ch_id);
1198			goto remove;
1199		}
1200
1201		req = vmbus_msghc_dataptr(mh);
1202		req->chm_hdr.chm_type = VMBUS_CHANMSG_TYPE_CHFREE;
1203		req->chm_chanid = chan->ch_id;
1204
1205		error = vmbus_msghc_exec_noresult(mh);
1206		vmbus_msghc_put(sc, mh);
1207
1208		if (error) {
1209			device_printf(sc->vmbus_dev,
1210			    "chfree(chan%u) failed: %d",
1211			    chan->ch_id, error);
1212			/* NOTE: Move on! */
1213		} else {
1214			if (bootverbose) {
1215				device_printf(sc->vmbus_dev, "chan%u freed\n",
1216				    chan->ch_id);
1217			}
1218		}
1219remove:
1220		mtx_lock(&pri_chan->ch_subchan_lock);
1221		TAILQ_REMOVE(&pri_chan->ch_subchans, chan, ch_sublink);
1222		KASSERT(pri_chan->ch_subchan_cnt > 0,
1223		    ("invalid subchan_cnt %d", pri_chan->ch_subchan_cnt));
1224		pri_chan->ch_subchan_cnt--;
1225		mtx_unlock(&pri_chan->ch_subchan_lock);
1226		wakeup(pri_chan);
1227
1228		vmbus_chan_free(chan);
1229	}
1230}
1231
1232/*
1233 * Detach all devices and destroy the corresponding primary channels.
1234 */
1235void
1236vmbus_chan_destroy_all(struct vmbus_softc *sc)
1237{
1238	struct vmbus_channel *chan;
1239
1240	mtx_lock(&sc->vmbus_prichan_lock);
1241	while ((chan = TAILQ_FIRST(&sc->vmbus_prichans)) != NULL) {
1242		KASSERT(VMBUS_CHAN_ISPRIMARY(chan), ("not primary channel"));
1243		TAILQ_REMOVE(&sc->vmbus_prichans, chan, ch_prilink);
1244		mtx_unlock(&sc->vmbus_prichan_lock);
1245
1246		vmbus_delete_child(chan);
1247		vmbus_chan_free(chan);
1248
1249		mtx_lock(&sc->vmbus_prichan_lock);
1250	}
1251	bzero(sc->vmbus_chmap,
1252	    sizeof(struct vmbus_channel *) * VMBUS_CHAN_MAX);
1253	mtx_unlock(&sc->vmbus_prichan_lock);
1254}
1255
1256/*
1257 * The channel whose vcpu binding is closest to the currect vcpu will
1258 * be selected.
1259 * If no multi-channel, always select primary channel.
1260 */
1261struct vmbus_channel *
1262vmbus_chan_cpu2chan(struct vmbus_channel *prichan, int cpu)
1263{
1264	struct vmbus_channel *sel, *chan;
1265	uint32_t vcpu, sel_dist;
1266
1267	KASSERT(cpu >= 0 && cpu < mp_ncpus, ("invalid cpuid %d", cpu));
1268	if (TAILQ_EMPTY(&prichan->ch_subchans))
1269		return prichan;
1270
1271	vcpu = VMBUS_PCPU_GET(prichan->ch_vmbus, vcpuid, cpu);
1272
1273#define CHAN_VCPU_DIST(ch, vcpu)		\
1274	(((ch)->ch_vcpuid > (vcpu)) ?		\
1275	 ((ch)->ch_vcpuid - (vcpu)) : ((vcpu) - (ch)->ch_vcpuid))
1276
1277#define CHAN_SELECT(ch)				\
1278do {						\
1279	sel = ch;				\
1280	sel_dist = CHAN_VCPU_DIST(ch, vcpu);	\
1281} while (0)
1282
1283	CHAN_SELECT(prichan);
1284
1285	mtx_lock(&prichan->ch_subchan_lock);
1286	TAILQ_FOREACH(chan, &prichan->ch_subchans, ch_sublink) {
1287		uint32_t dist;
1288
1289		KASSERT(chan->ch_stflags & VMBUS_CHAN_ST_OPENED,
1290		    ("chan%u is not opened", chan->ch_id));
1291
1292		if (chan->ch_vcpuid == vcpu) {
1293			/* Exact match; done */
1294			CHAN_SELECT(chan);
1295			break;
1296		}
1297
1298		dist = CHAN_VCPU_DIST(chan, vcpu);
1299		if (sel_dist <= dist) {
1300			/* Far or same distance; skip */
1301			continue;
1302		}
1303
1304		/* Select the closer channel. */
1305		CHAN_SELECT(chan);
1306	}
1307	mtx_unlock(&prichan->ch_subchan_lock);
1308
1309#undef CHAN_SELECT
1310#undef CHAN_VCPU_DIST
1311
1312	return sel;
1313}
1314
1315struct vmbus_channel **
1316vmbus_subchan_get(struct vmbus_channel *pri_chan, int subchan_cnt)
1317{
1318	struct vmbus_channel **ret, *chan;
1319	int i;
1320
1321	ret = malloc(subchan_cnt * sizeof(struct vmbus_channel *), M_TEMP,
1322	    M_WAITOK);
1323
1324	mtx_lock(&pri_chan->ch_subchan_lock);
1325
1326	while (pri_chan->ch_subchan_cnt < subchan_cnt)
1327		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "subch", 0);
1328
1329	i = 0;
1330	TAILQ_FOREACH(chan, &pri_chan->ch_subchans, ch_sublink) {
1331		/* TODO: refcnt chan */
1332		ret[i] = chan;
1333
1334		++i;
1335		if (i == subchan_cnt)
1336			break;
1337	}
1338	KASSERT(i == subchan_cnt, ("invalid subchan count %d, should be %d",
1339	    pri_chan->ch_subchan_cnt, subchan_cnt));
1340
1341	mtx_unlock(&pri_chan->ch_subchan_lock);
1342
1343	return ret;
1344}
1345
1346void
1347vmbus_subchan_rel(struct vmbus_channel **subchan, int subchan_cnt __unused)
1348{
1349
1350	free(subchan, M_TEMP);
1351}
1352
1353void
1354vmbus_subchan_drain(struct vmbus_channel *pri_chan)
1355{
1356	mtx_lock(&pri_chan->ch_subchan_lock);
1357	while (pri_chan->ch_subchan_cnt > 0)
1358		mtx_sleep(pri_chan, &pri_chan->ch_subchan_lock, 0, "dsubch", 0);
1359	mtx_unlock(&pri_chan->ch_subchan_lock);
1360}
1361
1362void
1363vmbus_chan_msgproc(struct vmbus_softc *sc, const struct vmbus_message *msg)
1364{
1365	vmbus_chanmsg_proc_t msg_proc;
1366	uint32_t msg_type;
1367
1368	msg_type = ((const struct vmbus_chanmsg_hdr *)msg->msg_data)->chm_type;
1369	KASSERT(msg_type < VMBUS_CHANMSG_TYPE_MAX,
1370	    ("invalid message type %u", msg_type));
1371
1372	msg_proc = vmbus_chan_msgprocs[msg_type];
1373	if (msg_proc != NULL)
1374		msg_proc(sc, msg);
1375}
1376
1377void
1378vmbus_chan_set_readbatch(struct vmbus_channel *chan, bool on)
1379{
1380	if (!on)
1381		chan->ch_flags &= ~VMBUS_CHAN_FLAG_BATCHREAD;
1382	else
1383		chan->ch_flags |= VMBUS_CHAN_FLAG_BATCHREAD;
1384}
1385
1386uint32_t
1387vmbus_chan_id(const struct vmbus_channel *chan)
1388{
1389	return chan->ch_id;
1390}
1391
1392uint32_t
1393vmbus_chan_subidx(const struct vmbus_channel *chan)
1394{
1395	return chan->ch_subidx;
1396}
1397
1398bool
1399vmbus_chan_is_primary(const struct vmbus_channel *chan)
1400{
1401	if (VMBUS_CHAN_ISPRIMARY(chan))
1402		return true;
1403	else
1404		return false;
1405}
1406
1407const struct hyperv_guid *
1408vmbus_chan_guid_inst(const struct vmbus_channel *chan)
1409{
1410	return &chan->ch_guid_inst;
1411}
1412