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