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