hv_netvsc: move start_remove flag to net_device_context
[cascardo/linux.git] / drivers / net / hyperv / 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, see <http://www.gnu.org/licenses/>.
15  *
16  * Authors:
17  *   Haiyang Zhang <haiyangz@microsoft.com>
18  *   Hank Janssen  <hjanssen@microsoft.com>
19  */
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21
22 #include <linux/kernel.h>
23 #include <linux/sched.h>
24 #include <linux/wait.h>
25 #include <linux/mm.h>
26 #include <linux/delay.h>
27 #include <linux/io.h>
28 #include <linux/slab.h>
29 #include <linux/netdevice.h>
30 #include <linux/if_ether.h>
31 #include <linux/vmalloc.h>
32 #include <asm/sync_bitops.h>
33
34 #include "hyperv_net.h"
35
36 /*
37  * Switch the data path from the synthetic interface to the VF
38  * interface.
39  */
40 void netvsc_switch_datapath(struct netvsc_device *nv_dev, bool vf)
41 {
42         struct nvsp_message *init_pkt = &nv_dev->channel_init_pkt;
43         struct hv_device *dev = nv_dev->dev;
44
45         memset(init_pkt, 0, sizeof(struct nvsp_message));
46         init_pkt->hdr.msg_type = NVSP_MSG4_TYPE_SWITCH_DATA_PATH;
47         if (vf)
48                 init_pkt->msg.v4_msg.active_dp.active_datapath =
49                         NVSP_DATAPATH_VF;
50         else
51                 init_pkt->msg.v4_msg.active_dp.active_datapath =
52                         NVSP_DATAPATH_SYNTHETIC;
53
54         vmbus_sendpacket(dev->channel, init_pkt,
55                                sizeof(struct nvsp_message),
56                                (unsigned long)init_pkt,
57                                VM_PKT_DATA_INBAND, 0);
58 }
59
60
61 static struct netvsc_device *alloc_net_device(struct hv_device *device)
62 {
63         struct netvsc_device *net_device;
64         struct net_device *ndev = hv_get_drvdata(device);
65
66         net_device = kzalloc(sizeof(struct netvsc_device), GFP_KERNEL);
67         if (!net_device)
68                 return NULL;
69
70         net_device->cb_buffer = kzalloc(NETVSC_PACKET_SIZE, GFP_KERNEL);
71         if (!net_device->cb_buffer) {
72                 kfree(net_device);
73                 return NULL;
74         }
75
76         init_waitqueue_head(&net_device->wait_drain);
77         net_device->destroy = false;
78         atomic_set(&net_device->open_cnt, 0);
79         atomic_set(&net_device->vf_use_cnt, 0);
80         net_device->dev = device;
81         net_device->ndev = ndev;
82         net_device->max_pkt = RNDIS_MAX_PKT_DEFAULT;
83         net_device->pkt_align = RNDIS_PKT_ALIGN_DEFAULT;
84
85         net_device->vf_netdev = NULL;
86         net_device->vf_inject = false;
87
88         hv_set_drvdata(device, net_device);
89         return net_device;
90 }
91
92 static void free_netvsc_device(struct netvsc_device *nvdev)
93 {
94         kfree(nvdev->cb_buffer);
95         kfree(nvdev);
96 }
97
98 static struct netvsc_device *get_outbound_net_device(struct hv_device *device)
99 {
100         struct netvsc_device *net_device;
101
102         net_device = hv_get_drvdata(device);
103         if (net_device && net_device->destroy)
104                 net_device = NULL;
105
106         return net_device;
107 }
108
109 static struct netvsc_device *get_inbound_net_device(struct hv_device *device)
110 {
111         struct netvsc_device *net_device;
112
113         net_device = hv_get_drvdata(device);
114
115         if (!net_device)
116                 goto get_in_err;
117
118         if (net_device->destroy &&
119                 atomic_read(&net_device->num_outstanding_sends) == 0)
120                 net_device = NULL;
121
122 get_in_err:
123         return net_device;
124 }
125
126
127 static int netvsc_destroy_buf(struct netvsc_device *net_device)
128 {
129         struct nvsp_message *revoke_packet;
130         int ret = 0;
131         struct net_device *ndev = net_device->ndev;
132
133         /*
134          * If we got a section count, it means we received a
135          * SendReceiveBufferComplete msg (ie sent
136          * NvspMessage1TypeSendReceiveBuffer msg) therefore, we need
137          * to send a revoke msg here
138          */
139         if (net_device->recv_section_cnt) {
140                 /* Send the revoke receive buffer */
141                 revoke_packet = &net_device->revoke_packet;
142                 memset(revoke_packet, 0, sizeof(struct nvsp_message));
143
144                 revoke_packet->hdr.msg_type =
145                         NVSP_MSG1_TYPE_REVOKE_RECV_BUF;
146                 revoke_packet->msg.v1_msg.
147                 revoke_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
148
149                 ret = vmbus_sendpacket(net_device->dev->channel,
150                                        revoke_packet,
151                                        sizeof(struct nvsp_message),
152                                        (unsigned long)revoke_packet,
153                                        VM_PKT_DATA_INBAND, 0);
154                 /*
155                  * If we failed here, we might as well return and
156                  * have a leak rather than continue and a bugchk
157                  */
158                 if (ret != 0) {
159                         netdev_err(ndev, "unable to send "
160                                 "revoke receive buffer to netvsp\n");
161                         return ret;
162                 }
163         }
164
165         /* Teardown the gpadl on the vsp end */
166         if (net_device->recv_buf_gpadl_handle) {
167                 ret = vmbus_teardown_gpadl(net_device->dev->channel,
168                            net_device->recv_buf_gpadl_handle);
169
170                 /* If we failed here, we might as well return and have a leak
171                  * rather than continue and a bugchk
172                  */
173                 if (ret != 0) {
174                         netdev_err(ndev,
175                                    "unable to teardown receive buffer's gpadl\n");
176                         return ret;
177                 }
178                 net_device->recv_buf_gpadl_handle = 0;
179         }
180
181         if (net_device->recv_buf) {
182                 /* Free up the receive buffer */
183                 vfree(net_device->recv_buf);
184                 net_device->recv_buf = NULL;
185         }
186
187         if (net_device->recv_section) {
188                 net_device->recv_section_cnt = 0;
189                 kfree(net_device->recv_section);
190                 net_device->recv_section = NULL;
191         }
192
193         /* Deal with the send buffer we may have setup.
194          * If we got a  send section size, it means we received a
195          * NVSP_MSG1_TYPE_SEND_SEND_BUF_COMPLETE msg (ie sent
196          * NVSP_MSG1_TYPE_SEND_SEND_BUF msg) therefore, we need
197          * to send a revoke msg here
198          */
199         if (net_device->send_section_size) {
200                 /* Send the revoke receive buffer */
201                 revoke_packet = &net_device->revoke_packet;
202                 memset(revoke_packet, 0, sizeof(struct nvsp_message));
203
204                 revoke_packet->hdr.msg_type =
205                         NVSP_MSG1_TYPE_REVOKE_SEND_BUF;
206                 revoke_packet->msg.v1_msg.revoke_send_buf.id =
207                         NETVSC_SEND_BUFFER_ID;
208
209                 ret = vmbus_sendpacket(net_device->dev->channel,
210                                        revoke_packet,
211                                        sizeof(struct nvsp_message),
212                                        (unsigned long)revoke_packet,
213                                        VM_PKT_DATA_INBAND, 0);
214                 /* If we failed here, we might as well return and
215                  * have a leak rather than continue and a bugchk
216                  */
217                 if (ret != 0) {
218                         netdev_err(ndev, "unable to send "
219                                    "revoke send buffer to netvsp\n");
220                         return ret;
221                 }
222         }
223         /* Teardown the gpadl on the vsp end */
224         if (net_device->send_buf_gpadl_handle) {
225                 ret = vmbus_teardown_gpadl(net_device->dev->channel,
226                                            net_device->send_buf_gpadl_handle);
227
228                 /* If we failed here, we might as well return and have a leak
229                  * rather than continue and a bugchk
230                  */
231                 if (ret != 0) {
232                         netdev_err(ndev,
233                                    "unable to teardown send buffer's gpadl\n");
234                         return ret;
235                 }
236                 net_device->send_buf_gpadl_handle = 0;
237         }
238         if (net_device->send_buf) {
239                 /* Free up the send buffer */
240                 vfree(net_device->send_buf);
241                 net_device->send_buf = NULL;
242         }
243         kfree(net_device->send_section_map);
244
245         return ret;
246 }
247
248 static int netvsc_init_buf(struct hv_device *device)
249 {
250         int ret = 0;
251         unsigned long t;
252         struct netvsc_device *net_device;
253         struct nvsp_message *init_packet;
254         struct net_device *ndev;
255         int node;
256
257         net_device = get_outbound_net_device(device);
258         if (!net_device)
259                 return -ENODEV;
260         ndev = net_device->ndev;
261
262         node = cpu_to_node(device->channel->target_cpu);
263         net_device->recv_buf = vzalloc_node(net_device->recv_buf_size, node);
264         if (!net_device->recv_buf)
265                 net_device->recv_buf = vzalloc(net_device->recv_buf_size);
266
267         if (!net_device->recv_buf) {
268                 netdev_err(ndev, "unable to allocate receive "
269                         "buffer of size %d\n", net_device->recv_buf_size);
270                 ret = -ENOMEM;
271                 goto cleanup;
272         }
273
274         /*
275          * Establish the gpadl handle for this buffer on this
276          * channel.  Note: This call uses the vmbus connection rather
277          * than the channel to establish the gpadl handle.
278          */
279         ret = vmbus_establish_gpadl(device->channel, net_device->recv_buf,
280                                     net_device->recv_buf_size,
281                                     &net_device->recv_buf_gpadl_handle);
282         if (ret != 0) {
283                 netdev_err(ndev,
284                         "unable to establish receive buffer's gpadl\n");
285                 goto cleanup;
286         }
287
288
289         /* Notify the NetVsp of the gpadl handle */
290         init_packet = &net_device->channel_init_pkt;
291
292         memset(init_packet, 0, sizeof(struct nvsp_message));
293
294         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_RECV_BUF;
295         init_packet->msg.v1_msg.send_recv_buf.
296                 gpadl_handle = net_device->recv_buf_gpadl_handle;
297         init_packet->msg.v1_msg.
298                 send_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
299
300         /* Send the gpadl notification request */
301         ret = vmbus_sendpacket(device->channel, init_packet,
302                                sizeof(struct nvsp_message),
303                                (unsigned long)init_packet,
304                                VM_PKT_DATA_INBAND,
305                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
306         if (ret != 0) {
307                 netdev_err(ndev,
308                         "unable to send receive buffer's gpadl to netvsp\n");
309                 goto cleanup;
310         }
311
312         t = wait_for_completion_timeout(&net_device->channel_init_wait, 5*HZ);
313         BUG_ON(t == 0);
314
315
316         /* Check the response */
317         if (init_packet->msg.v1_msg.
318             send_recv_buf_complete.status != NVSP_STAT_SUCCESS) {
319                 netdev_err(ndev, "Unable to complete receive buffer "
320                            "initialization with NetVsp - status %d\n",
321                            init_packet->msg.v1_msg.
322                            send_recv_buf_complete.status);
323                 ret = -EINVAL;
324                 goto cleanup;
325         }
326
327         /* Parse the response */
328
329         net_device->recv_section_cnt = init_packet->msg.
330                 v1_msg.send_recv_buf_complete.num_sections;
331
332         net_device->recv_section = kmemdup(
333                 init_packet->msg.v1_msg.send_recv_buf_complete.sections,
334                 net_device->recv_section_cnt *
335                 sizeof(struct nvsp_1_receive_buffer_section),
336                 GFP_KERNEL);
337         if (net_device->recv_section == NULL) {
338                 ret = -EINVAL;
339                 goto cleanup;
340         }
341
342         /*
343          * For 1st release, there should only be 1 section that represents the
344          * entire receive buffer
345          */
346         if (net_device->recv_section_cnt != 1 ||
347             net_device->recv_section->offset != 0) {
348                 ret = -EINVAL;
349                 goto cleanup;
350         }
351
352         /* Now setup the send buffer.
353          */
354         net_device->send_buf = vzalloc_node(net_device->send_buf_size, node);
355         if (!net_device->send_buf)
356                 net_device->send_buf = vzalloc(net_device->send_buf_size);
357         if (!net_device->send_buf) {
358                 netdev_err(ndev, "unable to allocate send "
359                            "buffer of size %d\n", net_device->send_buf_size);
360                 ret = -ENOMEM;
361                 goto cleanup;
362         }
363
364         /* Establish the gpadl handle for this buffer on this
365          * channel.  Note: This call uses the vmbus connection rather
366          * than the channel to establish the gpadl handle.
367          */
368         ret = vmbus_establish_gpadl(device->channel, net_device->send_buf,
369                                     net_device->send_buf_size,
370                                     &net_device->send_buf_gpadl_handle);
371         if (ret != 0) {
372                 netdev_err(ndev,
373                            "unable to establish send buffer's gpadl\n");
374                 goto cleanup;
375         }
376
377         /* Notify the NetVsp of the gpadl handle */
378         init_packet = &net_device->channel_init_pkt;
379         memset(init_packet, 0, sizeof(struct nvsp_message));
380         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_SEND_BUF;
381         init_packet->msg.v1_msg.send_send_buf.gpadl_handle =
382                 net_device->send_buf_gpadl_handle;
383         init_packet->msg.v1_msg.send_send_buf.id = NETVSC_SEND_BUFFER_ID;
384
385         /* Send the gpadl notification request */
386         ret = vmbus_sendpacket(device->channel, init_packet,
387                                sizeof(struct nvsp_message),
388                                (unsigned long)init_packet,
389                                VM_PKT_DATA_INBAND,
390                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
391         if (ret != 0) {
392                 netdev_err(ndev,
393                            "unable to send send buffer's gpadl to netvsp\n");
394                 goto cleanup;
395         }
396
397         t = wait_for_completion_timeout(&net_device->channel_init_wait, 5*HZ);
398         BUG_ON(t == 0);
399
400         /* Check the response */
401         if (init_packet->msg.v1_msg.
402             send_send_buf_complete.status != NVSP_STAT_SUCCESS) {
403                 netdev_err(ndev, "Unable to complete send buffer "
404                            "initialization with NetVsp - status %d\n",
405                            init_packet->msg.v1_msg.
406                            send_send_buf_complete.status);
407                 ret = -EINVAL;
408                 goto cleanup;
409         }
410
411         /* Parse the response */
412         net_device->send_section_size = init_packet->msg.
413                                 v1_msg.send_send_buf_complete.section_size;
414
415         /* Section count is simply the size divided by the section size.
416          */
417         net_device->send_section_cnt =
418                 net_device->send_buf_size/net_device->send_section_size;
419
420         dev_info(&device->device, "Send section size: %d, Section count:%d\n",
421                  net_device->send_section_size, net_device->send_section_cnt);
422
423         /* Setup state for managing the send buffer. */
424         net_device->map_words = DIV_ROUND_UP(net_device->send_section_cnt,
425                                              BITS_PER_LONG);
426
427         net_device->send_section_map =
428                 kzalloc(net_device->map_words * sizeof(ulong), GFP_KERNEL);
429         if (net_device->send_section_map == NULL) {
430                 ret = -ENOMEM;
431                 goto cleanup;
432         }
433
434         goto exit;
435
436 cleanup:
437         netvsc_destroy_buf(net_device);
438
439 exit:
440         return ret;
441 }
442
443
444 /* Negotiate NVSP protocol version */
445 static int negotiate_nvsp_ver(struct hv_device *device,
446                               struct netvsc_device *net_device,
447                               struct nvsp_message *init_packet,
448                               u32 nvsp_ver)
449 {
450         int ret;
451         unsigned long t;
452
453         memset(init_packet, 0, sizeof(struct nvsp_message));
454         init_packet->hdr.msg_type = NVSP_MSG_TYPE_INIT;
455         init_packet->msg.init_msg.init.min_protocol_ver = nvsp_ver;
456         init_packet->msg.init_msg.init.max_protocol_ver = nvsp_ver;
457
458         /* Send the init request */
459         ret = vmbus_sendpacket(device->channel, init_packet,
460                                sizeof(struct nvsp_message),
461                                (unsigned long)init_packet,
462                                VM_PKT_DATA_INBAND,
463                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
464
465         if (ret != 0)
466                 return ret;
467
468         t = wait_for_completion_timeout(&net_device->channel_init_wait, 5*HZ);
469
470         if (t == 0)
471                 return -ETIMEDOUT;
472
473         if (init_packet->msg.init_msg.init_complete.status !=
474             NVSP_STAT_SUCCESS)
475                 return -EINVAL;
476
477         if (nvsp_ver == NVSP_PROTOCOL_VERSION_1)
478                 return 0;
479
480         /* NVSPv2 or later: Send NDIS config */
481         memset(init_packet, 0, sizeof(struct nvsp_message));
482         init_packet->hdr.msg_type = NVSP_MSG2_TYPE_SEND_NDIS_CONFIG;
483         init_packet->msg.v2_msg.send_ndis_config.mtu = net_device->ndev->mtu +
484                                                        ETH_HLEN;
485         init_packet->msg.v2_msg.send_ndis_config.capability.ieee8021q = 1;
486
487         if (nvsp_ver >= NVSP_PROTOCOL_VERSION_5)
488                 init_packet->msg.v2_msg.send_ndis_config.capability.sriov = 1;
489
490         ret = vmbus_sendpacket(device->channel, init_packet,
491                                 sizeof(struct nvsp_message),
492                                 (unsigned long)init_packet,
493                                 VM_PKT_DATA_INBAND, 0);
494
495         return ret;
496 }
497
498 static int netvsc_connect_vsp(struct hv_device *device)
499 {
500         int ret;
501         struct netvsc_device *net_device;
502         struct nvsp_message *init_packet;
503         int ndis_version;
504         struct net_device *ndev;
505         u32 ver_list[] = { NVSP_PROTOCOL_VERSION_1, NVSP_PROTOCOL_VERSION_2,
506                 NVSP_PROTOCOL_VERSION_4, NVSP_PROTOCOL_VERSION_5 };
507         int i, num_ver = 4; /* number of different NVSP versions */
508
509         net_device = get_outbound_net_device(device);
510         if (!net_device)
511                 return -ENODEV;
512         ndev = net_device->ndev;
513
514         init_packet = &net_device->channel_init_pkt;
515
516         /* Negotiate the latest NVSP protocol supported */
517         for (i = num_ver - 1; i >= 0; i--)
518                 if (negotiate_nvsp_ver(device, net_device, init_packet,
519                                        ver_list[i])  == 0) {
520                         net_device->nvsp_version = ver_list[i];
521                         break;
522                 }
523
524         if (i < 0) {
525                 ret = -EPROTO;
526                 goto cleanup;
527         }
528
529         pr_debug("Negotiated NVSP version:%x\n", net_device->nvsp_version);
530
531         /* Send the ndis version */
532         memset(init_packet, 0, sizeof(struct nvsp_message));
533
534         if (net_device->nvsp_version <= NVSP_PROTOCOL_VERSION_4)
535                 ndis_version = 0x00060001;
536         else
537                 ndis_version = 0x0006001e;
538
539         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_NDIS_VER;
540         init_packet->msg.v1_msg.
541                 send_ndis_ver.ndis_major_ver =
542                                 (ndis_version & 0xFFFF0000) >> 16;
543         init_packet->msg.v1_msg.
544                 send_ndis_ver.ndis_minor_ver =
545                                 ndis_version & 0xFFFF;
546
547         /* Send the init request */
548         ret = vmbus_sendpacket(device->channel, init_packet,
549                                 sizeof(struct nvsp_message),
550                                 (unsigned long)init_packet,
551                                 VM_PKT_DATA_INBAND, 0);
552         if (ret != 0)
553                 goto cleanup;
554
555         /* Post the big receive buffer to NetVSP */
556         if (net_device->nvsp_version <= NVSP_PROTOCOL_VERSION_2)
557                 net_device->recv_buf_size = NETVSC_RECEIVE_BUFFER_SIZE_LEGACY;
558         else
559                 net_device->recv_buf_size = NETVSC_RECEIVE_BUFFER_SIZE;
560         net_device->send_buf_size = NETVSC_SEND_BUFFER_SIZE;
561
562         ret = netvsc_init_buf(device);
563
564 cleanup:
565         return ret;
566 }
567
568 static void netvsc_disconnect_vsp(struct netvsc_device *net_device)
569 {
570         netvsc_destroy_buf(net_device);
571 }
572
573 /*
574  * netvsc_device_remove - Callback when the root bus device is removed
575  */
576 int netvsc_device_remove(struct hv_device *device)
577 {
578         struct netvsc_device *net_device;
579         unsigned long flags;
580
581         net_device = hv_get_drvdata(device);
582
583         netvsc_disconnect_vsp(net_device);
584
585         /*
586          * Since we have already drained, we don't need to busy wait
587          * as was done in final_release_stor_device()
588          * Note that we cannot set the ext pointer to NULL until
589          * we have drained - to drain the outgoing packets, we need to
590          * allow incoming packets.
591          */
592
593         spin_lock_irqsave(&device->channel->inbound_lock, flags);
594         hv_set_drvdata(device, NULL);
595         spin_unlock_irqrestore(&device->channel->inbound_lock, flags);
596
597         /*
598          * At this point, no one should be accessing net_device
599          * except in here
600          */
601         dev_notice(&device->device, "net device safe to remove\n");
602
603         /* Now, we can close the channel safely */
604         vmbus_close(device->channel);
605
606         /* Release all resources */
607         vfree(net_device->sub_cb_buf);
608         free_netvsc_device(net_device);
609         return 0;
610 }
611
612
613 #define RING_AVAIL_PERCENT_HIWATER 20
614 #define RING_AVAIL_PERCENT_LOWATER 10
615
616 /*
617  * Get the percentage of available bytes to write in the ring.
618  * The return value is in range from 0 to 100.
619  */
620 static inline u32 hv_ringbuf_avail_percent(
621                 struct hv_ring_buffer_info *ring_info)
622 {
623         u32 avail_read, avail_write;
624
625         hv_get_ringbuffer_availbytes(ring_info, &avail_read, &avail_write);
626
627         return avail_write * 100 / ring_info->ring_datasize;
628 }
629
630 static inline void netvsc_free_send_slot(struct netvsc_device *net_device,
631                                          u32 index)
632 {
633         sync_change_bit(index, net_device->send_section_map);
634 }
635
636 static void netvsc_send_completion(struct netvsc_device *net_device,
637                                    struct vmbus_channel *incoming_channel,
638                                    struct hv_device *device,
639                                    struct vmpacket_descriptor *packet)
640 {
641         struct nvsp_message *nvsp_packet;
642         struct hv_netvsc_packet *nvsc_packet;
643         struct net_device *ndev;
644         u32 send_index;
645         struct sk_buff *skb;
646
647         ndev = net_device->ndev;
648
649         nvsp_packet = (struct nvsp_message *)((unsigned long)packet +
650                         (packet->offset8 << 3));
651
652         if ((nvsp_packet->hdr.msg_type == NVSP_MSG_TYPE_INIT_COMPLETE) ||
653             (nvsp_packet->hdr.msg_type ==
654              NVSP_MSG1_TYPE_SEND_RECV_BUF_COMPLETE) ||
655             (nvsp_packet->hdr.msg_type ==
656              NVSP_MSG1_TYPE_SEND_SEND_BUF_COMPLETE) ||
657             (nvsp_packet->hdr.msg_type ==
658              NVSP_MSG5_TYPE_SUBCHANNEL)) {
659                 /* Copy the response back */
660                 memcpy(&net_device->channel_init_pkt, nvsp_packet,
661                        sizeof(struct nvsp_message));
662                 complete(&net_device->channel_init_wait);
663         } else if (nvsp_packet->hdr.msg_type ==
664                    NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE) {
665                 int num_outstanding_sends;
666                 u16 q_idx = 0;
667                 struct vmbus_channel *channel = device->channel;
668                 int queue_sends;
669
670                 /* Get the send context */
671                 skb = (struct sk_buff *)(unsigned long)packet->trans_id;
672
673                 /* Notify the layer above us */
674                 if (skb) {
675                         nvsc_packet = (struct hv_netvsc_packet *) skb->cb;
676                         send_index = nvsc_packet->send_buf_index;
677                         if (send_index != NETVSC_INVALID_INDEX)
678                                 netvsc_free_send_slot(net_device, send_index);
679                         q_idx = nvsc_packet->q_idx;
680                         channel = incoming_channel;
681                         dev_kfree_skb_any(skb);
682                 }
683
684                 num_outstanding_sends =
685                         atomic_dec_return(&net_device->num_outstanding_sends);
686                 queue_sends = atomic_dec_return(&net_device->
687                                                 queue_sends[q_idx]);
688
689                 if (net_device->destroy && num_outstanding_sends == 0)
690                         wake_up(&net_device->wait_drain);
691
692                 if (netif_tx_queue_stopped(netdev_get_tx_queue(ndev, q_idx)) &&
693                     !net_device->nd_ctx->start_remove &&
694                     (hv_ringbuf_avail_percent(&channel->outbound) >
695                      RING_AVAIL_PERCENT_HIWATER || queue_sends < 1))
696                                 netif_tx_wake_queue(netdev_get_tx_queue(
697                                                     ndev, q_idx));
698         } else {
699                 netdev_err(ndev, "Unknown send completion packet type- "
700                            "%d received!!\n", nvsp_packet->hdr.msg_type);
701         }
702
703 }
704
705 static u32 netvsc_get_next_send_section(struct netvsc_device *net_device)
706 {
707         unsigned long index;
708         u32 max_words = net_device->map_words;
709         unsigned long *map_addr = (unsigned long *)net_device->send_section_map;
710         u32 section_cnt = net_device->send_section_cnt;
711         int ret_val = NETVSC_INVALID_INDEX;
712         int i;
713         int prev_val;
714
715         for (i = 0; i < max_words; i++) {
716                 if (!~(map_addr[i]))
717                         continue;
718                 index = ffz(map_addr[i]);
719                 prev_val = sync_test_and_set_bit(index, &map_addr[i]);
720                 if (prev_val)
721                         continue;
722                 if ((index + (i * BITS_PER_LONG)) >= section_cnt)
723                         break;
724                 ret_val = (index + (i * BITS_PER_LONG));
725                 break;
726         }
727         return ret_val;
728 }
729
730 static u32 netvsc_copy_to_send_buf(struct netvsc_device *net_device,
731                                    unsigned int section_index,
732                                    u32 pend_size,
733                                    struct hv_netvsc_packet *packet,
734                                    struct rndis_message *rndis_msg,
735                                    struct hv_page_buffer **pb,
736                                    struct sk_buff *skb)
737 {
738         char *start = net_device->send_buf;
739         char *dest = start + (section_index * net_device->send_section_size)
740                      + pend_size;
741         int i;
742         bool is_data_pkt = (skb != NULL) ? true : false;
743         bool xmit_more = (skb != NULL) ? skb->xmit_more : false;
744         u32 msg_size = 0;
745         u32 padding = 0;
746         u32 remain = packet->total_data_buflen % net_device->pkt_align;
747         u32 page_count = packet->cp_partial ? packet->rmsg_pgcnt :
748                 packet->page_buf_cnt;
749
750         /* Add padding */
751         if (is_data_pkt && xmit_more && remain &&
752             !packet->cp_partial) {
753                 padding = net_device->pkt_align - remain;
754                 rndis_msg->msg_len += padding;
755                 packet->total_data_buflen += padding;
756         }
757
758         for (i = 0; i < page_count; i++) {
759                 char *src = phys_to_virt((*pb)[i].pfn << PAGE_SHIFT);
760                 u32 offset = (*pb)[i].offset;
761                 u32 len = (*pb)[i].len;
762
763                 memcpy(dest, (src + offset), len);
764                 msg_size += len;
765                 dest += len;
766         }
767
768         if (padding) {
769                 memset(dest, 0, padding);
770                 msg_size += padding;
771         }
772
773         return msg_size;
774 }
775
776 static inline int netvsc_send_pkt(
777         struct hv_netvsc_packet *packet,
778         struct netvsc_device *net_device,
779         struct hv_page_buffer **pb,
780         struct sk_buff *skb)
781 {
782         struct nvsp_message nvmsg;
783         u16 q_idx = packet->q_idx;
784         struct vmbus_channel *out_channel = net_device->chn_table[q_idx];
785         struct net_device *ndev = net_device->ndev;
786         u64 req_id;
787         int ret;
788         struct hv_page_buffer *pgbuf;
789         u32 ring_avail = hv_ringbuf_avail_percent(&out_channel->outbound);
790         bool xmit_more = (skb != NULL) ? skb->xmit_more : false;
791
792         nvmsg.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT;
793         if (skb != NULL) {
794                 /* 0 is RMC_DATA; */
795                 nvmsg.msg.v1_msg.send_rndis_pkt.channel_type = 0;
796         } else {
797                 /* 1 is RMC_CONTROL; */
798                 nvmsg.msg.v1_msg.send_rndis_pkt.channel_type = 1;
799         }
800
801         nvmsg.msg.v1_msg.send_rndis_pkt.send_buf_section_index =
802                 packet->send_buf_index;
803         if (packet->send_buf_index == NETVSC_INVALID_INDEX)
804                 nvmsg.msg.v1_msg.send_rndis_pkt.send_buf_section_size = 0;
805         else
806                 nvmsg.msg.v1_msg.send_rndis_pkt.send_buf_section_size =
807                         packet->total_data_buflen;
808
809         req_id = (ulong)skb;
810
811         if (out_channel->rescind)
812                 return -ENODEV;
813
814         /*
815          * It is possible that once we successfully place this packet
816          * on the ringbuffer, we may stop the queue. In that case, we want
817          * to notify the host independent of the xmit_more flag. We don't
818          * need to be precise here; in the worst case we may signal the host
819          * unnecessarily.
820          */
821         if (ring_avail < (RING_AVAIL_PERCENT_LOWATER + 1))
822                 xmit_more = false;
823
824         if (packet->page_buf_cnt) {
825                 pgbuf = packet->cp_partial ? (*pb) +
826                         packet->rmsg_pgcnt : (*pb);
827                 ret = vmbus_sendpacket_pagebuffer_ctl(out_channel,
828                                                       pgbuf,
829                                                       packet->page_buf_cnt,
830                                                       &nvmsg,
831                                                       sizeof(struct nvsp_message),
832                                                       req_id,
833                                                       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED,
834                                                       !xmit_more);
835         } else {
836                 ret = vmbus_sendpacket_ctl(out_channel, &nvmsg,
837                                            sizeof(struct nvsp_message),
838                                            req_id,
839                                            VM_PKT_DATA_INBAND,
840                                            VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED,
841                                            !xmit_more);
842         }
843
844         if (ret == 0) {
845                 atomic_inc(&net_device->num_outstanding_sends);
846                 atomic_inc(&net_device->queue_sends[q_idx]);
847
848                 if (ring_avail < RING_AVAIL_PERCENT_LOWATER) {
849                         netif_tx_stop_queue(netdev_get_tx_queue(ndev, q_idx));
850
851                         if (atomic_read(&net_device->
852                                 queue_sends[q_idx]) < 1)
853                                 netif_tx_wake_queue(netdev_get_tx_queue(
854                                                     ndev, q_idx));
855                 }
856         } else if (ret == -EAGAIN) {
857                 netif_tx_stop_queue(netdev_get_tx_queue(
858                                     ndev, q_idx));
859                 if (atomic_read(&net_device->queue_sends[q_idx]) < 1) {
860                         netif_tx_wake_queue(netdev_get_tx_queue(
861                                             ndev, q_idx));
862                         ret = -ENOSPC;
863                 }
864         } else {
865                 netdev_err(ndev, "Unable to send packet %p ret %d\n",
866                            packet, ret);
867         }
868
869         return ret;
870 }
871
872 /* Move packet out of multi send data (msd), and clear msd */
873 static inline void move_pkt_msd(struct hv_netvsc_packet **msd_send,
874                                 struct sk_buff **msd_skb,
875                                 struct multi_send_data *msdp)
876 {
877         *msd_skb = msdp->skb;
878         *msd_send = msdp->pkt;
879         msdp->skb = NULL;
880         msdp->pkt = NULL;
881         msdp->count = 0;
882 }
883
884 int netvsc_send(struct hv_device *device,
885                 struct hv_netvsc_packet *packet,
886                 struct rndis_message *rndis_msg,
887                 struct hv_page_buffer **pb,
888                 struct sk_buff *skb)
889 {
890         struct netvsc_device *net_device;
891         int ret = 0, m_ret = 0;
892         struct vmbus_channel *out_channel;
893         u16 q_idx = packet->q_idx;
894         u32 pktlen = packet->total_data_buflen, msd_len = 0;
895         unsigned int section_index = NETVSC_INVALID_INDEX;
896         struct multi_send_data *msdp;
897         struct hv_netvsc_packet *msd_send = NULL, *cur_send = NULL;
898         struct sk_buff *msd_skb = NULL;
899         bool try_batch;
900         bool xmit_more = (skb != NULL) ? skb->xmit_more : false;
901
902         net_device = get_outbound_net_device(device);
903         if (!net_device)
904                 return -ENODEV;
905
906         out_channel = net_device->chn_table[q_idx];
907
908         packet->send_buf_index = NETVSC_INVALID_INDEX;
909         packet->cp_partial = false;
910
911         /* Send control message directly without accessing msd (Multi-Send
912          * Data) field which may be changed during data packet processing.
913          */
914         if (!skb) {
915                 cur_send = packet;
916                 goto send_now;
917         }
918
919         msdp = &net_device->msd[q_idx];
920
921         /* batch packets in send buffer if possible */
922         if (msdp->pkt)
923                 msd_len = msdp->pkt->total_data_buflen;
924
925         try_batch = (skb != NULL) && msd_len > 0 && msdp->count <
926                     net_device->max_pkt;
927
928         if (try_batch && msd_len + pktlen + net_device->pkt_align <
929             net_device->send_section_size) {
930                 section_index = msdp->pkt->send_buf_index;
931
932         } else if (try_batch && msd_len + packet->rmsg_size <
933                    net_device->send_section_size) {
934                 section_index = msdp->pkt->send_buf_index;
935                 packet->cp_partial = true;
936
937         } else if ((skb != NULL) && pktlen + net_device->pkt_align <
938                    net_device->send_section_size) {
939                 section_index = netvsc_get_next_send_section(net_device);
940                 if (section_index != NETVSC_INVALID_INDEX) {
941                         move_pkt_msd(&msd_send, &msd_skb, msdp);
942                         msd_len = 0;
943                 }
944         }
945
946         if (section_index != NETVSC_INVALID_INDEX) {
947                 netvsc_copy_to_send_buf(net_device,
948                                         section_index, msd_len,
949                                         packet, rndis_msg, pb, skb);
950
951                 packet->send_buf_index = section_index;
952
953                 if (packet->cp_partial) {
954                         packet->page_buf_cnt -= packet->rmsg_pgcnt;
955                         packet->total_data_buflen = msd_len + packet->rmsg_size;
956                 } else {
957                         packet->page_buf_cnt = 0;
958                         packet->total_data_buflen += msd_len;
959                 }
960
961                 if (msdp->skb)
962                         dev_kfree_skb_any(msdp->skb);
963
964                 if (xmit_more && !packet->cp_partial) {
965                         msdp->skb = skb;
966                         msdp->pkt = packet;
967                         msdp->count++;
968                 } else {
969                         cur_send = packet;
970                         msdp->skb = NULL;
971                         msdp->pkt = NULL;
972                         msdp->count = 0;
973                 }
974         } else {
975                 move_pkt_msd(&msd_send, &msd_skb, msdp);
976                 cur_send = packet;
977         }
978
979         if (msd_send) {
980                 m_ret = netvsc_send_pkt(msd_send, net_device, NULL, msd_skb);
981
982                 if (m_ret != 0) {
983                         netvsc_free_send_slot(net_device,
984                                               msd_send->send_buf_index);
985                         dev_kfree_skb_any(msd_skb);
986                 }
987         }
988
989 send_now:
990         if (cur_send)
991                 ret = netvsc_send_pkt(cur_send, net_device, pb, skb);
992
993         if (ret != 0 && section_index != NETVSC_INVALID_INDEX)
994                 netvsc_free_send_slot(net_device, section_index);
995
996         return ret;
997 }
998
999 static void netvsc_send_recv_completion(struct hv_device *device,
1000                                         struct vmbus_channel *channel,
1001                                         struct netvsc_device *net_device,
1002                                         u64 transaction_id, u32 status)
1003 {
1004         struct nvsp_message recvcompMessage;
1005         int retries = 0;
1006         int ret;
1007         struct net_device *ndev;
1008
1009         ndev = net_device->ndev;
1010
1011         recvcompMessage.hdr.msg_type =
1012                                 NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE;
1013
1014         recvcompMessage.msg.v1_msg.send_rndis_pkt_complete.status = status;
1015
1016 retry_send_cmplt:
1017         /* Send the completion */
1018         ret = vmbus_sendpacket(channel, &recvcompMessage,
1019                                sizeof(struct nvsp_message), transaction_id,
1020                                VM_PKT_COMP, 0);
1021         if (ret == 0) {
1022                 /* success */
1023                 /* no-op */
1024         } else if (ret == -EAGAIN) {
1025                 /* no more room...wait a bit and attempt to retry 3 times */
1026                 retries++;
1027                 netdev_err(ndev, "unable to send receive completion pkt"
1028                         " (tid %llx)...retrying %d\n", transaction_id, retries);
1029
1030                 if (retries < 4) {
1031                         udelay(100);
1032                         goto retry_send_cmplt;
1033                 } else {
1034                         netdev_err(ndev, "unable to send receive "
1035                                 "completion pkt (tid %llx)...give up retrying\n",
1036                                 transaction_id);
1037                 }
1038         } else {
1039                 netdev_err(ndev, "unable to send receive "
1040                         "completion pkt - %llx\n", transaction_id);
1041         }
1042 }
1043
1044 static void netvsc_receive(struct netvsc_device *net_device,
1045                         struct vmbus_channel *channel,
1046                         struct hv_device *device,
1047                         struct vmpacket_descriptor *packet)
1048 {
1049         struct vmtransfer_page_packet_header *vmxferpage_packet;
1050         struct nvsp_message *nvsp_packet;
1051         struct hv_netvsc_packet nv_pkt;
1052         struct hv_netvsc_packet *netvsc_packet = &nv_pkt;
1053         u32 status = NVSP_STAT_SUCCESS;
1054         int i;
1055         int count = 0;
1056         struct net_device *ndev;
1057         void *data;
1058
1059         ndev = net_device->ndev;
1060
1061         /*
1062          * All inbound packets other than send completion should be xfer page
1063          * packet
1064          */
1065         if (packet->type != VM_PKT_DATA_USING_XFER_PAGES) {
1066                 netdev_err(ndev, "Unknown packet type received - %d\n",
1067                            packet->type);
1068                 return;
1069         }
1070
1071         nvsp_packet = (struct nvsp_message *)((unsigned long)packet +
1072                         (packet->offset8 << 3));
1073
1074         /* Make sure this is a valid nvsp packet */
1075         if (nvsp_packet->hdr.msg_type !=
1076             NVSP_MSG1_TYPE_SEND_RNDIS_PKT) {
1077                 netdev_err(ndev, "Unknown nvsp packet type received-"
1078                         " %d\n", nvsp_packet->hdr.msg_type);
1079                 return;
1080         }
1081
1082         vmxferpage_packet = (struct vmtransfer_page_packet_header *)packet;
1083
1084         if (vmxferpage_packet->xfer_pageset_id != NETVSC_RECEIVE_BUFFER_ID) {
1085                 netdev_err(ndev, "Invalid xfer page set id - "
1086                            "expecting %x got %x\n", NETVSC_RECEIVE_BUFFER_ID,
1087                            vmxferpage_packet->xfer_pageset_id);
1088                 return;
1089         }
1090
1091         count = vmxferpage_packet->range_cnt;
1092
1093         /* Each range represents 1 RNDIS pkt that contains 1 ethernet frame */
1094         for (i = 0; i < count; i++) {
1095                 /* Initialize the netvsc packet */
1096                 data = (void *)((unsigned long)net_device->
1097                         recv_buf + vmxferpage_packet->ranges[i].byte_offset);
1098                 netvsc_packet->total_data_buflen =
1099                                         vmxferpage_packet->ranges[i].byte_count;
1100
1101                 /* Pass it to the upper layer */
1102                 status = rndis_filter_receive(device, netvsc_packet, &data,
1103                                               channel);
1104
1105         }
1106
1107         netvsc_send_recv_completion(device, channel, net_device,
1108                                     vmxferpage_packet->d.trans_id, status);
1109 }
1110
1111
1112 static void netvsc_send_table(struct hv_device *hdev,
1113                               struct nvsp_message *nvmsg)
1114 {
1115         struct netvsc_device *nvscdev;
1116         struct net_device *ndev;
1117         int i;
1118         u32 count, *tab;
1119
1120         nvscdev = get_outbound_net_device(hdev);
1121         if (!nvscdev)
1122                 return;
1123         ndev = nvscdev->ndev;
1124
1125         count = nvmsg->msg.v5_msg.send_table.count;
1126         if (count != VRSS_SEND_TAB_SIZE) {
1127                 netdev_err(ndev, "Received wrong send-table size:%u\n", count);
1128                 return;
1129         }
1130
1131         tab = (u32 *)((unsigned long)&nvmsg->msg.v5_msg.send_table +
1132                       nvmsg->msg.v5_msg.send_table.offset);
1133
1134         for (i = 0; i < count; i++)
1135                 nvscdev->send_table[i] = tab[i];
1136 }
1137
1138 static void netvsc_send_vf(struct netvsc_device *nvdev,
1139                            struct nvsp_message *nvmsg)
1140 {
1141         nvdev->vf_alloc = nvmsg->msg.v4_msg.vf_assoc.allocated;
1142         nvdev->vf_serial = nvmsg->msg.v4_msg.vf_assoc.serial;
1143 }
1144
1145 static inline void netvsc_receive_inband(struct hv_device *hdev,
1146                                          struct netvsc_device *nvdev,
1147                                          struct nvsp_message *nvmsg)
1148 {
1149         switch (nvmsg->hdr.msg_type) {
1150         case NVSP_MSG5_TYPE_SEND_INDIRECTION_TABLE:
1151                 netvsc_send_table(hdev, nvmsg);
1152                 break;
1153
1154         case NVSP_MSG4_TYPE_SEND_VF_ASSOCIATION:
1155                 netvsc_send_vf(nvdev, nvmsg);
1156                 break;
1157         }
1158 }
1159
1160 void netvsc_channel_cb(void *context)
1161 {
1162         int ret;
1163         struct vmbus_channel *channel = (struct vmbus_channel *)context;
1164         struct hv_device *device;
1165         struct netvsc_device *net_device;
1166         u32 bytes_recvd;
1167         u64 request_id;
1168         struct vmpacket_descriptor *desc;
1169         unsigned char *buffer;
1170         int bufferlen = NETVSC_PACKET_SIZE;
1171         struct net_device *ndev;
1172         struct nvsp_message *nvmsg;
1173
1174         if (channel->primary_channel != NULL)
1175                 device = channel->primary_channel->device_obj;
1176         else
1177                 device = channel->device_obj;
1178
1179         net_device = get_inbound_net_device(device);
1180         if (!net_device)
1181                 return;
1182         ndev = net_device->ndev;
1183         buffer = get_per_channel_state(channel);
1184
1185         do {
1186                 ret = vmbus_recvpacket_raw(channel, buffer, bufferlen,
1187                                            &bytes_recvd, &request_id);
1188                 if (ret == 0) {
1189                         if (bytes_recvd > 0) {
1190                                 desc = (struct vmpacket_descriptor *)buffer;
1191                                 nvmsg = (struct nvsp_message *)((unsigned long)
1192                                          desc + (desc->offset8 << 3));
1193                                 switch (desc->type) {
1194                                 case VM_PKT_COMP:
1195                                         netvsc_send_completion(net_device,
1196                                                                 channel,
1197                                                                 device, desc);
1198                                         break;
1199
1200                                 case VM_PKT_DATA_USING_XFER_PAGES:
1201                                         netvsc_receive(net_device, channel,
1202                                                        device, desc);
1203                                         break;
1204
1205                                 case VM_PKT_DATA_INBAND:
1206                                         netvsc_receive_inband(device,
1207                                                               net_device,
1208                                                               nvmsg);
1209                                         break;
1210
1211                                 default:
1212                                         netdev_err(ndev,
1213                                                    "unhandled packet type %d, "
1214                                                    "tid %llx len %d\n",
1215                                                    desc->type, request_id,
1216                                                    bytes_recvd);
1217                                         break;
1218                                 }
1219
1220                         } else {
1221                                 /*
1222                                  * We are done for this pass.
1223                                  */
1224                                 break;
1225                         }
1226
1227                 } else if (ret == -ENOBUFS) {
1228                         if (bufferlen > NETVSC_PACKET_SIZE)
1229                                 kfree(buffer);
1230                         /* Handle large packet */
1231                         buffer = kmalloc(bytes_recvd, GFP_ATOMIC);
1232                         if (buffer == NULL) {
1233                                 /* Try again next time around */
1234                                 netdev_err(ndev,
1235                                            "unable to allocate buffer of size "
1236                                            "(%d)!!\n", bytes_recvd);
1237                                 break;
1238                         }
1239
1240                         bufferlen = bytes_recvd;
1241                 }
1242         } while (1);
1243
1244         if (bufferlen > NETVSC_PACKET_SIZE)
1245                 kfree(buffer);
1246         return;
1247 }
1248
1249 /*
1250  * netvsc_device_add - Callback when the device belonging to this
1251  * driver is added
1252  */
1253 int netvsc_device_add(struct hv_device *device, void *additional_info)
1254 {
1255         int ret = 0;
1256         int ring_size =
1257         ((struct netvsc_device_info *)additional_info)->ring_size;
1258         struct netvsc_device *net_device;
1259         struct net_device *ndev;
1260
1261         net_device = alloc_net_device(device);
1262         if (!net_device)
1263                 return -ENOMEM;
1264
1265         net_device->ring_size = ring_size;
1266
1267         /*
1268          * Coming into this function, struct net_device * is
1269          * registered as the driver private data.
1270          * In alloc_net_device(), we register struct netvsc_device *
1271          * as the driver private data and stash away struct net_device *
1272          * in struct netvsc_device *.
1273          */
1274         ndev = net_device->ndev;
1275
1276         /* Add netvsc_device context to netvsc_device */
1277         net_device->nd_ctx = netdev_priv(ndev);
1278
1279         /* Initialize the NetVSC channel extension */
1280         init_completion(&net_device->channel_init_wait);
1281
1282         set_per_channel_state(device->channel, net_device->cb_buffer);
1283
1284         /* Open the channel */
1285         ret = vmbus_open(device->channel, ring_size * PAGE_SIZE,
1286                          ring_size * PAGE_SIZE, NULL, 0,
1287                          netvsc_channel_cb, device->channel);
1288
1289         if (ret != 0) {
1290                 netdev_err(ndev, "unable to open channel: %d\n", ret);
1291                 goto cleanup;
1292         }
1293
1294         /* Channel is opened */
1295         pr_info("hv_netvsc channel opened successfully\n");
1296
1297         net_device->chn_table[0] = device->channel;
1298
1299         /* Connect with the NetVsp */
1300         ret = netvsc_connect_vsp(device);
1301         if (ret != 0) {
1302                 netdev_err(ndev,
1303                         "unable to connect to NetVSP - %d\n", ret);
1304                 goto close;
1305         }
1306
1307         return ret;
1308
1309 close:
1310         /* Now, we can close the channel safely */
1311         vmbus_close(device->channel);
1312
1313 cleanup:
1314         free_netvsc_device(net_device);
1315
1316         return ret;
1317 }