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