Staging: hv: channel: export vmbus_sendpacket_multipagebuffer to modules
[pandora-kernel.git] / drivers / staging / hv / channel.c
1 /*
2  * Copyright (c) 2009, Microsoft Corporation.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Authors:
18  *   Haiyang Zhang <haiyangz@microsoft.com>
19  *   Hank Janssen  <hjanssen@microsoft.com>
20  */
21 #include <linux/kernel.h>
22 #include <linux/mm.h>
23 #include <linux/slab.h>
24 #include <linux/module.h>
25 #include "osd.h"
26 #include "logging.h"
27 #include "vmbus_private.h"
28
29 /* Internal routines */
30 static int create_gpadl_header(
31         void *kbuffer,  /* must be phys and virt contiguous */
32         u32 size,       /* page-size multiple */
33         struct vmbus_channel_msginfo **msginfo,
34         u32 *messagecount);
35 static void dump_vmbus_channel(struct vmbus_channel *channel);
36 static void vmbus_setevent(struct vmbus_channel *channel);
37
38
39 #if 0
40 static void DumpMonitorPage(struct hv_monitor_page *MonitorPage)
41 {
42         int i = 0;
43         int j = 0;
44
45         DPRINT_DBG(VMBUS, "monitorPage - %p, trigger state - %d",
46                    MonitorPage, MonitorPage->TriggerState);
47
48         for (i = 0; i < 4; i++)
49                 DPRINT_DBG(VMBUS, "trigger group (%d) - %llx", i,
50                            MonitorPage->TriggerGroup[i].AsUINT64);
51
52         for (i = 0; i < 4; i++) {
53                 for (j = 0; j < 32; j++) {
54                         DPRINT_DBG(VMBUS, "latency (%d)(%d) - %llx", i, j,
55                                    MonitorPage->Latency[i][j]);
56                 }
57         }
58         for (i = 0; i < 4; i++) {
59                 for (j = 0; j < 32; j++) {
60                         DPRINT_DBG(VMBUS, "param-conn id (%d)(%d) - %d", i, j,
61                                MonitorPage->Parameter[i][j].ConnectionId.Asu32);
62                         DPRINT_DBG(VMBUS, "param-flag (%d)(%d) - %d", i, j,
63                                 MonitorPage->Parameter[i][j].FlagNumber);
64                 }
65         }
66 }
67 #endif
68
69 /*
70  * vmbus_setevent- Trigger an event notification on the specified
71  * channel.
72  */
73 static void vmbus_setevent(struct vmbus_channel *channel)
74 {
75         struct hv_monitor_page *monitorpage;
76
77         if (channel->OfferMsg.MonitorAllocated) {
78                 /* Each u32 represents 32 channels */
79                 set_bit(channel->OfferMsg.ChildRelId & 31,
80                         (unsigned long *) gVmbusConnection.SendInterruptPage +
81                         (channel->OfferMsg.ChildRelId >> 5));
82
83                 monitorpage = gVmbusConnection.MonitorPages;
84                 monitorpage++; /* Get the child to parent monitor page */
85
86                 set_bit(channel->MonitorBit,
87                         (unsigned long *)&monitorpage->TriggerGroup
88                                         [channel->MonitorGroup].Pending);
89
90         } else {
91                 VmbusSetEvent(channel->OfferMsg.ChildRelId);
92         }
93 }
94
95 #if 0
96 static void VmbusChannelClearEvent(struct vmbus_channel *channel)
97 {
98         struct hv_monitor_page *monitorPage;
99
100         if (Channel->OfferMsg.MonitorAllocated) {
101                 /* Each u32 represents 32 channels */
102                 clear_bit(Channel->OfferMsg.ChildRelId & 31,
103                           (unsigned long *)gVmbusConnection.SendInterruptPage +
104                           (Channel->OfferMsg.ChildRelId >> 5));
105
106                 monitorPage =
107                         (struct hv_monitor_page *)gVmbusConnection.MonitorPages;
108                 monitorPage++; /* Get the child to parent monitor page */
109
110                 clear_bit(Channel->MonitorBit,
111                           (unsigned long *)&monitorPage->TriggerGroup
112                                         [Channel->MonitorGroup].Pending);
113         }
114 }
115
116 #endif
117 /*
118  * vmbus_get_debug_info -Retrieve various channel debug info
119  */
120 void vmbus_get_debug_info(struct vmbus_channel *channel,
121                               struct vmbus_channel_debug_info *debuginfo)
122 {
123         struct hv_monitor_page *monitorpage;
124         u8 monitor_group = (u8)channel->OfferMsg.MonitorId / 32;
125         u8 monitor_offset = (u8)channel->OfferMsg.MonitorId % 32;
126         /* u32 monitorBit       = 1 << monitorOffset; */
127
128         debuginfo->RelId = channel->OfferMsg.ChildRelId;
129         debuginfo->State = channel->State;
130         memcpy(&debuginfo->InterfaceType,
131                &channel->OfferMsg.Offer.InterfaceType, sizeof(struct hv_guid));
132         memcpy(&debuginfo->InterfaceInstance,
133                &channel->OfferMsg.Offer.InterfaceInstance,
134                sizeof(struct hv_guid));
135
136         monitorpage = (struct hv_monitor_page *)gVmbusConnection.MonitorPages;
137
138         debuginfo->MonitorId = channel->OfferMsg.MonitorId;
139
140         debuginfo->ServerMonitorPending =
141                         monitorpage->TriggerGroup[monitor_group].Pending;
142         debuginfo->ServerMonitorLatency =
143                         monitorpage->Latency[monitor_group][monitor_offset];
144         debuginfo->ServerMonitorConnectionId =
145                         monitorpage->Parameter[monitor_group]
146                                         [monitor_offset].ConnectionId.u.Id;
147
148         monitorpage++;
149
150         debuginfo->ClientMonitorPending =
151                         monitorpage->TriggerGroup[monitor_group].Pending;
152         debuginfo->ClientMonitorLatency =
153                         monitorpage->Latency[monitor_group][monitor_offset];
154         debuginfo->ClientMonitorConnectionId =
155                         monitorpage->Parameter[monitor_group]
156                                         [monitor_offset].ConnectionId.u.Id;
157
158         RingBufferGetDebugInfo(&channel->Inbound, &debuginfo->Inbound);
159         RingBufferGetDebugInfo(&channel->Outbound, &debuginfo->Outbound);
160 }
161
162 /*
163  * vmbus_open - Open the specified channel.
164  */
165 int vmbus_open(struct vmbus_channel *newchannel, u32 send_ringbuffer_size,
166                      u32 recv_ringbuffer_size, void *userdata, u32 userdatalen,
167                      void (*onchannelcallback)(void *context), void *context)
168 {
169         struct vmbus_channel_open_channel *openMsg;
170         struct vmbus_channel_msginfo *openInfo = NULL;
171         void *in, *out;
172         unsigned long flags;
173         int ret, err = 0;
174
175         /* Aligned to page size */
176         /* ASSERT(!(SendRingBufferSize & (PAGE_SIZE - 1))); */
177         /* ASSERT(!(RecvRingBufferSize & (PAGE_SIZE - 1))); */
178
179         newchannel->OnChannelCallback = onchannelcallback;
180         newchannel->ChannelCallbackContext = context;
181
182         /* Allocate the ring buffer */
183         out = osd_PageAlloc((send_ringbuffer_size + recv_ringbuffer_size)
184                              >> PAGE_SHIFT);
185         if (!out)
186                 return -ENOMEM;
187
188         /* ASSERT(((unsigned long)out & (PAGE_SIZE-1)) == 0); */
189
190         in = (void *)((unsigned long)out + send_ringbuffer_size);
191
192         newchannel->RingBufferPages = out;
193         newchannel->RingBufferPageCount = (send_ringbuffer_size +
194                                            recv_ringbuffer_size) >> PAGE_SHIFT;
195
196         ret = RingBufferInit(&newchannel->Outbound, out, send_ringbuffer_size);
197         if (ret != 0) {
198                 err = ret;
199                 goto errorout;
200         }
201
202         ret = RingBufferInit(&newchannel->Inbound, in, recv_ringbuffer_size);
203         if (ret != 0) {
204                 err = ret;
205                 goto errorout;
206         }
207
208
209         /* Establish the gpadl for the ring buffer */
210         DPRINT_DBG(VMBUS, "Establishing ring buffer's gpadl for channel %p...",
211                    newchannel);
212
213         newchannel->RingBufferGpadlHandle = 0;
214
215         ret = vmbus_establish_gpadl(newchannel,
216                                          newchannel->Outbound.RingBuffer,
217                                          send_ringbuffer_size +
218                                          recv_ringbuffer_size,
219                                          &newchannel->RingBufferGpadlHandle);
220
221         if (ret != 0) {
222                 err = ret;
223                 goto errorout;
224         }
225
226         DPRINT_DBG(VMBUS, "channel %p <relid %d gpadl 0x%x send ring %p "
227                    "size %d recv ring %p size %d, downstreamoffset %d>",
228                    newchannel, newchannel->OfferMsg.ChildRelId,
229                    newchannel->RingBufferGpadlHandle,
230                    newchannel->Outbound.RingBuffer,
231                    newchannel->Outbound.RingSize,
232                    newchannel->Inbound.RingBuffer,
233                    newchannel->Inbound.RingSize,
234                    send_ringbuffer_size);
235
236         /* Create and init the channel open message */
237         openInfo = kmalloc(sizeof(*openInfo) +
238                            sizeof(struct vmbus_channel_open_channel),
239                            GFP_KERNEL);
240         if (!openInfo) {
241                 err = -ENOMEM;
242                 goto errorout;
243         }
244
245         openInfo->WaitEvent = osd_WaitEventCreate();
246         if (!openInfo->WaitEvent) {
247                 err = -ENOMEM;
248                 goto errorout;
249         }
250
251         openMsg = (struct vmbus_channel_open_channel *)openInfo->Msg;
252         openMsg->Header.MessageType = ChannelMessageOpenChannel;
253         openMsg->OpenId = newchannel->OfferMsg.ChildRelId; /* FIXME */
254         openMsg->ChildRelId = newchannel->OfferMsg.ChildRelId;
255         openMsg->RingBufferGpadlHandle = newchannel->RingBufferGpadlHandle;
256         openMsg->DownstreamRingBufferPageOffset = send_ringbuffer_size >>
257                                                   PAGE_SHIFT;
258         openMsg->ServerContextAreaGpadlHandle = 0; /* TODO */
259
260         if (userdatalen > MAX_USER_DEFINED_BYTES) {
261                 err = -EINVAL;
262                 goto errorout;
263         }
264
265         if (userdatalen)
266                 memcpy(openMsg->UserData, userdata, userdatalen);
267
268         spin_lock_irqsave(&gVmbusConnection.channelmsg_lock, flags);
269         list_add_tail(&openInfo->MsgListEntry,
270                       &gVmbusConnection.ChannelMsgList);
271         spin_unlock_irqrestore(&gVmbusConnection.channelmsg_lock, flags);
272
273         DPRINT_DBG(VMBUS, "Sending channel open msg...");
274
275         ret = VmbusPostMessage(openMsg,
276                                sizeof(struct vmbus_channel_open_channel));
277         if (ret != 0) {
278                 DPRINT_ERR(VMBUS, "unable to open channel - %d", ret);
279                 goto Cleanup;
280         }
281
282         /* FIXME: Need to time-out here */
283         osd_WaitEventWait(openInfo->WaitEvent);
284
285         if (openInfo->Response.OpenResult.Status == 0)
286                 DPRINT_INFO(VMBUS, "channel <%p> open success!!", newchannel);
287         else
288                 DPRINT_INFO(VMBUS, "channel <%p> open failed - %d!!",
289                             newchannel, openInfo->Response.OpenResult.Status);
290
291 Cleanup:
292         spin_lock_irqsave(&gVmbusConnection.channelmsg_lock, flags);
293         list_del(&openInfo->MsgListEntry);
294         spin_unlock_irqrestore(&gVmbusConnection.channelmsg_lock, flags);
295
296         kfree(openInfo->WaitEvent);
297         kfree(openInfo);
298         return 0;
299
300 errorout:
301         RingBufferCleanup(&newchannel->Outbound);
302         RingBufferCleanup(&newchannel->Inbound);
303         osd_PageFree(out, (send_ringbuffer_size + recv_ringbuffer_size)
304                      >> PAGE_SHIFT);
305         kfree(openInfo);
306         return err;
307 }
308
309 /*
310  * dump_gpadl_body - Dump the gpadl body message to the console for
311  * debugging purposes.
312  */
313 static void dump_gpadl_body(struct vmbus_channel_gpadl_body *gpadl, u32 len)
314 {
315         int i;
316         int pfncount;
317
318         pfncount = (len - sizeof(struct vmbus_channel_gpadl_body)) /
319                    sizeof(u64);
320         DPRINT_DBG(VMBUS, "gpadl body - len %d pfn count %d", len, pfncount);
321
322         for (i = 0; i < pfncount; i++)
323                 DPRINT_DBG(VMBUS, "gpadl body  - %d) pfn %llu",
324                            i, gpadl->Pfn[i]);
325 }
326
327 /*
328  * dump_gpadl_header - Dump the gpadl header message to the console for
329  * debugging purposes.
330  */
331 static void dump_gpadl_header(struct vmbus_channel_gpadl_header *gpadl)
332 {
333         int i, j;
334         int pagecount;
335
336         DPRINT_DBG(VMBUS,
337                    "gpadl header - relid %d, range count %d, range buflen %d",
338                    gpadl->ChildRelId, gpadl->RangeCount, gpadl->RangeBufLen);
339         for (i = 0; i < gpadl->RangeCount; i++) {
340                 pagecount = gpadl->Range[i].ByteCount >> PAGE_SHIFT;
341                 pagecount = (pagecount > 26) ? 26 : pagecount;
342
343                 DPRINT_DBG(VMBUS, "gpadl range %d - len %d offset %d "
344                            "page count %d", i, gpadl->Range[i].ByteCount,
345                            gpadl->Range[i].ByteOffset, pagecount);
346
347                 for (j = 0; j < pagecount; j++)
348                         DPRINT_DBG(VMBUS, "%d) pfn %llu", j,
349                                    gpadl->Range[i].PfnArray[j]);
350         }
351 }
352
353 /*
354  * create_gpadl_header - Creates a gpadl for the specified buffer
355  */
356 static int create_gpadl_header(void *kbuffer, u32 size,
357                                          struct vmbus_channel_msginfo **msginfo,
358                                          u32 *messagecount)
359 {
360         int i;
361         int pagecount;
362         unsigned long long pfn;
363         struct vmbus_channel_gpadl_header *gpadl_header;
364         struct vmbus_channel_gpadl_body *gpadl_body;
365         struct vmbus_channel_msginfo *msgheader;
366         struct vmbus_channel_msginfo *msgbody = NULL;
367         u32 msgsize;
368
369         int pfnsum, pfncount, pfnleft, pfncurr, pfnsize;
370
371         /* ASSERT((kbuffer & (PAGE_SIZE-1)) == 0); */
372         /* ASSERT((Size & (PAGE_SIZE-1)) == 0); */
373
374         pagecount = size >> PAGE_SHIFT;
375         pfn = virt_to_phys(kbuffer) >> PAGE_SHIFT;
376
377         /* do we need a gpadl body msg */
378         pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
379                   sizeof(struct vmbus_channel_gpadl_header) -
380                   sizeof(struct gpa_range);
381         pfncount = pfnsize / sizeof(u64);
382
383         if (pagecount > pfncount) {
384                 /* we need a gpadl body */
385                 /* fill in the header */
386                 msgsize = sizeof(struct vmbus_channel_msginfo) +
387                           sizeof(struct vmbus_channel_gpadl_header) +
388                           sizeof(struct gpa_range) + pfncount * sizeof(u64);
389                 msgheader =  kzalloc(msgsize, GFP_KERNEL);
390                 if (!msgheader)
391                         goto nomem;
392
393                 INIT_LIST_HEAD(&msgheader->SubMsgList);
394                 msgheader->MessageSize = msgsize;
395
396                 gpadl_header = (struct vmbus_channel_gpadl_header *)
397                         msgheader->Msg;
398                 gpadl_header->RangeCount = 1;
399                 gpadl_header->RangeBufLen = sizeof(struct gpa_range) +
400                                          pagecount * sizeof(u64);
401                 gpadl_header->Range[0].ByteOffset = 0;
402                 gpadl_header->Range[0].ByteCount = size;
403                 for (i = 0; i < pfncount; i++)
404                         gpadl_header->Range[0].PfnArray[i] = pfn+i;
405                 *msginfo = msgheader;
406                 *messagecount = 1;
407
408                 pfnsum = pfncount;
409                 pfnleft = pagecount - pfncount;
410
411                 /* how many pfns can we fit */
412                 pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
413                           sizeof(struct vmbus_channel_gpadl_body);
414                 pfncount = pfnsize / sizeof(u64);
415
416                 /* fill in the body */
417                 while (pfnleft) {
418                         if (pfnleft > pfncount)
419                                 pfncurr = pfncount;
420                         else
421                                 pfncurr = pfnleft;
422
423                         msgsize = sizeof(struct vmbus_channel_msginfo) +
424                                   sizeof(struct vmbus_channel_gpadl_body) +
425                                   pfncurr * sizeof(u64);
426                         msgbody = kzalloc(msgsize, GFP_KERNEL);
427                         /* FIXME: we probably need to more if this fails */
428                         if (!msgbody)
429                                 goto nomem;
430                         msgbody->MessageSize = msgsize;
431                         (*messagecount)++;
432                         gpadl_body =
433                                 (struct vmbus_channel_gpadl_body *)msgbody->Msg;
434
435                         /*
436                          * FIXME:
437                          * Gpadl is u32 and we are using a pointer which could
438                          * be 64-bit
439                          */
440                         /* gpadl_body->Gpadl = kbuffer; */
441                         for (i = 0; i < pfncurr; i++)
442                                 gpadl_body->Pfn[i] = pfn + pfnsum + i;
443
444                         /* add to msg header */
445                         list_add_tail(&msgbody->MsgListEntry,
446                                       &msgheader->SubMsgList);
447                         pfnsum += pfncurr;
448                         pfnleft -= pfncurr;
449                 }
450         } else {
451                 /* everything fits in a header */
452                 msgsize = sizeof(struct vmbus_channel_msginfo) +
453                           sizeof(struct vmbus_channel_gpadl_header) +
454                           sizeof(struct gpa_range) + pagecount * sizeof(u64);
455                 msgheader = kzalloc(msgsize, GFP_KERNEL);
456                 if (msgheader == NULL)
457                         goto nomem;
458                 msgheader->MessageSize = msgsize;
459
460                 gpadl_header = (struct vmbus_channel_gpadl_header *)
461                         msgheader->Msg;
462                 gpadl_header->RangeCount = 1;
463                 gpadl_header->RangeBufLen = sizeof(struct gpa_range) +
464                                          pagecount * sizeof(u64);
465                 gpadl_header->Range[0].ByteOffset = 0;
466                 gpadl_header->Range[0].ByteCount = size;
467                 for (i = 0; i < pagecount; i++)
468                         gpadl_header->Range[0].PfnArray[i] = pfn+i;
469
470                 *msginfo = msgheader;
471                 *messagecount = 1;
472         }
473
474         return 0;
475 nomem:
476         kfree(msgheader);
477         kfree(msgbody);
478         return -ENOMEM;
479 }
480
481 /*
482  * vmbus_establish_gpadl - Estabish a GPADL for the specified buffer
483  *
484  * @channel: a channel
485  * @kbuffer: from kmalloc
486  * @size: page-size multiple
487  * @gpadl_handle: some funky thing
488  */
489 int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,
490                                u32 size, u32 *gpadl_handle)
491 {
492         struct vmbus_channel_gpadl_header *gpadlmsg;
493         struct vmbus_channel_gpadl_body *gpadl_body;
494         /* struct vmbus_channel_gpadl_created *gpadlCreated; */
495         struct vmbus_channel_msginfo *msginfo = NULL;
496         struct vmbus_channel_msginfo *submsginfo;
497         u32 msgcount;
498         struct list_head *curr;
499         u32 next_gpadl_handle;
500         unsigned long flags;
501         int ret = 0;
502
503         next_gpadl_handle = atomic_read(&gVmbusConnection.NextGpadlHandle);
504         atomic_inc(&gVmbusConnection.NextGpadlHandle);
505
506         ret = create_gpadl_header(kbuffer, size, &msginfo, &msgcount);
507         if (ret)
508                 return ret;
509
510         msginfo->WaitEvent = osd_WaitEventCreate();
511         if (!msginfo->WaitEvent) {
512                 ret = -ENOMEM;
513                 goto Cleanup;
514         }
515
516         gpadlmsg = (struct vmbus_channel_gpadl_header *)msginfo->Msg;
517         gpadlmsg->Header.MessageType = ChannelMessageGpadlHeader;
518         gpadlmsg->ChildRelId = channel->OfferMsg.ChildRelId;
519         gpadlmsg->Gpadl = next_gpadl_handle;
520
521         dump_gpadl_header(gpadlmsg);
522
523         spin_lock_irqsave(&gVmbusConnection.channelmsg_lock, flags);
524         list_add_tail(&msginfo->MsgListEntry,
525                       &gVmbusConnection.ChannelMsgList);
526
527         spin_unlock_irqrestore(&gVmbusConnection.channelmsg_lock, flags);
528         DPRINT_DBG(VMBUS, "buffer %p, size %d msg cnt %d",
529                    kbuffer, size, msgcount);
530
531         DPRINT_DBG(VMBUS, "Sending GPADL Header - len %zd",
532                    msginfo->MessageSize - sizeof(*msginfo));
533
534         ret = VmbusPostMessage(gpadlmsg, msginfo->MessageSize -
535                                sizeof(*msginfo));
536         if (ret != 0) {
537                 DPRINT_ERR(VMBUS, "Unable to open channel - %d", ret);
538                 goto Cleanup;
539         }
540
541         if (msgcount > 1) {
542                 list_for_each(curr, &msginfo->SubMsgList) {
543
544                         /* FIXME: should this use list_entry() instead ? */
545                         submsginfo = (struct vmbus_channel_msginfo *)curr;
546                         gpadl_body =
547                              (struct vmbus_channel_gpadl_body *)submsginfo->Msg;
548
549                         gpadl_body->Header.MessageType =
550                                 ChannelMessageGpadlBody;
551                         gpadl_body->Gpadl = next_gpadl_handle;
552
553                         DPRINT_DBG(VMBUS, "Sending GPADL Body - len %zd",
554                                    submsginfo->MessageSize -
555                                    sizeof(*submsginfo));
556
557                         dump_gpadl_body(gpadl_body, submsginfo->MessageSize -
558                                       sizeof(*submsginfo));
559                         ret = VmbusPostMessage(gpadl_body,
560                                                submsginfo->MessageSize -
561                                                sizeof(*submsginfo));
562                         if (ret != 0)
563                                 goto Cleanup;
564
565                 }
566         }
567         osd_WaitEventWait(msginfo->WaitEvent);
568
569         /* At this point, we received the gpadl created msg */
570         DPRINT_DBG(VMBUS, "Received GPADL created "
571                    "(relid %d, status %d handle %x)",
572                    channel->OfferMsg.ChildRelId,
573                    msginfo->Response.GpadlCreated.CreationStatus,
574                    gpadlmsg->Gpadl);
575
576         *gpadl_handle = gpadlmsg->Gpadl;
577
578 Cleanup:
579         spin_lock_irqsave(&gVmbusConnection.channelmsg_lock, flags);
580         list_del(&msginfo->MsgListEntry);
581         spin_unlock_irqrestore(&gVmbusConnection.channelmsg_lock, flags);
582
583         kfree(msginfo->WaitEvent);
584         kfree(msginfo);
585         return ret;
586 }
587 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
588
589 /*
590  * vmbus_teardown_gpadl -Teardown the specified GPADL handle
591  */
592 int vmbus_teardown_gpadl(struct vmbus_channel *channel, u32 gpadl_handle)
593 {
594         struct vmbus_channel_gpadl_teardown *msg;
595         struct vmbus_channel_msginfo *info;
596         unsigned long flags;
597         int ret;
598
599         /* ASSERT(gpadl_handle != 0); */
600
601         info = kmalloc(sizeof(*info) +
602                        sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
603         if (!info)
604                 return -ENOMEM;
605
606         info->WaitEvent = osd_WaitEventCreate();
607         if (!info->WaitEvent) {
608                 kfree(info);
609                 return -ENOMEM;
610         }
611
612         msg = (struct vmbus_channel_gpadl_teardown *)info->Msg;
613
614         msg->Header.MessageType = ChannelMessageGpadlTeardown;
615         msg->ChildRelId = channel->OfferMsg.ChildRelId;
616         msg->Gpadl = gpadl_handle;
617
618         spin_lock_irqsave(&gVmbusConnection.channelmsg_lock, flags);
619         list_add_tail(&info->MsgListEntry,
620                       &gVmbusConnection.ChannelMsgList);
621         spin_unlock_irqrestore(&gVmbusConnection.channelmsg_lock, flags);
622
623         ret = VmbusPostMessage(msg,
624                                sizeof(struct vmbus_channel_gpadl_teardown));
625         if (ret != 0) {
626                 /* TODO: */
627                 /* something... */
628         }
629
630         osd_WaitEventWait(info->WaitEvent);
631
632         /* Received a torndown response */
633         spin_lock_irqsave(&gVmbusConnection.channelmsg_lock, flags);
634         list_del(&info->MsgListEntry);
635         spin_unlock_irqrestore(&gVmbusConnection.channelmsg_lock, flags);
636
637         kfree(info->WaitEvent);
638         kfree(info);
639         return ret;
640 }
641 EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl);
642
643 /*
644  * vmbus_close - Close the specified channel
645  */
646 void vmbus_close(struct vmbus_channel *channel)
647 {
648         struct vmbus_channel_close_channel *msg;
649         struct vmbus_channel_msginfo *info;
650         unsigned long flags;
651         int ret;
652
653         /* Stop callback and cancel the timer asap */
654         channel->OnChannelCallback = NULL;
655         del_timer_sync(&channel->poll_timer);
656
657         /* Send a closing message */
658         info = kmalloc(sizeof(*info) +
659                        sizeof(struct vmbus_channel_close_channel), GFP_KERNEL);
660         /* FIXME: can't do anything other than return here because the
661          *        function is void */
662         if (!info)
663                 return;
664
665         /* info->waitEvent = osd_WaitEventCreate(); */
666
667         msg = (struct vmbus_channel_close_channel *)info->Msg;
668         msg->Header.MessageType = ChannelMessageCloseChannel;
669         msg->ChildRelId = channel->OfferMsg.ChildRelId;
670
671         ret = VmbusPostMessage(msg, sizeof(struct vmbus_channel_close_channel));
672         if (ret != 0) {
673                 /* TODO: */
674                 /* something... */
675         }
676
677         /* Tear down the gpadl for the channel's ring buffer */
678         if (channel->RingBufferGpadlHandle)
679                 vmbus_teardown_gpadl(channel,
680                                           channel->RingBufferGpadlHandle);
681
682         /* TODO: Send a msg to release the childRelId */
683
684         /* Cleanup the ring buffers for this channel */
685         RingBufferCleanup(&channel->Outbound);
686         RingBufferCleanup(&channel->Inbound);
687
688         osd_PageFree(channel->RingBufferPages, channel->RingBufferPageCount);
689
690         kfree(info);
691
692         /*
693          * If we are closing the channel during an error path in
694          * opening the channel, don't free the channel since the
695          * caller will free the channel
696          */
697
698         if (channel->State == CHANNEL_OPEN_STATE) {
699                 spin_lock_irqsave(&gVmbusConnection.channel_lock, flags);
700                 list_del(&channel->ListEntry);
701                 spin_unlock_irqrestore(&gVmbusConnection.channel_lock, flags);
702
703                 free_channel(channel);
704         }
705 }
706
707 /**
708  * vmbus_sendpacket() - Send the specified buffer on the given channel
709  * @channel: Pointer to vmbus_channel structure.
710  * @buffer: Pointer to the buffer you want to receive the data into.
711  * @bufferlen: Maximum size of what the the buffer will hold
712  * @requestid: Identifier of the request
713  * @type: Type of packet that is being send e.g. negotiate, time
714  * packet etc.
715  *
716  * Sends data in @buffer directly to hyper-v via the vmbus
717  * This will send the data unparsed to hyper-v.
718  *
719  * Mainly used by Hyper-V drivers.
720  */
721 int vmbus_sendpacket(struct vmbus_channel *channel, const void *buffer,
722                            u32 bufferlen, u64 requestid,
723                            enum vmbus_packet_type type, u32 flags)
724 {
725         struct vmpacket_descriptor desc;
726         u32 packetlen = sizeof(struct vmpacket_descriptor) + bufferlen;
727         u32 packetlen_aligned = ALIGN_UP(packetlen, sizeof(u64));
728         struct scatterlist bufferlist[3];
729         u64 aligned_data = 0;
730         int ret;
731
732         DPRINT_DBG(VMBUS, "channel %p buffer %p len %d",
733                    channel, buffer, bufferlen);
734
735         dump_vmbus_channel(channel);
736
737         /* ASSERT((packetLenAligned - packetLen) < sizeof(u64)); */
738
739         /* Setup the descriptor */
740         desc.Type = type; /* VmbusPacketTypeDataInBand; */
741         desc.Flags = flags; /* VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED; */
742         /* in 8-bytes granularity */
743         desc.DataOffset8 = sizeof(struct vmpacket_descriptor) >> 3;
744         desc.Length8 = (u16)(packetlen_aligned >> 3);
745         desc.TransactionId = requestid;
746
747         sg_init_table(bufferlist, 3);
748         sg_set_buf(&bufferlist[0], &desc, sizeof(struct vmpacket_descriptor));
749         sg_set_buf(&bufferlist[1], buffer, bufferlen);
750         sg_set_buf(&bufferlist[2], &aligned_data,
751                    packetlen_aligned - packetlen);
752
753         ret = RingBufferWrite(&channel->Outbound, bufferlist, 3);
754
755         /* TODO: We should determine if this is optional */
756         if (ret == 0 && !GetRingBufferInterruptMask(&channel->Outbound))
757                 vmbus_setevent(channel);
758
759         return ret;
760 }
761 EXPORT_SYMBOL(vmbus_sendpacket);
762
763 /*
764  * vmbus_sendpacket_pagebuffer - Send a range of single-page buffer
765  * packets using a GPADL Direct packet type.
766  */
767 int vmbus_sendpacket_pagebuffer(struct vmbus_channel *channel,
768                                      struct hv_page_buffer pagebuffers[],
769                                      u32 pagecount, void *buffer, u32 bufferlen,
770                                      u64 requestid)
771 {
772         int ret;
773         int i;
774         struct vmbus_channel_packet_page_buffer desc;
775         u32 descsize;
776         u32 packetlen;
777         u32 packetlen_aligned;
778         struct scatterlist bufferlist[3];
779         u64 aligned_data = 0;
780
781         if (pagecount > MAX_PAGE_BUFFER_COUNT)
782                 return -EINVAL;
783
784         dump_vmbus_channel(channel);
785
786         /*
787          * Adjust the size down since vmbus_channel_packet_page_buffer is the
788          * largest size we support
789          */
790         descsize = sizeof(struct vmbus_channel_packet_page_buffer) -
791                           ((MAX_PAGE_BUFFER_COUNT - pagecount) *
792                           sizeof(struct hv_page_buffer));
793         packetlen = descsize + bufferlen;
794         packetlen_aligned = ALIGN_UP(packetlen, sizeof(u64));
795
796         /* ASSERT((packetLenAligned - packetLen) < sizeof(u64)); */
797
798         /* Setup the descriptor */
799         desc.type = VmbusPacketTypeDataUsingGpaDirect;
800         desc.flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
801         desc.dataoffset8 = descsize >> 3; /* in 8-bytes grandularity */
802         desc.length8 = (u16)(packetlen_aligned >> 3);
803         desc.transactionid = requestid;
804         desc.rangecount = pagecount;
805
806         for (i = 0; i < pagecount; i++) {
807                 desc.range[i].Length = pagebuffers[i].Length;
808                 desc.range[i].Offset = pagebuffers[i].Offset;
809                 desc.range[i].Pfn        = pagebuffers[i].Pfn;
810         }
811
812         sg_init_table(bufferlist, 3);
813         sg_set_buf(&bufferlist[0], &desc, descsize);
814         sg_set_buf(&bufferlist[1], buffer, bufferlen);
815         sg_set_buf(&bufferlist[2], &aligned_data,
816                 packetlen_aligned - packetlen);
817
818         ret = RingBufferWrite(&channel->Outbound, bufferlist, 3);
819
820         /* TODO: We should determine if this is optional */
821         if (ret == 0 && !GetRingBufferInterruptMask(&channel->Outbound))
822                 vmbus_setevent(channel);
823
824         return ret;
825 }
826
827 /*
828  * vmbus_sendpacket_multipagebuffer - Send a multi-page buffer packet
829  * using a GPADL Direct packet type.
830  */
831 int vmbus_sendpacket_multipagebuffer(struct vmbus_channel *channel,
832                                 struct hv_multipage_buffer *multi_pagebuffer,
833                                 void *buffer, u32 bufferlen, u64 requestid)
834 {
835         int ret;
836         struct vmbus_channel_packet_multipage_buffer desc;
837         u32 descsize;
838         u32 packetlen;
839         u32 packetlen_aligned;
840         struct scatterlist bufferlist[3];
841         u64 aligned_data = 0;
842         u32 pfncount = NUM_PAGES_SPANNED(multi_pagebuffer->Offset,
843                                          multi_pagebuffer->Length);
844
845         dump_vmbus_channel(channel);
846
847         DPRINT_DBG(VMBUS, "data buffer - offset %u len %u pfn count %u",
848                 multi_pagebuffer->Offset,
849                 multi_pagebuffer->Length, pfncount);
850
851         if ((pfncount < 0) || (pfncount > MAX_MULTIPAGE_BUFFER_COUNT))
852                 return -EINVAL;
853
854         /*
855          * Adjust the size down since vmbus_channel_packet_multipage_buffer is
856          * the largest size we support
857          */
858         descsize = sizeof(struct vmbus_channel_packet_multipage_buffer) -
859                           ((MAX_MULTIPAGE_BUFFER_COUNT - pfncount) *
860                           sizeof(u64));
861         packetlen = descsize + bufferlen;
862         packetlen_aligned = ALIGN_UP(packetlen, sizeof(u64));
863
864         /* ASSERT((packetLenAligned - packetLen) < sizeof(u64)); */
865
866         /* Setup the descriptor */
867         desc.type = VmbusPacketTypeDataUsingGpaDirect;
868         desc.flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
869         desc.dataoffset8 = descsize >> 3; /* in 8-bytes grandularity */
870         desc.length8 = (u16)(packetlen_aligned >> 3);
871         desc.transactionid = requestid;
872         desc.rangecount = 1;
873
874         desc.range.Length = multi_pagebuffer->Length;
875         desc.range.Offset = multi_pagebuffer->Offset;
876
877         memcpy(desc.range.PfnArray, multi_pagebuffer->PfnArray,
878                pfncount * sizeof(u64));
879
880         sg_init_table(bufferlist, 3);
881         sg_set_buf(&bufferlist[0], &desc, descsize);
882         sg_set_buf(&bufferlist[1], buffer, bufferlen);
883         sg_set_buf(&bufferlist[2], &aligned_data,
884                 packetlen_aligned - packetlen);
885
886         ret = RingBufferWrite(&channel->Outbound, bufferlist, 3);
887
888         /* TODO: We should determine if this is optional */
889         if (ret == 0 && !GetRingBufferInterruptMask(&channel->Outbound))
890                 vmbus_setevent(channel);
891
892         return ret;
893 }
894 EXPORT_SYMBOL_GPL(vmbus_sendpacket_multipagebuffer);
895
896 /**
897  * vmbus_recvpacket() - Retrieve the user packet on the specified channel
898  * @channel: Pointer to vmbus_channel structure.
899  * @buffer: Pointer to the buffer you want to receive the data into.
900  * @bufferlen: Maximum size of what the the buffer will hold
901  * @buffer_actual_len: The actual size of the data after it was received
902  * @requestid: Identifier of the request
903  *
904  * Receives directly from the hyper-v vmbus and puts the data it received
905  * into Buffer. This will receive the data unparsed from hyper-v.
906  *
907  * Mainly used by Hyper-V drivers.
908  */
909 int vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
910                         u32 bufferlen, u32 *buffer_actual_len, u64 *requestid)
911 {
912         struct vmpacket_descriptor desc;
913         u32 packetlen;
914         u32 userlen;
915         int ret;
916         unsigned long flags;
917
918         *buffer_actual_len = 0;
919         *requestid = 0;
920
921         spin_lock_irqsave(&channel->inbound_lock, flags);
922
923         ret = RingBufferPeek(&channel->Inbound, &desc,
924                              sizeof(struct vmpacket_descriptor));
925         if (ret != 0) {
926                 spin_unlock_irqrestore(&channel->inbound_lock, flags);
927
928                 /* DPRINT_DBG(VMBUS, "nothing to read!!"); */
929                 return 0;
930         }
931
932         /* VmbusChannelClearEvent(Channel); */
933
934         packetlen = desc.Length8 << 3;
935         userlen = packetlen - (desc.DataOffset8 << 3);
936         /* ASSERT(userLen > 0); */
937
938         DPRINT_DBG(VMBUS, "packet received on channel %p relid %d <type %d "
939                    "flag %d tid %llx pktlen %d datalen %d> ",
940                    channel, channel->OfferMsg.ChildRelId, desc.Type,
941                    desc.Flags, desc.TransactionId, packetlen, userlen);
942
943         *buffer_actual_len = userlen;
944
945         if (userlen > bufferlen) {
946                 spin_unlock_irqrestore(&channel->inbound_lock, flags);
947
948                 DPRINT_ERR(VMBUS, "buffer too small - got %d needs %d",
949                            bufferlen, userlen);
950                 return -1;
951         }
952
953         *requestid = desc.TransactionId;
954
955         /* Copy over the packet to the user buffer */
956         ret = RingBufferRead(&channel->Inbound, buffer, userlen,
957                              (desc.DataOffset8 << 3));
958
959         spin_unlock_irqrestore(&channel->inbound_lock, flags);
960
961         return 0;
962 }
963 EXPORT_SYMBOL(vmbus_recvpacket);
964
965 /*
966  * vmbus_recvpacket_raw - Retrieve the raw packet on the specified channel
967  */
968 int vmbus_recvpacket_raw(struct vmbus_channel *channel, void *buffer,
969                               u32 bufferlen, u32 *buffer_actual_len,
970                               u64 *requestid)
971 {
972         struct vmpacket_descriptor desc;
973         u32 packetlen;
974         u32 userlen;
975         int ret;
976         unsigned long flags;
977
978         *buffer_actual_len = 0;
979         *requestid = 0;
980
981         spin_lock_irqsave(&channel->inbound_lock, flags);
982
983         ret = RingBufferPeek(&channel->Inbound, &desc,
984                              sizeof(struct vmpacket_descriptor));
985         if (ret != 0) {
986                 spin_unlock_irqrestore(&channel->inbound_lock, flags);
987
988                 /* DPRINT_DBG(VMBUS, "nothing to read!!"); */
989                 return 0;
990         }
991
992         /* VmbusChannelClearEvent(Channel); */
993
994         packetlen = desc.Length8 << 3;
995         userlen = packetlen - (desc.DataOffset8 << 3);
996
997         DPRINT_DBG(VMBUS, "packet received on channel %p relid %d <type %d "
998                    "flag %d tid %llx pktlen %d datalen %d> ",
999                    channel, channel->OfferMsg.ChildRelId, desc.Type,
1000                    desc.Flags, desc.TransactionId, packetlen, userlen);
1001
1002         *buffer_actual_len = packetlen;
1003
1004         if (packetlen > bufferlen) {
1005                 spin_unlock_irqrestore(&channel->inbound_lock, flags);
1006
1007                 DPRINT_ERR(VMBUS, "buffer too small - needed %d bytes but "
1008                            "got space for only %d bytes", packetlen, bufferlen);
1009                 return -2;
1010         }
1011
1012         *requestid = desc.TransactionId;
1013
1014         /* Copy over the entire packet to the user buffer */
1015         ret = RingBufferRead(&channel->Inbound, buffer, packetlen, 0);
1016
1017         spin_unlock_irqrestore(&channel->inbound_lock, flags);
1018         return 0;
1019 }
1020 EXPORT_SYMBOL_GPL(vmbus_recvpacket_raw);
1021
1022 /*
1023  * vmbus_onchannel_event - Channel event callback
1024  */
1025 void vmbus_onchannel_event(struct vmbus_channel *channel)
1026 {
1027         dump_vmbus_channel(channel);
1028         /* ASSERT(Channel->OnChannelCallback); */
1029
1030         channel->OnChannelCallback(channel->ChannelCallbackContext);
1031
1032         mod_timer(&channel->poll_timer, jiffies + usecs_to_jiffies(100));
1033 }
1034
1035 /*
1036  * vmbus_ontimer - Timer event callback
1037  */
1038 void vmbus_ontimer(unsigned long data)
1039 {
1040         struct vmbus_channel *channel = (struct vmbus_channel *)data;
1041
1042         if (channel->OnChannelCallback)
1043                 channel->OnChannelCallback(channel->ChannelCallbackContext);
1044 }
1045
1046 /*
1047  * dump_vmbus_channel- Dump vmbus channel info to the console
1048  */
1049 static void dump_vmbus_channel(struct vmbus_channel *channel)
1050 {
1051         DPRINT_DBG(VMBUS, "Channel (%d)", channel->OfferMsg.ChildRelId);
1052         DumpRingInfo(&channel->Outbound, "Outbound ");
1053         DumpRingInfo(&channel->Inbound, "Inbound ");
1054 }