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