]> git.karo-electronics.de Git - linux-beck.git/blob - drivers/staging/hv/netvsc.c
8b73144e7c12213edacee10f8b81ce9b84530bbf
[linux-beck.git] / drivers / staging / hv / netvsc.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/delay.h>
24 #include <linux/io.h>
25 #include <linux/slab.h>
26 #include "osd.h"
27 #include "logging.h"
28 #include "netvsc.h"
29 #include "rndis_filter.h"
30 #include "channel.h"
31
32
33 /* Globals */
34 static const char *gDriverName = "netvsc";
35
36 /* {F8615163-DF3E-46c5-913F-F2D2F965ED0E} */
37 static const struct hv_guid gNetVscDeviceType = {
38         .data = {
39                 0x63, 0x51, 0x61, 0xF8, 0x3E, 0xDF, 0xc5, 0x46,
40                 0x91, 0x3F, 0xF2, 0xD2, 0xF9, 0x65, 0xED, 0x0E
41         }
42 };
43
44 static int NetVscOnDeviceAdd(struct hv_device *Device, void *AdditionalInfo);
45
46 static int NetVscOnDeviceRemove(struct hv_device *Device);
47
48 static void NetVscOnCleanup(struct hv_driver *Driver);
49
50 static void NetVscOnChannelCallback(void *context);
51
52 static int NetVscInitializeSendBufferWithNetVsp(struct hv_device *Device);
53
54 static int NetVscInitializeReceiveBufferWithNetVsp(struct hv_device *Device);
55
56 static int NetVscDestroySendBuffer(struct netvsc_device *NetDevice);
57
58 static int NetVscDestroyReceiveBuffer(struct netvsc_device *NetDevice);
59
60 static int NetVscConnectToVsp(struct hv_device *Device);
61
62 static void NetVscOnSendCompletion(struct hv_device *Device,
63                                    struct vmpacket_descriptor *Packet);
64
65 static int NetVscOnSend(struct hv_device *Device,
66                         struct hv_netvsc_packet *Packet);
67
68 static void NetVscOnReceive(struct hv_device *Device,
69                             struct vmpacket_descriptor *Packet);
70
71 static void NetVscOnReceiveCompletion(void *Context);
72
73 static void NetVscSendReceiveCompletion(struct hv_device *Device,
74                                         u64 TransactionId);
75
76
77 static struct netvsc_device *AllocNetDevice(struct hv_device *Device)
78 {
79         struct netvsc_device *netDevice;
80
81         netDevice = kzalloc(sizeof(struct netvsc_device), GFP_KERNEL);
82         if (!netDevice)
83                 return NULL;
84
85         /* Set to 2 to allow both inbound and outbound traffic */
86         atomic_cmpxchg(&netDevice->RefCount, 0, 2);
87
88         netDevice->Device = Device;
89         Device->Extension = netDevice;
90
91         return netDevice;
92 }
93
94 static void FreeNetDevice(struct netvsc_device *Device)
95 {
96         WARN_ON(atomic_read(&Device->RefCount) == 0);
97         Device->Device->Extension = NULL;
98         kfree(Device);
99 }
100
101
102 /* Get the net device object iff exists and its refcount > 1 */
103 static struct netvsc_device *GetOutboundNetDevice(struct hv_device *Device)
104 {
105         struct netvsc_device *netDevice;
106
107         netDevice = Device->Extension;
108         if (netDevice && atomic_read(&netDevice->RefCount) > 1)
109                 atomic_inc(&netDevice->RefCount);
110         else
111                 netDevice = NULL;
112
113         return netDevice;
114 }
115
116 /* Get the net device object iff exists and its refcount > 0 */
117 static struct netvsc_device *GetInboundNetDevice(struct hv_device *Device)
118 {
119         struct netvsc_device *netDevice;
120
121         netDevice = Device->Extension;
122         if (netDevice && atomic_read(&netDevice->RefCount))
123                 atomic_inc(&netDevice->RefCount);
124         else
125                 netDevice = NULL;
126
127         return netDevice;
128 }
129
130 static void PutNetDevice(struct hv_device *Device)
131 {
132         struct netvsc_device *netDevice;
133
134         netDevice = Device->Extension;
135         /* ASSERT(netDevice); */
136
137         atomic_dec(&netDevice->RefCount);
138 }
139
140 static struct netvsc_device *ReleaseOutboundNetDevice(struct hv_device *Device)
141 {
142         struct netvsc_device *netDevice;
143
144         netDevice = Device->Extension;
145         if (netDevice == NULL)
146                 return NULL;
147
148         /* Busy wait until the ref drop to 2, then set it to 1 */
149         while (atomic_cmpxchg(&netDevice->RefCount, 2, 1) != 2)
150                 udelay(100);
151
152         return netDevice;
153 }
154
155 static struct netvsc_device *ReleaseInboundNetDevice(struct hv_device *Device)
156 {
157         struct netvsc_device *netDevice;
158
159         netDevice = Device->Extension;
160         if (netDevice == NULL)
161                 return NULL;
162
163         /* Busy wait until the ref drop to 1, then set it to 0 */
164         while (atomic_cmpxchg(&netDevice->RefCount, 1, 0) != 1)
165                 udelay(100);
166
167         Device->Extension = NULL;
168         return netDevice;
169 }
170
171 /*
172  * NetVscInitialize - Main entry point
173  */
174 int NetVscInitialize(struct hv_driver *drv)
175 {
176         struct netvsc_driver *driver = (struct netvsc_driver *)drv;
177
178         DPRINT_DBG(NETVSC, "sizeof(struct hv_netvsc_packet)=%zd, "
179                    "sizeof(struct nvsp_message)=%zd, "
180                    "sizeof(struct vmtransfer_page_packet_header)=%zd",
181                    sizeof(struct hv_netvsc_packet),
182                    sizeof(struct nvsp_message),
183                    sizeof(struct vmtransfer_page_packet_header));
184
185         /* Make sure we are at least 2 pages since 1 page is used for control */
186         /* ASSERT(driver->RingBufferSize >= (PAGE_SIZE << 1)); */
187
188         drv->name = gDriverName;
189         memcpy(&drv->deviceType, &gNetVscDeviceType, sizeof(struct hv_guid));
190
191         /* Make sure it is set by the caller */
192         /* FIXME: These probably should still be tested in some way */
193         /* ASSERT(driver->OnReceiveCallback); */
194         /* ASSERT(driver->OnLinkStatusChanged); */
195
196         /* Setup the dispatch table */
197         driver->Base.OnDeviceAdd        = NetVscOnDeviceAdd;
198         driver->Base.OnDeviceRemove     = NetVscOnDeviceRemove;
199         driver->Base.OnCleanup          = NetVscOnCleanup;
200
201         driver->OnSend                  = NetVscOnSend;
202
203         RndisFilterInit(driver);
204         return 0;
205 }
206
207 static int NetVscInitializeReceiveBufferWithNetVsp(struct hv_device *Device)
208 {
209         int ret = 0;
210         struct netvsc_device *netDevice;
211         struct nvsp_message *initPacket;
212
213         netDevice = GetOutboundNetDevice(Device);
214         if (!netDevice) {
215                 DPRINT_ERR(NETVSC, "unable to get net device..."
216                            "device being destroyed?");
217                 return -1;
218         }
219         /* ASSERT(netDevice->ReceiveBufferSize > 0); */
220         /* page-size grandularity */
221         /* ASSERT((netDevice->ReceiveBufferSize & (PAGE_SIZE - 1)) == 0); */
222
223         netDevice->ReceiveBuffer =
224                 osd_PageAlloc(netDevice->ReceiveBufferSize >> PAGE_SHIFT);
225         if (!netDevice->ReceiveBuffer) {
226                 DPRINT_ERR(NETVSC,
227                            "unable to allocate receive buffer of size %d",
228                            netDevice->ReceiveBufferSize);
229                 ret = -1;
230                 goto Cleanup;
231         }
232         /* page-aligned buffer */
233         /* ASSERT(((unsigned long)netDevice->ReceiveBuffer & (PAGE_SIZE - 1)) == */
234         /*      0); */
235
236         DPRINT_INFO(NETVSC, "Establishing receive buffer's GPADL...");
237
238         /*
239          * Establish the gpadl handle for this buffer on this
240          * channel.  Note: This call uses the vmbus connection rather
241          * than the channel to establish the gpadl handle.
242          */
243         ret = vmbus_establish_gpadl(Device->channel, netDevice->ReceiveBuffer,
244                                     netDevice->ReceiveBufferSize,
245                                     &netDevice->ReceiveBufferGpadlHandle);
246         if (ret != 0) {
247                 DPRINT_ERR(NETVSC,
248                            "unable to establish receive buffer's gpadl");
249                 goto Cleanup;
250         }
251
252         /* osd_WaitEventWait(ext->ChannelInitEvent); */
253
254         /* Notify the NetVsp of the gpadl handle */
255         DPRINT_INFO(NETVSC, "Sending NvspMessage1TypeSendReceiveBuffer...");
256
257         initPacket = &netDevice->ChannelInitPacket;
258
259         memset(initPacket, 0, sizeof(struct nvsp_message));
260
261         initPacket->Header.MessageType = NvspMessage1TypeSendReceiveBuffer;
262         initPacket->Messages.Version1Messages.SendReceiveBuffer.GpadlHandle = netDevice->ReceiveBufferGpadlHandle;
263         initPacket->Messages.Version1Messages.SendReceiveBuffer.Id = NETVSC_RECEIVE_BUFFER_ID;
264
265         /* Send the gpadl notification request */
266         ret = vmbus_sendpacket(Device->channel, initPacket,
267                                sizeof(struct nvsp_message),
268                                (unsigned long)initPacket,
269                                VmbusPacketTypeDataInBand,
270                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
271         if (ret != 0) {
272                 DPRINT_ERR(NETVSC,
273                            "unable to send receive buffer's gpadl to netvsp");
274                 goto Cleanup;
275         }
276
277         osd_WaitEventWait(netDevice->ChannelInitEvent);
278
279         /* Check the response */
280         if (initPacket->Messages.Version1Messages.SendReceiveBufferComplete.Status != NvspStatusSuccess) {
281                 DPRINT_ERR(NETVSC, "Unable to complete receive buffer "
282                            "initialzation with NetVsp - status %d",
283                            initPacket->Messages.Version1Messages.SendReceiveBufferComplete.Status);
284                 ret = -1;
285                 goto Cleanup;
286         }
287
288         /* Parse the response */
289         /* ASSERT(netDevice->ReceiveSectionCount == 0); */
290         /* ASSERT(netDevice->ReceiveSections == NULL); */
291
292         netDevice->ReceiveSectionCount = initPacket->Messages.Version1Messages.SendReceiveBufferComplete.NumSections;
293
294         netDevice->ReceiveSections = kmalloc(netDevice->ReceiveSectionCount * sizeof(struct nvsp_1_receive_buffer_section), GFP_KERNEL);
295         if (netDevice->ReceiveSections == NULL) {
296                 ret = -1;
297                 goto Cleanup;
298         }
299
300         memcpy(netDevice->ReceiveSections,
301                 initPacket->Messages.Version1Messages.SendReceiveBufferComplete.Sections,
302                 netDevice->ReceiveSectionCount * sizeof(struct nvsp_1_receive_buffer_section));
303
304         DPRINT_INFO(NETVSC, "Receive sections info (count %d, offset %d, "
305                     "endoffset %d, suballoc size %d, num suballocs %d)",
306                     netDevice->ReceiveSectionCount,
307                     netDevice->ReceiveSections[0].Offset,
308                     netDevice->ReceiveSections[0].EndOffset,
309                     netDevice->ReceiveSections[0].SubAllocationSize,
310                     netDevice->ReceiveSections[0].NumSubAllocations);
311
312         /*
313          * For 1st release, there should only be 1 section that represents the
314          * entire receive buffer
315          */
316         if (netDevice->ReceiveSectionCount != 1 ||
317             netDevice->ReceiveSections->Offset != 0) {
318                 ret = -1;
319                 goto Cleanup;
320         }
321
322         goto Exit;
323
324 Cleanup:
325         NetVscDestroyReceiveBuffer(netDevice);
326
327 Exit:
328         PutNetDevice(Device);
329         return ret;
330 }
331
332 static int NetVscInitializeSendBufferWithNetVsp(struct hv_device *Device)
333 {
334         int ret = 0;
335         struct netvsc_device *netDevice;
336         struct nvsp_message *initPacket;
337
338         netDevice = GetOutboundNetDevice(Device);
339         if (!netDevice) {
340                 DPRINT_ERR(NETVSC, "unable to get net device..."
341                            "device being destroyed?");
342                 return -1;
343         }
344         if (netDevice->SendBufferSize <= 0) {
345                 ret = -EINVAL;
346                 goto Cleanup;
347         }
348
349         /* page-size grandularity */
350         /* ASSERT((netDevice->SendBufferSize & (PAGE_SIZE - 1)) == 0); */
351
352         netDevice->SendBuffer =
353                 osd_PageAlloc(netDevice->SendBufferSize >> PAGE_SHIFT);
354         if (!netDevice->SendBuffer) {
355                 DPRINT_ERR(NETVSC, "unable to allocate send buffer of size %d",
356                            netDevice->SendBufferSize);
357                 ret = -1;
358                 goto Cleanup;
359         }
360         /* page-aligned buffer */
361         /* ASSERT(((unsigned long)netDevice->SendBuffer & (PAGE_SIZE - 1)) == 0); */
362
363         DPRINT_INFO(NETVSC, "Establishing send buffer's GPADL...");
364
365         /*
366          * Establish the gpadl handle for this buffer on this
367          * channel.  Note: This call uses the vmbus connection rather
368          * than the channel to establish the gpadl handle.
369          */
370         ret = vmbus_establish_gpadl(Device->channel, netDevice->SendBuffer,
371                                     netDevice->SendBufferSize,
372                                     &netDevice->SendBufferGpadlHandle);
373         if (ret != 0) {
374                 DPRINT_ERR(NETVSC, "unable to establish send buffer's gpadl");
375                 goto Cleanup;
376         }
377
378         /* osd_WaitEventWait(ext->ChannelInitEvent); */
379
380         /* Notify the NetVsp of the gpadl handle */
381         DPRINT_INFO(NETVSC, "Sending NvspMessage1TypeSendSendBuffer...");
382
383         initPacket = &netDevice->ChannelInitPacket;
384
385         memset(initPacket, 0, sizeof(struct nvsp_message));
386
387         initPacket->Header.MessageType = NvspMessage1TypeSendSendBuffer;
388         initPacket->Messages.Version1Messages.SendReceiveBuffer.GpadlHandle = netDevice->SendBufferGpadlHandle;
389         initPacket->Messages.Version1Messages.SendReceiveBuffer.Id = NETVSC_SEND_BUFFER_ID;
390
391         /* Send the gpadl notification request */
392         ret = vmbus_sendpacket(Device->channel, initPacket,
393                                sizeof(struct nvsp_message),
394                                (unsigned long)initPacket,
395                                VmbusPacketTypeDataInBand,
396                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
397         if (ret != 0) {
398                 DPRINT_ERR(NETVSC,
399                            "unable to send receive buffer's gpadl to netvsp");
400                 goto Cleanup;
401         }
402
403         osd_WaitEventWait(netDevice->ChannelInitEvent);
404
405         /* Check the response */
406         if (initPacket->Messages.Version1Messages.SendSendBufferComplete.Status != NvspStatusSuccess) {
407                 DPRINT_ERR(NETVSC, "Unable to complete send buffer "
408                            "initialzation with NetVsp - status %d",
409                            initPacket->Messages.Version1Messages.SendSendBufferComplete.Status);
410                 ret = -1;
411                 goto Cleanup;
412         }
413
414         netDevice->SendSectionSize = initPacket->Messages.Version1Messages.SendSendBufferComplete.SectionSize;
415
416         goto Exit;
417
418 Cleanup:
419         NetVscDestroySendBuffer(netDevice);
420
421 Exit:
422         PutNetDevice(Device);
423         return ret;
424 }
425
426 static int NetVscDestroyReceiveBuffer(struct netvsc_device *NetDevice)
427 {
428         struct nvsp_message *revokePacket;
429         int ret = 0;
430
431         /*
432          * If we got a section count, it means we received a
433          * SendReceiveBufferComplete msg (ie sent
434          * NvspMessage1TypeSendReceiveBuffer msg) therefore, we need
435          * to send a revoke msg here
436          */
437         if (NetDevice->ReceiveSectionCount) {
438                 DPRINT_INFO(NETVSC,
439                             "Sending NvspMessage1TypeRevokeReceiveBuffer...");
440
441                 /* Send the revoke receive buffer */
442                 revokePacket = &NetDevice->RevokePacket;
443                 memset(revokePacket, 0, sizeof(struct nvsp_message));
444
445                 revokePacket->Header.MessageType = NvspMessage1TypeRevokeReceiveBuffer;
446                 revokePacket->Messages.Version1Messages.RevokeReceiveBuffer.Id = NETVSC_RECEIVE_BUFFER_ID;
447
448                 ret = vmbus_sendpacket(NetDevice->Device->channel, revokePacket,
449                                        sizeof(struct nvsp_message),
450                                        (unsigned long)revokePacket,
451                                        VmbusPacketTypeDataInBand, 0);
452                 /*
453                  * If we failed here, we might as well return and
454                  * have a leak rather than continue and a bugchk
455                  */
456                 if (ret != 0) {
457                         DPRINT_ERR(NETVSC, "unable to send revoke receive "
458                                    "buffer to netvsp");
459                         return -1;
460                 }
461         }
462
463         /* Teardown the gpadl on the vsp end */
464         if (NetDevice->ReceiveBufferGpadlHandle) {
465                 DPRINT_INFO(NETVSC, "Tearing down receive buffer's GPADL...");
466
467                 ret = vmbus_teardown_gpadl(NetDevice->Device->channel,
468                                            NetDevice->ReceiveBufferGpadlHandle);
469
470                 /* If we failed here, we might as well return and have a leak rather than continue and a bugchk */
471                 if (ret != 0) {
472                         DPRINT_ERR(NETVSC,
473                                    "unable to teardown receive buffer's gpadl");
474                         return -1;
475                 }
476                 NetDevice->ReceiveBufferGpadlHandle = 0;
477         }
478
479         if (NetDevice->ReceiveBuffer) {
480                 DPRINT_INFO(NETVSC, "Freeing up receive buffer...");
481
482                 /* Free up the receive buffer */
483                 osd_PageFree(NetDevice->ReceiveBuffer,
484                              NetDevice->ReceiveBufferSize >> PAGE_SHIFT);
485                 NetDevice->ReceiveBuffer = NULL;
486         }
487
488         if (NetDevice->ReceiveSections) {
489                 NetDevice->ReceiveSectionCount = 0;
490                 kfree(NetDevice->ReceiveSections);
491                 NetDevice->ReceiveSections = NULL;
492         }
493
494         return ret;
495 }
496
497 static int NetVscDestroySendBuffer(struct netvsc_device *NetDevice)
498 {
499         struct nvsp_message *revokePacket;
500         int ret = 0;
501
502         /*
503          * If we got a section count, it means we received a
504          *  SendReceiveBufferComplete msg (ie sent
505          *  NvspMessage1TypeSendReceiveBuffer msg) therefore, we need
506          *  to send a revoke msg here
507          */
508         if (NetDevice->SendSectionSize) {
509                 DPRINT_INFO(NETVSC,
510                             "Sending NvspMessage1TypeRevokeSendBuffer...");
511
512                 /* Send the revoke send buffer */
513                 revokePacket = &NetDevice->RevokePacket;
514                 memset(revokePacket, 0, sizeof(struct nvsp_message));
515
516                 revokePacket->Header.MessageType = NvspMessage1TypeRevokeSendBuffer;
517                 revokePacket->Messages.Version1Messages.RevokeSendBuffer.Id = NETVSC_SEND_BUFFER_ID;
518
519                 ret = vmbus_sendpacket(NetDevice->Device->channel, revokePacket,
520                                        sizeof(struct nvsp_message),
521                                        (unsigned long)revokePacket,
522                                        VmbusPacketTypeDataInBand, 0);
523                 /*
524                  * If we failed here, we might as well return and have a leak
525                  * rather than continue and a bugchk
526                  */
527                 if (ret != 0) {
528                         DPRINT_ERR(NETVSC, "unable to send revoke send buffer "
529                                    "to netvsp");
530                         return -1;
531                 }
532         }
533
534         /* Teardown the gpadl on the vsp end */
535         if (NetDevice->SendBufferGpadlHandle) {
536                 DPRINT_INFO(NETVSC, "Tearing down send buffer's GPADL...");
537                 ret = vmbus_teardown_gpadl(NetDevice->Device->channel,
538                                            NetDevice->SendBufferGpadlHandle);
539
540                 /*
541                  * If we failed here, we might as well return and have a leak
542                  * rather than continue and a bugchk
543                  */
544                 if (ret != 0) {
545                         DPRINT_ERR(NETVSC, "unable to teardown send buffer's "
546                                    "gpadl");
547                         return -1;
548                 }
549                 NetDevice->SendBufferGpadlHandle = 0;
550         }
551
552         if (NetDevice->SendBuffer) {
553                 DPRINT_INFO(NETVSC, "Freeing up send buffer...");
554
555                 /* Free up the receive buffer */
556                 osd_PageFree(NetDevice->SendBuffer,
557                              NetDevice->SendBufferSize >> PAGE_SHIFT);
558                 NetDevice->SendBuffer = NULL;
559         }
560
561         return ret;
562 }
563
564
565 static int NetVscConnectToVsp(struct hv_device *Device)
566 {
567         int ret;
568         struct netvsc_device *netDevice;
569         struct nvsp_message *initPacket;
570         int ndisVersion;
571
572         netDevice = GetOutboundNetDevice(Device);
573         if (!netDevice) {
574                 DPRINT_ERR(NETVSC, "unable to get net device..."
575                            "device being destroyed?");
576                 return -1;
577         }
578
579         initPacket = &netDevice->ChannelInitPacket;
580
581         memset(initPacket, 0, sizeof(struct nvsp_message));
582         initPacket->Header.MessageType = NvspMessageTypeInit;
583         initPacket->Messages.InitMessages.Init.MinProtocolVersion = NVSP_MIN_PROTOCOL_VERSION;
584         initPacket->Messages.InitMessages.Init.MaxProtocolVersion = NVSP_MAX_PROTOCOL_VERSION;
585
586         DPRINT_INFO(NETVSC, "Sending NvspMessageTypeInit...");
587
588         /* Send the init request */
589         ret = vmbus_sendpacket(Device->channel, initPacket,
590                                sizeof(struct nvsp_message),
591                                (unsigned long)initPacket,
592                                VmbusPacketTypeDataInBand,
593                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
594
595         if (ret != 0) {
596                 DPRINT_ERR(NETVSC, "unable to send NvspMessageTypeInit");
597                 goto Cleanup;
598         }
599
600         osd_WaitEventWait(netDevice->ChannelInitEvent);
601
602         /* Now, check the response */
603         /* ASSERT(initPacket->Messages.InitMessages.InitComplete.MaximumMdlChainLength <= MAX_MULTIPAGE_BUFFER_COUNT); */
604         DPRINT_INFO(NETVSC, "NvspMessageTypeInit status(%d) max mdl chain (%d)",
605                 initPacket->Messages.InitMessages.InitComplete.Status,
606                 initPacket->Messages.InitMessages.InitComplete.MaximumMdlChainLength);
607
608         if (initPacket->Messages.InitMessages.InitComplete.Status !=
609             NvspStatusSuccess) {
610                 DPRINT_ERR(NETVSC,
611                         "unable to initialize with netvsp (status 0x%x)",
612                         initPacket->Messages.InitMessages.InitComplete.Status);
613                 ret = -1;
614                 goto Cleanup;
615         }
616
617         if (initPacket->Messages.InitMessages.InitComplete.NegotiatedProtocolVersion != NVSP_PROTOCOL_VERSION_1) {
618                 DPRINT_ERR(NETVSC, "unable to initialize with netvsp "
619                            "(version expected 1 got %d)",
620                            initPacket->Messages.InitMessages.InitComplete.NegotiatedProtocolVersion);
621                 ret = -1;
622                 goto Cleanup;
623         }
624         DPRINT_INFO(NETVSC, "Sending NvspMessage1TypeSendNdisVersion...");
625
626         /* Send the ndis version */
627         memset(initPacket, 0, sizeof(struct nvsp_message));
628
629         ndisVersion = 0x00050000;
630
631         initPacket->Header.MessageType = NvspMessage1TypeSendNdisVersion;
632         initPacket->Messages.Version1Messages.SendNdisVersion.NdisMajorVersion =
633                                 (ndisVersion & 0xFFFF0000) >> 16;
634         initPacket->Messages.Version1Messages.SendNdisVersion.NdisMinorVersion =
635                                 ndisVersion & 0xFFFF;
636
637         /* Send the init request */
638         ret = vmbus_sendpacket(Device->channel, initPacket,
639                                sizeof(struct nvsp_message),
640                                (unsigned long)initPacket,
641                                VmbusPacketTypeDataInBand, 0);
642         if (ret != 0) {
643                 DPRINT_ERR(NETVSC,
644                            "unable to send NvspMessage1TypeSendNdisVersion");
645                 ret = -1;
646                 goto Cleanup;
647         }
648         /*
649          * BUGBUG - We have to wait for the above msg since the
650          * netvsp uses KMCL which acknowledges packet (completion
651          * packet) since our Vmbus always set the
652          * VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED flag
653          */
654          /* osd_WaitEventWait(NetVscChannel->ChannelInitEvent); */
655
656         /* Post the big receive buffer to NetVSP */
657         ret = NetVscInitializeReceiveBufferWithNetVsp(Device);
658         if (ret == 0)
659                 ret = NetVscInitializeSendBufferWithNetVsp(Device);
660
661 Cleanup:
662         PutNetDevice(Device);
663         return ret;
664 }
665
666 static void NetVscDisconnectFromVsp(struct netvsc_device *NetDevice)
667 {
668         NetVscDestroyReceiveBuffer(NetDevice);
669         NetVscDestroySendBuffer(NetDevice);
670 }
671
672 /*
673  * NetVscOnDeviceAdd - Callback when the device belonging to this driver is added
674  */
675 static int NetVscOnDeviceAdd(struct hv_device *Device, void *AdditionalInfo)
676 {
677         int ret = 0;
678         int i;
679         struct netvsc_device *netDevice;
680         struct hv_netvsc_packet *packet, *pos;
681         struct netvsc_driver *netDriver =
682                                 (struct netvsc_driver *)Device->Driver;
683
684         netDevice = AllocNetDevice(Device);
685         if (!netDevice) {
686                 ret = -1;
687                 goto Cleanup;
688         }
689
690         DPRINT_DBG(NETVSC, "netvsc channel object allocated - %p", netDevice);
691
692         /* Initialize the NetVSC channel extension */
693         netDevice->ReceiveBufferSize = NETVSC_RECEIVE_BUFFER_SIZE;
694         spin_lock_init(&netDevice->receive_packet_list_lock);
695
696         netDevice->SendBufferSize = NETVSC_SEND_BUFFER_SIZE;
697
698         INIT_LIST_HEAD(&netDevice->ReceivePacketList);
699
700         for (i = 0; i < NETVSC_RECEIVE_PACKETLIST_COUNT; i++) {
701                 packet = kzalloc(sizeof(struct hv_netvsc_packet) +
702                                  (NETVSC_RECEIVE_SG_COUNT *
703                                   sizeof(struct hv_page_buffer)), GFP_KERNEL);
704                 if (!packet) {
705                         DPRINT_DBG(NETVSC, "unable to allocate netvsc pkts "
706                                    "for receive pool (wanted %d got %d)",
707                                    NETVSC_RECEIVE_PACKETLIST_COUNT, i);
708                         break;
709                 }
710                 list_add_tail(&packet->ListEntry,
711                               &netDevice->ReceivePacketList);
712         }
713         netDevice->ChannelInitEvent = osd_WaitEventCreate();
714         if (!netDevice->ChannelInitEvent) {
715                 ret = -ENOMEM;
716                 goto Cleanup;
717         }
718
719         /* Open the channel */
720         ret = Device->Driver->VmbusChannelInterface.Open(Device,
721                                                 netDriver->RingBufferSize,
722                                                 netDriver->RingBufferSize,
723                                                 NULL, 0,
724                                                 NetVscOnChannelCallback,
725                                                 Device);
726
727         if (ret != 0) {
728                 DPRINT_ERR(NETVSC, "unable to open channel: %d", ret);
729                 ret = -1;
730                 goto Cleanup;
731         }
732
733         /* Channel is opened */
734         DPRINT_INFO(NETVSC, "*** NetVSC channel opened successfully! ***");
735
736         /* Connect with the NetVsp */
737         ret = NetVscConnectToVsp(Device);
738         if (ret != 0) {
739                 DPRINT_ERR(NETVSC, "unable to connect to NetVSP - %d", ret);
740                 ret = -1;
741                 goto close;
742         }
743
744         DPRINT_INFO(NETVSC, "*** NetVSC channel handshake result - %d ***",
745                     ret);
746
747         return ret;
748
749 close:
750         /* Now, we can close the channel safely */
751         vmbus_close(Device->channel);
752
753 Cleanup:
754
755         if (netDevice) {
756                 kfree(netDevice->ChannelInitEvent);
757
758                 list_for_each_entry_safe(packet, pos,
759                                          &netDevice->ReceivePacketList,
760                                          ListEntry) {
761                         list_del(&packet->ListEntry);
762                         kfree(packet);
763                 }
764
765                 ReleaseOutboundNetDevice(Device);
766                 ReleaseInboundNetDevice(Device);
767
768                 FreeNetDevice(netDevice);
769         }
770
771         return ret;
772 }
773
774 /*
775  * NetVscOnDeviceRemove - Callback when the root bus device is removed
776  */
777 static int NetVscOnDeviceRemove(struct hv_device *Device)
778 {
779         struct netvsc_device *netDevice;
780         struct hv_netvsc_packet *netvscPacket, *pos;
781
782         DPRINT_INFO(NETVSC, "Disabling outbound traffic on net device (%p)...",
783                     Device->Extension);
784
785         /* Stop outbound traffic ie sends and receives completions */
786         netDevice = ReleaseOutboundNetDevice(Device);
787         if (!netDevice) {
788                 DPRINT_ERR(NETVSC, "No net device present!!");
789                 return -1;
790         }
791
792         /* Wait for all send completions */
793         while (atomic_read(&netDevice->NumOutstandingSends)) {
794                 DPRINT_INFO(NETVSC, "waiting for %d requests to complete...",
795                             atomic_read(&netDevice->NumOutstandingSends));
796                 udelay(100);
797         }
798
799         DPRINT_INFO(NETVSC, "Disconnecting from netvsp...");
800
801         NetVscDisconnectFromVsp(netDevice);
802
803         DPRINT_INFO(NETVSC, "Disabling inbound traffic on net device (%p)...",
804                     Device->Extension);
805
806         /* Stop inbound traffic ie receives and sends completions */
807         netDevice = ReleaseInboundNetDevice(Device);
808
809         /* At this point, no one should be accessing netDevice except in here */
810         DPRINT_INFO(NETVSC, "net device (%p) safe to remove", netDevice);
811
812         /* Now, we can close the channel safely */
813         vmbus_close(Device->channel);
814
815         /* Release all resources */
816         list_for_each_entry_safe(netvscPacket, pos,
817                                  &netDevice->ReceivePacketList, ListEntry) {
818                 list_del(&netvscPacket->ListEntry);
819                 kfree(netvscPacket);
820         }
821
822         kfree(netDevice->ChannelInitEvent);
823         FreeNetDevice(netDevice);
824         return 0;
825 }
826
827 /*
828  * NetVscOnCleanup - Perform any cleanup when the driver is removed
829  */
830 static void NetVscOnCleanup(struct hv_driver *drv)
831 {
832 }
833
834 static void NetVscOnSendCompletion(struct hv_device *Device,
835                                    struct vmpacket_descriptor *Packet)
836 {
837         struct netvsc_device *netDevice;
838         struct nvsp_message *nvspPacket;
839         struct hv_netvsc_packet *nvscPacket;
840
841         netDevice = GetInboundNetDevice(Device);
842         if (!netDevice) {
843                 DPRINT_ERR(NETVSC, "unable to get net device..."
844                            "device being destroyed?");
845                 return;
846         }
847
848         nvspPacket = (struct nvsp_message *)((unsigned long)Packet + (Packet->DataOffset8 << 3));
849
850         DPRINT_DBG(NETVSC, "send completion packet - type %d",
851                    nvspPacket->Header.MessageType);
852
853         if ((nvspPacket->Header.MessageType == NvspMessageTypeInitComplete) ||
854             (nvspPacket->Header.MessageType ==
855              NvspMessage1TypeSendReceiveBufferComplete) ||
856             (nvspPacket->Header.MessageType ==
857              NvspMessage1TypeSendSendBufferComplete)) {
858                 /* Copy the response back */
859                 memcpy(&netDevice->ChannelInitPacket, nvspPacket,
860                        sizeof(struct nvsp_message));
861                 osd_WaitEventSet(netDevice->ChannelInitEvent);
862         } else if (nvspPacket->Header.MessageType ==
863                    NvspMessage1TypeSendRNDISPacketComplete) {
864                 /* Get the send context */
865                 nvscPacket = (struct hv_netvsc_packet *)(unsigned long)Packet->TransactionId;
866                 /* ASSERT(nvscPacket); */
867
868                 /* Notify the layer above us */
869                 nvscPacket->Completion.Send.OnSendCompletion(nvscPacket->Completion.Send.SendCompletionContext);
870
871                 atomic_dec(&netDevice->NumOutstandingSends);
872         } else {
873                 DPRINT_ERR(NETVSC, "Unknown send completion packet type - "
874                            "%d received!!", nvspPacket->Header.MessageType);
875         }
876
877         PutNetDevice(Device);
878 }
879
880 static int NetVscOnSend(struct hv_device *Device,
881                         struct hv_netvsc_packet *Packet)
882 {
883         struct netvsc_device *netDevice;
884         int ret = 0;
885
886         struct nvsp_message sendMessage;
887
888         netDevice = GetOutboundNetDevice(Device);
889         if (!netDevice) {
890                 DPRINT_ERR(NETVSC, "net device (%p) shutting down..."
891                            "ignoring outbound packets", netDevice);
892                 return -2;
893         }
894
895         sendMessage.Header.MessageType = NvspMessage1TypeSendRNDISPacket;
896         if (Packet->IsDataPacket) {
897                 /* 0 is RMC_DATA; */
898                 sendMessage.Messages.Version1Messages.SendRNDISPacket.ChannelType = 0;
899         } else {
900                 /* 1 is RMC_CONTROL; */
901                 sendMessage.Messages.Version1Messages.SendRNDISPacket.ChannelType = 1;
902         }
903
904         /* Not using send buffer section */
905         sendMessage.Messages.Version1Messages.SendRNDISPacket.SendBufferSectionIndex = 0xFFFFFFFF;
906         sendMessage.Messages.Version1Messages.SendRNDISPacket.SendBufferSectionSize = 0;
907
908         if (Packet->PageBufferCount) {
909                 ret = vmbus_sendpacket_pagebuffer(Device->channel,
910                                                   Packet->PageBuffers,
911                                                   Packet->PageBufferCount,
912                                                   &sendMessage,
913                                                   sizeof(struct nvsp_message),
914                                                   (unsigned long)Packet);
915         } else {
916                 ret = vmbus_sendpacket(Device->channel, &sendMessage,
917                                        sizeof(struct nvsp_message),
918                                        (unsigned long)Packet,
919                                        VmbusPacketTypeDataInBand,
920                                        VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
921
922         }
923
924         if (ret != 0)
925                 DPRINT_ERR(NETVSC, "Unable to send packet %p ret %d",
926                            Packet, ret);
927
928         atomic_inc(&netDevice->NumOutstandingSends);
929         PutNetDevice(Device);
930         return ret;
931 }
932
933 static void NetVscOnReceive(struct hv_device *Device,
934                             struct vmpacket_descriptor *Packet)
935 {
936         struct netvsc_device *netDevice;
937         struct vmtransfer_page_packet_header *vmxferpagePacket;
938         struct nvsp_message *nvspPacket;
939         struct hv_netvsc_packet *netvscPacket = NULL;
940         unsigned long start;
941         unsigned long end, endVirtual;
942         /* struct netvsc_driver *netvscDriver; */
943         struct xferpage_packet *xferpagePacket = NULL;
944         int i, j;
945         int count = 0, bytesRemain = 0;
946         unsigned long flags;
947         LIST_HEAD(listHead);
948
949         netDevice = GetInboundNetDevice(Device);
950         if (!netDevice) {
951                 DPRINT_ERR(NETVSC, "unable to get net device..."
952                            "device being destroyed?");
953                 return;
954         }
955
956         /*
957          * All inbound packets other than send completion should be xfer page
958          * packet
959          */
960         if (Packet->Type != VmbusPacketTypeDataUsingTransferPages) {
961                 DPRINT_ERR(NETVSC, "Unknown packet type received - %d",
962                            Packet->Type);
963                 PutNetDevice(Device);
964                 return;
965         }
966
967         nvspPacket = (struct nvsp_message *)((unsigned long)Packet +
968                         (Packet->DataOffset8 << 3));
969
970         /* Make sure this is a valid nvsp packet */
971         if (nvspPacket->Header.MessageType != NvspMessage1TypeSendRNDISPacket) {
972                 DPRINT_ERR(NETVSC, "Unknown nvsp packet type received - %d",
973                            nvspPacket->Header.MessageType);
974                 PutNetDevice(Device);
975                 return;
976         }
977
978         DPRINT_DBG(NETVSC, "NVSP packet received - type %d",
979                    nvspPacket->Header.MessageType);
980
981         vmxferpagePacket = (struct vmtransfer_page_packet_header *)Packet;
982
983         if (vmxferpagePacket->TransferPageSetId != NETVSC_RECEIVE_BUFFER_ID) {
984                 DPRINT_ERR(NETVSC, "Invalid xfer page set id - "
985                            "expecting %x got %x", NETVSC_RECEIVE_BUFFER_ID,
986                            vmxferpagePacket->TransferPageSetId);
987                 PutNetDevice(Device);
988                 return;
989         }
990
991         DPRINT_DBG(NETVSC, "xfer page - range count %d",
992                    vmxferpagePacket->RangeCount);
993
994         /*
995          * Grab free packets (range count + 1) to represent this xfer
996          * page packet. +1 to represent the xfer page packet itself.
997          * We grab it here so that we know exactly how many we can
998          * fulfil
999          */
1000         spin_lock_irqsave(&netDevice->receive_packet_list_lock, flags);
1001         while (!list_empty(&netDevice->ReceivePacketList)) {
1002                 list_move_tail(netDevice->ReceivePacketList.next, &listHead);
1003                 if (++count == vmxferpagePacket->RangeCount + 1)
1004                         break;
1005         }
1006         spin_unlock_irqrestore(&netDevice->receive_packet_list_lock, flags);
1007
1008         /*
1009          * We need at least 2 netvsc pkts (1 to represent the xfer
1010          * page and at least 1 for the range) i.e. we can handled
1011          * some of the xfer page packet ranges...
1012          */
1013         if (count < 2) {
1014                 DPRINT_ERR(NETVSC, "Got only %d netvsc pkt...needed %d pkts. "
1015                            "Dropping this xfer page packet completely!",
1016                            count, vmxferpagePacket->RangeCount + 1);
1017
1018                 /* Return it to the freelist */
1019                 spin_lock_irqsave(&netDevice->receive_packet_list_lock, flags);
1020                 for (i = count; i != 0; i--) {
1021                         list_move_tail(listHead.next,
1022                                        &netDevice->ReceivePacketList);
1023                 }
1024                 spin_unlock_irqrestore(&netDevice->receive_packet_list_lock,
1025                                        flags);
1026
1027                 NetVscSendReceiveCompletion(Device,
1028                                             vmxferpagePacket->d.TransactionId);
1029
1030                 PutNetDevice(Device);
1031                 return;
1032         }
1033
1034         /* Remove the 1st packet to represent the xfer page packet itself */
1035         xferpagePacket = (struct xferpage_packet *)listHead.next;
1036         list_del(&xferpagePacket->ListEntry);
1037
1038         /* This is how much we can satisfy */
1039         xferpagePacket->Count = count - 1;
1040         /* ASSERT(xferpagePacket->Count > 0 && xferpagePacket->Count <= */
1041         /*      vmxferpagePacket->RangeCount); */
1042
1043         if (xferpagePacket->Count != vmxferpagePacket->RangeCount) {
1044                 DPRINT_INFO(NETVSC, "Needed %d netvsc pkts to satisy this xfer "
1045                             "page...got %d", vmxferpagePacket->RangeCount,
1046                             xferpagePacket->Count);
1047         }
1048
1049         /* Each range represents 1 RNDIS pkt that contains 1 ethernet frame */
1050         for (i = 0; i < (count - 1); i++) {
1051                 netvscPacket = (struct hv_netvsc_packet *)listHead.next;
1052                 list_del(&netvscPacket->ListEntry);
1053
1054                 /* Initialize the netvsc packet */
1055                 netvscPacket->XferPagePacket = xferpagePacket;
1056                 netvscPacket->Completion.Recv.OnReceiveCompletion =
1057                                         NetVscOnReceiveCompletion;
1058                 netvscPacket->Completion.Recv.ReceiveCompletionContext =
1059                                         netvscPacket;
1060                 netvscPacket->Device = Device;
1061                 /* Save this so that we can send it back */
1062                 netvscPacket->Completion.Recv.ReceiveCompletionTid =
1063                                         vmxferpagePacket->d.TransactionId;
1064
1065                 netvscPacket->TotalDataBufferLength =
1066                                         vmxferpagePacket->Ranges[i].ByteCount;
1067                 netvscPacket->PageBufferCount = 1;
1068
1069                 /* ASSERT(vmxferpagePacket->Ranges[i].ByteOffset + */
1070                 /*      vmxferpagePacket->Ranges[i].ByteCount < */
1071                 /*      netDevice->ReceiveBufferSize); */
1072
1073                 netvscPacket->PageBuffers[0].Length =
1074                                         vmxferpagePacket->Ranges[i].ByteCount;
1075
1076                 start = virt_to_phys((void *)((unsigned long)netDevice->ReceiveBuffer + vmxferpagePacket->Ranges[i].ByteOffset));
1077
1078                 netvscPacket->PageBuffers[0].Pfn = start >> PAGE_SHIFT;
1079                 endVirtual = (unsigned long)netDevice->ReceiveBuffer
1080                     + vmxferpagePacket->Ranges[i].ByteOffset
1081                     + vmxferpagePacket->Ranges[i].ByteCount - 1;
1082                 end = virt_to_phys((void *)endVirtual);
1083
1084                 /* Calculate the page relative offset */
1085                 netvscPacket->PageBuffers[0].Offset =
1086                         vmxferpagePacket->Ranges[i].ByteOffset & (PAGE_SIZE - 1);
1087                 if ((end >> PAGE_SHIFT) != (start >> PAGE_SHIFT)) {
1088                         /* Handle frame across multiple pages: */
1089                         netvscPacket->PageBuffers[0].Length =
1090                                 (netvscPacket->PageBuffers[0].Pfn << PAGE_SHIFT)
1091                                 + PAGE_SIZE - start;
1092                         bytesRemain = netvscPacket->TotalDataBufferLength -
1093                                         netvscPacket->PageBuffers[0].Length;
1094                         for (j = 1; j < NETVSC_PACKET_MAXPAGE; j++) {
1095                                 netvscPacket->PageBuffers[j].Offset = 0;
1096                                 if (bytesRemain <= PAGE_SIZE) {
1097                                         netvscPacket->PageBuffers[j].Length = bytesRemain;
1098                                         bytesRemain = 0;
1099                                 } else {
1100                                         netvscPacket->PageBuffers[j].Length = PAGE_SIZE;
1101                                         bytesRemain -= PAGE_SIZE;
1102                                 }
1103                                 netvscPacket->PageBuffers[j].Pfn =
1104                                     virt_to_phys((void *)(endVirtual - bytesRemain)) >> PAGE_SHIFT;
1105                                 netvscPacket->PageBufferCount++;
1106                                 if (bytesRemain == 0)
1107                                         break;
1108                         }
1109                         /* ASSERT(bytesRemain == 0); */
1110                 }
1111                 DPRINT_DBG(NETVSC, "[%d] - (abs offset %u len %u) => "
1112                            "(pfn %llx, offset %u, len %u)", i,
1113                            vmxferpagePacket->Ranges[i].ByteOffset,
1114                            vmxferpagePacket->Ranges[i].ByteCount,
1115                            netvscPacket->PageBuffers[0].Pfn,
1116                            netvscPacket->PageBuffers[0].Offset,
1117                            netvscPacket->PageBuffers[0].Length);
1118
1119                 /* Pass it to the upper layer */
1120                 ((struct netvsc_driver *)Device->Driver)->OnReceiveCallback(Device, netvscPacket);
1121
1122                 NetVscOnReceiveCompletion(netvscPacket->Completion.Recv.ReceiveCompletionContext);
1123         }
1124
1125         /* ASSERT(list_empty(&listHead)); */
1126
1127         PutNetDevice(Device);
1128 }
1129
1130 static void NetVscSendReceiveCompletion(struct hv_device *Device,
1131                                         u64 TransactionId)
1132 {
1133         struct nvsp_message recvcompMessage;
1134         int retries = 0;
1135         int ret;
1136
1137         DPRINT_DBG(NETVSC, "Sending receive completion pkt - %llx",
1138                    TransactionId);
1139
1140         recvcompMessage.Header.MessageType =
1141                                 NvspMessage1TypeSendRNDISPacketComplete;
1142
1143         /* FIXME: Pass in the status */
1144         recvcompMessage.Messages.Version1Messages.SendRNDISPacketComplete.Status = NvspStatusSuccess;
1145
1146 retry_send_cmplt:
1147         /* Send the completion */
1148         ret = vmbus_sendpacket(Device->channel, &recvcompMessage,
1149                                sizeof(struct nvsp_message), TransactionId,
1150                                VmbusPacketTypeCompletion, 0);
1151         if (ret == 0) {
1152                 /* success */
1153                 /* no-op */
1154         } else if (ret == -1) {
1155                 /* no more room...wait a bit and attempt to retry 3 times */
1156                 retries++;
1157                 DPRINT_ERR(NETVSC, "unable to send receive completion pkt "
1158                            "(tid %llx)...retrying %d", TransactionId, retries);
1159
1160                 if (retries < 4) {
1161                         udelay(100);
1162                         goto retry_send_cmplt;
1163                 } else {
1164                         DPRINT_ERR(NETVSC, "unable to send receive completion "
1165                                   "pkt (tid %llx)...give up retrying",
1166                                   TransactionId);
1167                 }
1168         } else {
1169                 DPRINT_ERR(NETVSC, "unable to send receive completion pkt - "
1170                            "%llx", TransactionId);
1171         }
1172 }
1173
1174 /* Send a receive completion packet to RNDIS device (ie NetVsp) */
1175 static void NetVscOnReceiveCompletion(void *Context)
1176 {
1177         struct hv_netvsc_packet *packet = Context;
1178         struct hv_device *device = (struct hv_device *)packet->Device;
1179         struct netvsc_device *netDevice;
1180         u64 transactionId = 0;
1181         bool fSendReceiveComp = false;
1182         unsigned long flags;
1183
1184         /* ASSERT(packet->XferPagePacket); */
1185
1186         /*
1187          * Even though it seems logical to do a GetOutboundNetDevice() here to
1188          * send out receive completion, we are using GetInboundNetDevice()
1189          * since we may have disable outbound traffic already.
1190          */
1191         netDevice = GetInboundNetDevice(device);
1192         if (!netDevice) {
1193                 DPRINT_ERR(NETVSC, "unable to get net device..."
1194                            "device being destroyed?");
1195                 return;
1196         }
1197
1198         /* Overloading use of the lock. */
1199         spin_lock_irqsave(&netDevice->receive_packet_list_lock, flags);
1200
1201         /* ASSERT(packet->XferPagePacket->Count > 0); */
1202         packet->XferPagePacket->Count--;
1203
1204         /*
1205          * Last one in the line that represent 1 xfer page packet.
1206          * Return the xfer page packet itself to the freelist
1207          */
1208         if (packet->XferPagePacket->Count == 0) {
1209                 fSendReceiveComp = true;
1210                 transactionId = packet->Completion.Recv.ReceiveCompletionTid;
1211                 list_add_tail(&packet->XferPagePacket->ListEntry,
1212                               &netDevice->ReceivePacketList);
1213
1214         }
1215
1216         /* Put the packet back */
1217         list_add_tail(&packet->ListEntry, &netDevice->ReceivePacketList);
1218         spin_unlock_irqrestore(&netDevice->receive_packet_list_lock, flags);
1219
1220         /* Send a receive completion for the xfer page packet */
1221         if (fSendReceiveComp)
1222                 NetVscSendReceiveCompletion(device, transactionId);
1223
1224         PutNetDevice(device);
1225 }
1226
1227 static void NetVscOnChannelCallback(void *Context)
1228 {
1229         int ret;
1230         struct hv_device *device = Context;
1231         struct netvsc_device *netDevice;
1232         u32 bytesRecvd;
1233         u64 requestId;
1234         unsigned char *packet;
1235         struct vmpacket_descriptor *desc;
1236         unsigned char *buffer;
1237         int bufferlen = NETVSC_PACKET_SIZE;
1238
1239         /* ASSERT(device); */
1240
1241         packet = kzalloc(NETVSC_PACKET_SIZE * sizeof(unsigned char),
1242                          GFP_KERNEL);
1243         if (!packet)
1244                 return;
1245         buffer = packet;
1246
1247         netDevice = GetInboundNetDevice(device);
1248         if (!netDevice) {
1249                 DPRINT_ERR(NETVSC, "net device (%p) shutting down..."
1250                            "ignoring inbound packets", netDevice);
1251                 goto out;
1252         }
1253
1254         do {
1255                 ret = vmbus_recvpacket_raw(device->channel, buffer, bufferlen,
1256                                            &bytesRecvd, &requestId);
1257                 if (ret == 0) {
1258                         if (bytesRecvd > 0) {
1259                                 DPRINT_DBG(NETVSC, "receive %d bytes, tid %llx",
1260                                            bytesRecvd, requestId);
1261
1262                                 desc = (struct vmpacket_descriptor *)buffer;
1263                                 switch (desc->Type) {
1264                                 case VmbusPacketTypeCompletion:
1265                                         NetVscOnSendCompletion(device, desc);
1266                                         break;
1267
1268                                 case VmbusPacketTypeDataUsingTransferPages:
1269                                         NetVscOnReceive(device, desc);
1270                                         break;
1271
1272                                 default:
1273                                         DPRINT_ERR(NETVSC,
1274                                                    "unhandled packet type %d, "
1275                                                    "tid %llx len %d\n",
1276                                                    desc->Type, requestId,
1277                                                    bytesRecvd);
1278                                         break;
1279                                 }
1280
1281                                 /* reset */
1282                                 if (bufferlen > NETVSC_PACKET_SIZE) {
1283                                         kfree(buffer);
1284                                         buffer = packet;
1285                                         bufferlen = NETVSC_PACKET_SIZE;
1286                                 }
1287                         } else {
1288                                 /* reset */
1289                                 if (bufferlen > NETVSC_PACKET_SIZE) {
1290                                         kfree(buffer);
1291                                         buffer = packet;
1292                                         bufferlen = NETVSC_PACKET_SIZE;
1293                                 }
1294
1295                                 break;
1296                         }
1297                 } else if (ret == -2) {
1298                         /* Handle large packet */
1299                         buffer = kmalloc(bytesRecvd, GFP_ATOMIC);
1300                         if (buffer == NULL) {
1301                                 /* Try again next time around */
1302                                 DPRINT_ERR(NETVSC,
1303                                            "unable to allocate buffer of size "
1304                                            "(%d)!!", bytesRecvd);
1305                                 break;
1306                         }
1307
1308                         bufferlen = bytesRecvd;
1309                 }
1310         } while (1);
1311
1312         PutNetDevice(device);
1313 out:
1314         kfree(buffer);
1315         return;
1316 }