GNU Linux-libre 4.14.254-gnu1
[releases.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 <linux/rtnetlink.h>
33 #include <linux/prefetch.h>
34
35 #include <asm/sync_bitops.h>
36
37 #include "hyperv_net.h"
38
39 /*
40  * Switch the data path from the synthetic interface to the VF
41  * interface.
42  */
43 void netvsc_switch_datapath(struct net_device *ndev, bool vf)
44 {
45         struct net_device_context *net_device_ctx = netdev_priv(ndev);
46         struct hv_device *dev = net_device_ctx->device_ctx;
47         struct netvsc_device *nv_dev = rtnl_dereference(net_device_ctx->nvdev);
48         struct nvsp_message *init_pkt = &nv_dev->channel_init_pkt;
49
50         memset(init_pkt, 0, sizeof(struct nvsp_message));
51         init_pkt->hdr.msg_type = NVSP_MSG4_TYPE_SWITCH_DATA_PATH;
52         if (vf)
53                 init_pkt->msg.v4_msg.active_dp.active_datapath =
54                         NVSP_DATAPATH_VF;
55         else
56                 init_pkt->msg.v4_msg.active_dp.active_datapath =
57                         NVSP_DATAPATH_SYNTHETIC;
58
59         vmbus_sendpacket(dev->channel, init_pkt,
60                                sizeof(struct nvsp_message),
61                                (unsigned long)init_pkt,
62                                VM_PKT_DATA_INBAND, 0);
63 }
64
65 /* Worker to setup sub channels on initial setup
66  * Initial hotplug event occurs in softirq context
67  * and can't wait for channels.
68  */
69 static void netvsc_subchan_work(struct work_struct *w)
70 {
71         struct netvsc_device *nvdev =
72                 container_of(w, struct netvsc_device, subchan_work);
73         struct rndis_device *rdev;
74         int i, ret;
75
76         /* Avoid deadlock with device removal already under RTNL */
77         if (!rtnl_trylock()) {
78                 schedule_work(w);
79                 return;
80         }
81
82         rdev = nvdev->extension;
83         if (rdev) {
84                 ret = rndis_set_subchannel(rdev->ndev, nvdev);
85                 if (ret == 0) {
86                         netif_device_attach(rdev->ndev);
87                 } else {
88                         /* fallback to only primary channel */
89                         for (i = 1; i < nvdev->num_chn; i++)
90                                 netif_napi_del(&nvdev->chan_table[i].napi);
91
92                         nvdev->max_chn = 1;
93                         nvdev->num_chn = 1;
94                 }
95         }
96
97         rtnl_unlock();
98 }
99
100 static struct netvsc_device *alloc_net_device(void)
101 {
102         struct netvsc_device *net_device;
103
104         net_device = kzalloc(sizeof(struct netvsc_device), GFP_KERNEL);
105         if (!net_device)
106                 return NULL;
107
108         init_waitqueue_head(&net_device->wait_drain);
109         net_device->destroy = false;
110         net_device->tx_disable = false;
111         atomic_set(&net_device->open_cnt, 0);
112         net_device->max_pkt = RNDIS_MAX_PKT_DEFAULT;
113         net_device->pkt_align = RNDIS_PKT_ALIGN_DEFAULT;
114
115         init_completion(&net_device->channel_init_wait);
116         init_waitqueue_head(&net_device->subchan_open);
117         INIT_WORK(&net_device->subchan_work, netvsc_subchan_work);
118
119         return net_device;
120 }
121
122 static void free_netvsc_device(struct rcu_head *head)
123 {
124         struct netvsc_device *nvdev
125                 = container_of(head, struct netvsc_device, rcu);
126         int i;
127
128         kfree(nvdev->extension);
129         vfree(nvdev->recv_buf);
130         vfree(nvdev->send_buf);
131         kfree(nvdev->send_section_map);
132
133         for (i = 0; i < VRSS_CHANNEL_MAX; i++)
134                 vfree(nvdev->chan_table[i].mrc.slots);
135
136         kfree(nvdev);
137 }
138
139 static void free_netvsc_device_rcu(struct netvsc_device *nvdev)
140 {
141         call_rcu(&nvdev->rcu, free_netvsc_device);
142 }
143
144 static void netvsc_revoke_recv_buf(struct hv_device *device,
145                                    struct netvsc_device *net_device)
146 {
147         struct net_device *ndev = hv_get_drvdata(device);
148         struct nvsp_message *revoke_packet;
149         int ret;
150
151         /*
152          * If we got a section count, it means we received a
153          * SendReceiveBufferComplete msg (ie sent
154          * NvspMessage1TypeSendReceiveBuffer msg) therefore, we need
155          * to send a revoke msg here
156          */
157         if (net_device->recv_section_cnt) {
158                 /* Send the revoke receive buffer */
159                 revoke_packet = &net_device->revoke_packet;
160                 memset(revoke_packet, 0, sizeof(struct nvsp_message));
161
162                 revoke_packet->hdr.msg_type =
163                         NVSP_MSG1_TYPE_REVOKE_RECV_BUF;
164                 revoke_packet->msg.v1_msg.
165                 revoke_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
166
167                 ret = vmbus_sendpacket(device->channel,
168                                        revoke_packet,
169                                        sizeof(struct nvsp_message),
170                                        (unsigned long)revoke_packet,
171                                        VM_PKT_DATA_INBAND, 0);
172                 /* If the failure is because the channel is rescinded;
173                  * ignore the failure since we cannot send on a rescinded
174                  * channel. This would allow us to properly cleanup
175                  * even when the channel is rescinded.
176                  */
177                 if (device->channel->rescind)
178                         ret = 0;
179                 /*
180                  * If we failed here, we might as well return and
181                  * have a leak rather than continue and a bugchk
182                  */
183                 if (ret != 0) {
184                         netdev_err(ndev, "unable to send "
185                                 "revoke receive buffer to netvsp\n");
186                         return;
187                 }
188                 net_device->recv_section_cnt = 0;
189         }
190 }
191
192 static void netvsc_revoke_send_buf(struct hv_device *device,
193                                    struct netvsc_device *net_device)
194 {
195         struct net_device *ndev = hv_get_drvdata(device);
196         struct nvsp_message *revoke_packet;
197         int ret;
198
199         /* Deal with the send buffer we may have setup.
200          * If we got a  send section size, it means we received a
201          * NVSP_MSG1_TYPE_SEND_SEND_BUF_COMPLETE msg (ie sent
202          * NVSP_MSG1_TYPE_SEND_SEND_BUF msg) therefore, we need
203          * to send a revoke msg here
204          */
205         if (net_device->send_section_cnt) {
206                 /* Send the revoke receive buffer */
207                 revoke_packet = &net_device->revoke_packet;
208                 memset(revoke_packet, 0, sizeof(struct nvsp_message));
209
210                 revoke_packet->hdr.msg_type =
211                         NVSP_MSG1_TYPE_REVOKE_SEND_BUF;
212                 revoke_packet->msg.v1_msg.revoke_send_buf.id =
213                         NETVSC_SEND_BUFFER_ID;
214
215                 ret = vmbus_sendpacket(device->channel,
216                                        revoke_packet,
217                                        sizeof(struct nvsp_message),
218                                        (unsigned long)revoke_packet,
219                                        VM_PKT_DATA_INBAND, 0);
220
221                 /* If the failure is because the channel is rescinded;
222                  * ignore the failure since we cannot send on a rescinded
223                  * channel. This would allow us to properly cleanup
224                  * even when the channel is rescinded.
225                  */
226                 if (device->channel->rescind)
227                         ret = 0;
228
229                 /* If we failed here, we might as well return and
230                  * have a leak rather than continue and a bugchk
231                  */
232                 if (ret != 0) {
233                         netdev_err(ndev, "unable to send "
234                                    "revoke send buffer to netvsp\n");
235                         return;
236                 }
237                 net_device->send_section_cnt = 0;
238         }
239 }
240
241 static void netvsc_teardown_recv_gpadl(struct hv_device *device,
242                                        struct netvsc_device *net_device)
243 {
244         struct net_device *ndev = hv_get_drvdata(device);
245         int ret;
246
247         if (net_device->recv_buf_gpadl_handle) {
248                 ret = vmbus_teardown_gpadl(device->channel,
249                                            net_device->recv_buf_gpadl_handle);
250
251                 /* If we failed here, we might as well return and have a leak
252                  * rather than continue and a bugchk
253                  */
254                 if (ret != 0) {
255                         netdev_err(ndev,
256                                    "unable to teardown receive buffer's gpadl\n");
257                         return;
258                 }
259                 net_device->recv_buf_gpadl_handle = 0;
260         }
261 }
262
263 static void netvsc_teardown_send_gpadl(struct hv_device *device,
264                                        struct netvsc_device *net_device)
265 {
266         struct net_device *ndev = hv_get_drvdata(device);
267         int ret;
268
269         if (net_device->send_buf_gpadl_handle) {
270                 ret = vmbus_teardown_gpadl(device->channel,
271                                            net_device->send_buf_gpadl_handle);
272
273                 /* If we failed here, we might as well return and have a leak
274                  * rather than continue and a bugchk
275                  */
276                 if (ret != 0) {
277                         netdev_err(ndev,
278                                    "unable to teardown send buffer's gpadl\n");
279                         return;
280                 }
281                 net_device->send_buf_gpadl_handle = 0;
282         }
283 }
284
285 int netvsc_alloc_recv_comp_ring(struct netvsc_device *net_device, u32 q_idx)
286 {
287         struct netvsc_channel *nvchan = &net_device->chan_table[q_idx];
288         int node = cpu_to_node(nvchan->channel->target_cpu);
289         size_t size;
290
291         size = net_device->recv_completion_cnt * sizeof(struct recv_comp_data);
292         nvchan->mrc.slots = vzalloc_node(size, node);
293         if (!nvchan->mrc.slots)
294                 nvchan->mrc.slots = vzalloc(size);
295
296         return nvchan->mrc.slots ? 0 : -ENOMEM;
297 }
298
299 static int netvsc_init_buf(struct hv_device *device,
300                            struct netvsc_device *net_device,
301                            const struct netvsc_device_info *device_info)
302 {
303         struct nvsp_1_message_send_receive_buffer_complete *resp;
304         struct net_device *ndev = hv_get_drvdata(device);
305         struct nvsp_message *init_packet;
306         unsigned int buf_size;
307         size_t map_words;
308         int ret = 0;
309
310         /* Get receive buffer area. */
311         buf_size = device_info->recv_sections * device_info->recv_section_size;
312         buf_size = roundup(buf_size, PAGE_SIZE);
313
314         /* Legacy hosts only allow smaller receive buffer */
315         if (net_device->nvsp_version <= NVSP_PROTOCOL_VERSION_2)
316                 buf_size = min_t(unsigned int, buf_size,
317                                  NETVSC_RECEIVE_BUFFER_SIZE_LEGACY);
318
319         net_device->recv_buf = vzalloc(buf_size);
320         if (!net_device->recv_buf) {
321                 netdev_err(ndev,
322                            "unable to allocate receive buffer of size %u\n",
323                            buf_size);
324                 ret = -ENOMEM;
325                 goto cleanup;
326         }
327
328         /*
329          * Establish the gpadl handle for this buffer on this
330          * channel.  Note: This call uses the vmbus connection rather
331          * than the channel to establish the gpadl handle.
332          */
333         ret = vmbus_establish_gpadl(device->channel, net_device->recv_buf,
334                                     buf_size,
335                                     &net_device->recv_buf_gpadl_handle);
336         if (ret != 0) {
337                 netdev_err(ndev,
338                         "unable to establish receive buffer's gpadl\n");
339                 goto cleanup;
340         }
341
342         /* Notify the NetVsp of the gpadl handle */
343         init_packet = &net_device->channel_init_pkt;
344         memset(init_packet, 0, sizeof(struct nvsp_message));
345         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_RECV_BUF;
346         init_packet->msg.v1_msg.send_recv_buf.
347                 gpadl_handle = net_device->recv_buf_gpadl_handle;
348         init_packet->msg.v1_msg.
349                 send_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
350
351         /* Send the gpadl notification request */
352         ret = vmbus_sendpacket(device->channel, init_packet,
353                                sizeof(struct nvsp_message),
354                                (unsigned long)init_packet,
355                                VM_PKT_DATA_INBAND,
356                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
357         if (ret != 0) {
358                 netdev_err(ndev,
359                         "unable to send receive buffer's gpadl to netvsp\n");
360                 goto cleanup;
361         }
362
363         wait_for_completion(&net_device->channel_init_wait);
364
365         /* Check the response */
366         resp = &init_packet->msg.v1_msg.send_recv_buf_complete;
367         if (resp->status != NVSP_STAT_SUCCESS) {
368                 netdev_err(ndev,
369                            "Unable to complete receive buffer initialization with NetVsp - status %d\n",
370                            resp->status);
371                 ret = -EINVAL;
372                 goto cleanup;
373         }
374
375         /* Parse the response */
376         netdev_dbg(ndev, "Receive sections: %u sub_allocs: size %u count: %u\n",
377                    resp->num_sections, resp->sections[0].sub_alloc_size,
378                    resp->sections[0].num_sub_allocs);
379
380         /* There should only be one section for the entire receive buffer */
381         if (resp->num_sections != 1 || resp->sections[0].offset != 0) {
382                 ret = -EINVAL;
383                 goto cleanup;
384         }
385
386         net_device->recv_section_size = resp->sections[0].sub_alloc_size;
387         net_device->recv_section_cnt = resp->sections[0].num_sub_allocs;
388
389         /* Setup receive completion ring */
390         net_device->recv_completion_cnt
391                 = round_up(net_device->recv_section_cnt + 1,
392                            PAGE_SIZE / sizeof(u64));
393         ret = netvsc_alloc_recv_comp_ring(net_device, 0);
394         if (ret)
395                 goto cleanup;
396
397         /* Now setup the send buffer. */
398         buf_size = device_info->send_sections * device_info->send_section_size;
399         buf_size = round_up(buf_size, PAGE_SIZE);
400
401         net_device->send_buf = vzalloc(buf_size);
402         if (!net_device->send_buf) {
403                 netdev_err(ndev, "unable to allocate send buffer of size %u\n",
404                            buf_size);
405                 ret = -ENOMEM;
406                 goto cleanup;
407         }
408
409         /* Establish the gpadl handle for this buffer on this
410          * channel.  Note: This call uses the vmbus connection rather
411          * than the channel to establish the gpadl handle.
412          */
413         ret = vmbus_establish_gpadl(device->channel, net_device->send_buf,
414                                     buf_size,
415                                     &net_device->send_buf_gpadl_handle);
416         if (ret != 0) {
417                 netdev_err(ndev,
418                            "unable to establish send buffer's gpadl\n");
419                 goto cleanup;
420         }
421
422         /* Notify the NetVsp of the gpadl handle */
423         init_packet = &net_device->channel_init_pkt;
424         memset(init_packet, 0, sizeof(struct nvsp_message));
425         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_SEND_BUF;
426         init_packet->msg.v1_msg.send_send_buf.gpadl_handle =
427                 net_device->send_buf_gpadl_handle;
428         init_packet->msg.v1_msg.send_send_buf.id = NETVSC_SEND_BUFFER_ID;
429
430         /* Send the gpadl notification request */
431         ret = vmbus_sendpacket(device->channel, init_packet,
432                                sizeof(struct nvsp_message),
433                                (unsigned long)init_packet,
434                                VM_PKT_DATA_INBAND,
435                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
436         if (ret != 0) {
437                 netdev_err(ndev,
438                            "unable to send send buffer's gpadl to netvsp\n");
439                 goto cleanup;
440         }
441
442         wait_for_completion(&net_device->channel_init_wait);
443
444         /* Check the response */
445         if (init_packet->msg.v1_msg.
446             send_send_buf_complete.status != NVSP_STAT_SUCCESS) {
447                 netdev_err(ndev, "Unable to complete send buffer "
448                            "initialization with NetVsp - status %d\n",
449                            init_packet->msg.v1_msg.
450                            send_send_buf_complete.status);
451                 ret = -EINVAL;
452                 goto cleanup;
453         }
454
455         /* Parse the response */
456         net_device->send_section_size = init_packet->msg.
457                                 v1_msg.send_send_buf_complete.section_size;
458
459         /* Section count is simply the size divided by the section size. */
460         net_device->send_section_cnt = buf_size / net_device->send_section_size;
461
462         netdev_dbg(ndev, "Send section size: %d, Section count:%d\n",
463                    net_device->send_section_size, net_device->send_section_cnt);
464
465         /* Setup state for managing the send buffer. */
466         map_words = DIV_ROUND_UP(net_device->send_section_cnt, BITS_PER_LONG);
467
468         net_device->send_section_map = kcalloc(map_words, sizeof(ulong), GFP_KERNEL);
469         if (net_device->send_section_map == NULL) {
470                 ret = -ENOMEM;
471                 goto cleanup;
472         }
473
474         goto exit;
475
476 cleanup:
477         netvsc_revoke_recv_buf(device, net_device);
478         netvsc_revoke_send_buf(device, net_device);
479         netvsc_teardown_recv_gpadl(device, net_device);
480         netvsc_teardown_send_gpadl(device, net_device);
481
482 exit:
483         return ret;
484 }
485
486 /* Negotiate NVSP protocol version */
487 static int negotiate_nvsp_ver(struct hv_device *device,
488                               struct netvsc_device *net_device,
489                               struct nvsp_message *init_packet,
490                               u32 nvsp_ver)
491 {
492         struct net_device *ndev = hv_get_drvdata(device);
493         int ret;
494
495         memset(init_packet, 0, sizeof(struct nvsp_message));
496         init_packet->hdr.msg_type = NVSP_MSG_TYPE_INIT;
497         init_packet->msg.init_msg.init.min_protocol_ver = nvsp_ver;
498         init_packet->msg.init_msg.init.max_protocol_ver = nvsp_ver;
499
500         /* Send the init request */
501         ret = vmbus_sendpacket(device->channel, init_packet,
502                                sizeof(struct nvsp_message),
503                                (unsigned long)init_packet,
504                                VM_PKT_DATA_INBAND,
505                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
506
507         if (ret != 0)
508                 return ret;
509
510         wait_for_completion(&net_device->channel_init_wait);
511
512         if (init_packet->msg.init_msg.init_complete.status !=
513             NVSP_STAT_SUCCESS)
514                 return -EINVAL;
515
516         if (nvsp_ver == NVSP_PROTOCOL_VERSION_1)
517                 return 0;
518
519         /* NVSPv2 or later: Send NDIS config */
520         memset(init_packet, 0, sizeof(struct nvsp_message));
521         init_packet->hdr.msg_type = NVSP_MSG2_TYPE_SEND_NDIS_CONFIG;
522         init_packet->msg.v2_msg.send_ndis_config.mtu = ndev->mtu + ETH_HLEN;
523         init_packet->msg.v2_msg.send_ndis_config.capability.ieee8021q = 1;
524
525         if (nvsp_ver >= NVSP_PROTOCOL_VERSION_5) {
526                 init_packet->msg.v2_msg.send_ndis_config.capability.sriov = 1;
527
528                 /* Teaming bit is needed to receive link speed updates */
529                 init_packet->msg.v2_msg.send_ndis_config.capability.teaming = 1;
530         }
531
532         ret = vmbus_sendpacket(device->channel, init_packet,
533                                 sizeof(struct nvsp_message),
534                                 (unsigned long)init_packet,
535                                 VM_PKT_DATA_INBAND, 0);
536
537         return ret;
538 }
539
540 static int netvsc_connect_vsp(struct hv_device *device,
541                               struct netvsc_device *net_device,
542                               const struct netvsc_device_info *device_info)
543 {
544         const u32 ver_list[] = {
545                 NVSP_PROTOCOL_VERSION_1, NVSP_PROTOCOL_VERSION_2,
546                 NVSP_PROTOCOL_VERSION_4, NVSP_PROTOCOL_VERSION_5
547         };
548         struct nvsp_message *init_packet;
549         int ndis_version, i, ret;
550
551         init_packet = &net_device->channel_init_pkt;
552
553         /* Negotiate the latest NVSP protocol supported */
554         for (i = ARRAY_SIZE(ver_list) - 1; i >= 0; i--)
555                 if (negotiate_nvsp_ver(device, net_device, init_packet,
556                                        ver_list[i])  == 0) {
557                         net_device->nvsp_version = ver_list[i];
558                         break;
559                 }
560
561         if (i < 0) {
562                 ret = -EPROTO;
563                 goto cleanup;
564         }
565
566         pr_debug("Negotiated NVSP version:%x\n", net_device->nvsp_version);
567
568         /* Send the ndis version */
569         memset(init_packet, 0, sizeof(struct nvsp_message));
570
571         if (net_device->nvsp_version <= NVSP_PROTOCOL_VERSION_4)
572                 ndis_version = 0x00060001;
573         else
574                 ndis_version = 0x0006001e;
575
576         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_NDIS_VER;
577         init_packet->msg.v1_msg.
578                 send_ndis_ver.ndis_major_ver =
579                                 (ndis_version & 0xFFFF0000) >> 16;
580         init_packet->msg.v1_msg.
581                 send_ndis_ver.ndis_minor_ver =
582                                 ndis_version & 0xFFFF;
583
584         /* Send the init request */
585         ret = vmbus_sendpacket(device->channel, init_packet,
586                                 sizeof(struct nvsp_message),
587                                 (unsigned long)init_packet,
588                                 VM_PKT_DATA_INBAND, 0);
589         if (ret != 0)
590                 goto cleanup;
591
592
593         ret = netvsc_init_buf(device, net_device, device_info);
594
595 cleanup:
596         return ret;
597 }
598
599 /*
600  * netvsc_device_remove - Callback when the root bus device is removed
601  */
602 void netvsc_device_remove(struct hv_device *device)
603 {
604         struct net_device *ndev = hv_get_drvdata(device);
605         struct net_device_context *net_device_ctx = netdev_priv(ndev);
606         struct netvsc_device *net_device
607                 = rtnl_dereference(net_device_ctx->nvdev);
608         int i;
609
610         /*
611          * Revoke receive buffer. If host is pre-Win2016 then tear down
612          * receive buffer GPADL. Do the same for send buffer.
613          */
614         netvsc_revoke_recv_buf(device, net_device);
615         if (vmbus_proto_version < VERSION_WIN10)
616                 netvsc_teardown_recv_gpadl(device, net_device);
617
618         netvsc_revoke_send_buf(device, net_device);
619         if (vmbus_proto_version < VERSION_WIN10)
620                 netvsc_teardown_send_gpadl(device, net_device);
621
622         RCU_INIT_POINTER(net_device_ctx->nvdev, NULL);
623
624         /* And disassociate NAPI context from device */
625         for (i = 0; i < net_device->num_chn; i++)
626                 netif_napi_del(&net_device->chan_table[i].napi);
627
628         /*
629          * At this point, no one should be accessing net_device
630          * except in here
631          */
632         netdev_dbg(ndev, "net device safe to remove\n");
633
634         /* Now, we can close the channel safely */
635         vmbus_close(device->channel);
636
637         /*
638          * If host is Win2016 or higher then we do the GPADL tear down
639          * here after VMBus is closed.
640         */
641         if (vmbus_proto_version >= VERSION_WIN10) {
642                 netvsc_teardown_recv_gpadl(device, net_device);
643                 netvsc_teardown_send_gpadl(device, net_device);
644         }
645
646         /* Release all resources */
647         free_netvsc_device_rcu(net_device);
648 }
649
650 #define RING_AVAIL_PERCENT_HIWATER 20
651 #define RING_AVAIL_PERCENT_LOWATER 10
652
653 /*
654  * Get the percentage of available bytes to write in the ring.
655  * The return value is in range from 0 to 100.
656  */
657 static inline u32 hv_ringbuf_avail_percent(
658                 struct hv_ring_buffer_info *ring_info)
659 {
660         u32 avail_read, avail_write;
661
662         hv_get_ringbuffer_availbytes(ring_info, &avail_read, &avail_write);
663
664         return avail_write * 100 / ring_info->ring_datasize;
665 }
666
667 static inline void netvsc_free_send_slot(struct netvsc_device *net_device,
668                                          u32 index)
669 {
670         sync_change_bit(index, net_device->send_section_map);
671 }
672
673 static void netvsc_send_tx_complete(struct netvsc_device *net_device,
674                                     struct vmbus_channel *incoming_channel,
675                                     struct hv_device *device,
676                                     const struct vmpacket_descriptor *desc,
677                                     int budget)
678 {
679         struct sk_buff *skb = (struct sk_buff *)(unsigned long)desc->trans_id;
680         struct net_device *ndev = hv_get_drvdata(device);
681         struct vmbus_channel *channel = device->channel;
682         u16 q_idx = 0;
683         int queue_sends;
684
685         /* Notify the layer above us */
686         if (likely(skb)) {
687                 const struct hv_netvsc_packet *packet
688                         = (struct hv_netvsc_packet *)skb->cb;
689                 u32 send_index = packet->send_buf_index;
690                 struct netvsc_stats *tx_stats;
691
692                 if (send_index != NETVSC_INVALID_INDEX)
693                         netvsc_free_send_slot(net_device, send_index);
694                 q_idx = packet->q_idx;
695                 channel = incoming_channel;
696
697                 tx_stats = &net_device->chan_table[q_idx].tx_stats;
698
699                 u64_stats_update_begin(&tx_stats->syncp);
700                 tx_stats->packets += packet->total_packets;
701                 tx_stats->bytes += packet->total_bytes;
702                 u64_stats_update_end(&tx_stats->syncp);
703
704                 napi_consume_skb(skb, budget);
705         }
706
707         queue_sends =
708                 atomic_dec_return(&net_device->chan_table[q_idx].queue_sends);
709
710         if (unlikely(net_device->destroy)) {
711                 if (queue_sends == 0)
712                         wake_up(&net_device->wait_drain);
713         } else {
714                 struct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);
715
716                 if (netif_tx_queue_stopped(txq) && !net_device->tx_disable &&
717                     (hv_ringbuf_avail_percent(&channel->outbound) > RING_AVAIL_PERCENT_HIWATER ||
718                      queue_sends < 1)) {
719                         netif_tx_wake_queue(txq);
720                 }
721         }
722 }
723
724 static void netvsc_send_completion(struct netvsc_device *net_device,
725                                    struct vmbus_channel *incoming_channel,
726                                    struct hv_device *device,
727                                    const struct vmpacket_descriptor *desc,
728                                    int budget)
729 {
730         struct nvsp_message *nvsp_packet = hv_pkt_data(desc);
731         struct net_device *ndev = hv_get_drvdata(device);
732
733         switch (nvsp_packet->hdr.msg_type) {
734         case NVSP_MSG_TYPE_INIT_COMPLETE:
735         case NVSP_MSG1_TYPE_SEND_RECV_BUF_COMPLETE:
736         case NVSP_MSG1_TYPE_SEND_SEND_BUF_COMPLETE:
737         case NVSP_MSG5_TYPE_SUBCHANNEL:
738                 /* Copy the response back */
739                 memcpy(&net_device->channel_init_pkt, nvsp_packet,
740                        sizeof(struct nvsp_message));
741                 complete(&net_device->channel_init_wait);
742                 break;
743
744         case NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE:
745                 netvsc_send_tx_complete(net_device, incoming_channel,
746                                         device, desc, budget);
747                 break;
748
749         default:
750                 netdev_err(ndev,
751                            "Unknown send completion type %d received!!\n",
752                            nvsp_packet->hdr.msg_type);
753         }
754 }
755
756 static u32 netvsc_get_next_send_section(struct netvsc_device *net_device)
757 {
758         unsigned long *map_addr = net_device->send_section_map;
759         unsigned int i;
760
761         for_each_clear_bit(i, map_addr, net_device->send_section_cnt) {
762                 if (sync_test_and_set_bit(i, map_addr) == 0)
763                         return i;
764         }
765
766         return NETVSC_INVALID_INDEX;
767 }
768
769 static void netvsc_copy_to_send_buf(struct netvsc_device *net_device,
770                                     unsigned int section_index,
771                                     u32 pend_size,
772                                     struct hv_netvsc_packet *packet,
773                                     struct rndis_message *rndis_msg,
774                                     struct hv_page_buffer *pb,
775                                     bool xmit_more)
776 {
777         char *start = net_device->send_buf;
778         char *dest = start + (section_index * net_device->send_section_size)
779                      + pend_size;
780         int i;
781         u32 msg_size = 0;
782         u32 padding = 0;
783         u32 remain = packet->total_data_buflen % net_device->pkt_align;
784         u32 page_count = packet->cp_partial ? packet->rmsg_pgcnt :
785                 packet->page_buf_cnt;
786
787         /* Add padding */
788         remain = packet->total_data_buflen & (net_device->pkt_align - 1);
789         if (xmit_more && remain) {
790                 padding = net_device->pkt_align - remain;
791                 rndis_msg->msg_len += padding;
792                 packet->total_data_buflen += padding;
793         }
794
795         for (i = 0; i < page_count; i++) {
796                 char *src = phys_to_virt(pb[i].pfn << PAGE_SHIFT);
797                 u32 offset = pb[i].offset;
798                 u32 len = pb[i].len;
799
800                 memcpy(dest, (src + offset), len);
801                 msg_size += len;
802                 dest += len;
803         }
804
805         if (padding) {
806                 memset(dest, 0, padding);
807                 msg_size += padding;
808         }
809 }
810
811 static inline int netvsc_send_pkt(
812         struct hv_device *device,
813         struct hv_netvsc_packet *packet,
814         struct netvsc_device *net_device,
815         struct hv_page_buffer *pb,
816         struct sk_buff *skb)
817 {
818         struct nvsp_message nvmsg;
819         struct nvsp_1_message_send_rndis_packet * const rpkt =
820                 &nvmsg.msg.v1_msg.send_rndis_pkt;
821         struct netvsc_channel * const nvchan =
822                 &net_device->chan_table[packet->q_idx];
823         struct vmbus_channel *out_channel = nvchan->channel;
824         struct net_device *ndev = hv_get_drvdata(device);
825         struct netdev_queue *txq = netdev_get_tx_queue(ndev, packet->q_idx);
826         u64 req_id;
827         int ret;
828         u32 ring_avail = hv_ringbuf_avail_percent(&out_channel->outbound);
829
830         nvmsg.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT;
831         if (skb)
832                 rpkt->channel_type = 0;         /* 0 is RMC_DATA */
833         else
834                 rpkt->channel_type = 1;         /* 1 is RMC_CONTROL */
835
836         rpkt->send_buf_section_index = packet->send_buf_index;
837         if (packet->send_buf_index == NETVSC_INVALID_INDEX)
838                 rpkt->send_buf_section_size = 0;
839         else
840                 rpkt->send_buf_section_size = packet->total_data_buflen;
841
842         req_id = (ulong)skb;
843
844         if (out_channel->rescind)
845                 return -ENODEV;
846
847         if (packet->page_buf_cnt) {
848                 if (packet->cp_partial)
849                         pb += packet->rmsg_pgcnt;
850
851                 ret = vmbus_sendpacket_pagebuffer(out_channel,
852                                                   pb, packet->page_buf_cnt,
853                                                   &nvmsg, sizeof(nvmsg),
854                                                   req_id);
855         } else {
856                 ret = vmbus_sendpacket(out_channel,
857                                        &nvmsg, sizeof(nvmsg),
858                                        req_id, VM_PKT_DATA_INBAND,
859                                        VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
860         }
861
862         if (ret == 0) {
863                 atomic_inc_return(&nvchan->queue_sends);
864
865                 if (ring_avail < RING_AVAIL_PERCENT_LOWATER)
866                         netif_tx_stop_queue(txq);
867         } else if (ret == -EAGAIN) {
868                 netif_tx_stop_queue(txq);
869                 if (atomic_read(&nvchan->queue_sends) < 1 &&
870                     !net_device->tx_disable) {
871                         netif_tx_wake_queue(txq);
872                         ret = -ENOSPC;
873                 }
874         } else {
875                 netdev_err(ndev,
876                            "Unable to send packet pages %u len %u, ret %d\n",
877                            packet->page_buf_cnt, packet->total_data_buflen,
878                            ret);
879         }
880
881         return ret;
882 }
883
884 /* Move packet out of multi send data (msd), and clear msd */
885 static inline void move_pkt_msd(struct hv_netvsc_packet **msd_send,
886                                 struct sk_buff **msd_skb,
887                                 struct multi_send_data *msdp)
888 {
889         *msd_skb = msdp->skb;
890         *msd_send = msdp->pkt;
891         msdp->skb = NULL;
892         msdp->pkt = NULL;
893         msdp->count = 0;
894 }
895
896 /* RCU already held by caller */
897 int netvsc_send(struct net_device *ndev,
898                 struct hv_netvsc_packet *packet,
899                 struct rndis_message *rndis_msg,
900                 struct hv_page_buffer *pb,
901                 struct sk_buff *skb)
902 {
903         struct net_device_context *ndev_ctx = netdev_priv(ndev);
904         struct netvsc_device *net_device
905                 = rcu_dereference_bh(ndev_ctx->nvdev);
906         struct hv_device *device = ndev_ctx->device_ctx;
907         int ret = 0;
908         struct netvsc_channel *nvchan;
909         u32 pktlen = packet->total_data_buflen, msd_len = 0;
910         unsigned int section_index = NETVSC_INVALID_INDEX;
911         struct multi_send_data *msdp;
912         struct hv_netvsc_packet *msd_send = NULL, *cur_send = NULL;
913         struct sk_buff *msd_skb = NULL;
914         bool try_batch, xmit_more;
915
916         /* If device is rescinded, return error and packet will get dropped. */
917         if (unlikely(!net_device || net_device->destroy))
918                 return -ENODEV;
919
920         nvchan = &net_device->chan_table[packet->q_idx];
921         packet->send_buf_index = NETVSC_INVALID_INDEX;
922         packet->cp_partial = false;
923
924         /* Send control message directly without accessing msd (Multi-Send
925          * Data) field which may be changed during data packet processing.
926          */
927         if (!skb)
928                 return netvsc_send_pkt(device, packet, net_device, pb, skb);
929
930         /* batch packets in send buffer if possible */
931         msdp = &nvchan->msd;
932         if (msdp->pkt)
933                 msd_len = msdp->pkt->total_data_buflen;
934
935         try_batch =  msd_len > 0 && msdp->count < net_device->max_pkt;
936         if (try_batch && msd_len + pktlen + net_device->pkt_align <
937             net_device->send_section_size) {
938                 section_index = msdp->pkt->send_buf_index;
939
940         } else if (try_batch && msd_len + packet->rmsg_size <
941                    net_device->send_section_size) {
942                 section_index = msdp->pkt->send_buf_index;
943                 packet->cp_partial = true;
944
945         } else if (pktlen + net_device->pkt_align <
946                    net_device->send_section_size) {
947                 section_index = netvsc_get_next_send_section(net_device);
948                 if (unlikely(section_index == NETVSC_INVALID_INDEX)) {
949                         ++ndev_ctx->eth_stats.tx_send_full;
950                 } else {
951                         move_pkt_msd(&msd_send, &msd_skb, msdp);
952                         msd_len = 0;
953                 }
954         }
955
956         /* Keep aggregating only if stack says more data is coming
957          * and not doing mixed modes send and not flow blocked
958          */
959         xmit_more = skb->xmit_more &&
960                 !packet->cp_partial &&
961                 !netif_xmit_stopped(netdev_get_tx_queue(ndev, packet->q_idx));
962
963         if (section_index != NETVSC_INVALID_INDEX) {
964                 netvsc_copy_to_send_buf(net_device,
965                                         section_index, msd_len,
966                                         packet, rndis_msg, pb, xmit_more);
967
968                 packet->send_buf_index = section_index;
969
970                 if (packet->cp_partial) {
971                         packet->page_buf_cnt -= packet->rmsg_pgcnt;
972                         packet->total_data_buflen = msd_len + packet->rmsg_size;
973                 } else {
974                         packet->page_buf_cnt = 0;
975                         packet->total_data_buflen += msd_len;
976                 }
977
978                 if (msdp->pkt) {
979                         packet->total_packets += msdp->pkt->total_packets;
980                         packet->total_bytes += msdp->pkt->total_bytes;
981                 }
982
983                 if (msdp->skb)
984                         dev_consume_skb_any(msdp->skb);
985
986                 if (xmit_more) {
987                         msdp->skb = skb;
988                         msdp->pkt = packet;
989                         msdp->count++;
990                 } else {
991                         cur_send = packet;
992                         msdp->skb = NULL;
993                         msdp->pkt = NULL;
994                         msdp->count = 0;
995                 }
996         } else {
997                 move_pkt_msd(&msd_send, &msd_skb, msdp);
998                 cur_send = packet;
999         }
1000
1001         if (msd_send) {
1002                 int m_ret = netvsc_send_pkt(device, msd_send, net_device,
1003                                             NULL, msd_skb);
1004
1005                 if (m_ret != 0) {
1006                         netvsc_free_send_slot(net_device,
1007                                               msd_send->send_buf_index);
1008                         dev_kfree_skb_any(msd_skb);
1009                 }
1010         }
1011
1012         if (cur_send)
1013                 ret = netvsc_send_pkt(device, cur_send, net_device, pb, skb);
1014
1015         if (ret != 0 && section_index != NETVSC_INVALID_INDEX)
1016                 netvsc_free_send_slot(net_device, section_index);
1017
1018         return ret;
1019 }
1020
1021 /* Send pending recv completions */
1022 static int send_recv_completions(struct net_device *ndev,
1023                                  struct netvsc_device *nvdev,
1024                                  struct netvsc_channel *nvchan)
1025 {
1026         struct multi_recv_comp *mrc = &nvchan->mrc;
1027         struct recv_comp_msg {
1028                 struct nvsp_message_header hdr;
1029                 u32 status;
1030         }  __packed;
1031         struct recv_comp_msg msg = {
1032                 .hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE,
1033         };
1034         int ret;
1035
1036         while (mrc->first != mrc->next) {
1037                 const struct recv_comp_data *rcd
1038                         = mrc->slots + mrc->first;
1039
1040                 msg.status = rcd->status;
1041                 ret = vmbus_sendpacket(nvchan->channel, &msg, sizeof(msg),
1042                                        rcd->tid, VM_PKT_COMP, 0);
1043                 if (unlikely(ret)) {
1044                         struct net_device_context *ndev_ctx = netdev_priv(ndev);
1045
1046                         ++ndev_ctx->eth_stats.rx_comp_busy;
1047                         return ret;
1048                 }
1049
1050                 if (++mrc->first == nvdev->recv_completion_cnt)
1051                         mrc->first = 0;
1052         }
1053
1054         /* receive completion ring has been emptied */
1055         if (unlikely(nvdev->destroy))
1056                 wake_up(&nvdev->wait_drain);
1057
1058         return 0;
1059 }
1060
1061 /* Count how many receive completions are outstanding */
1062 static void recv_comp_slot_avail(const struct netvsc_device *nvdev,
1063                                  const struct multi_recv_comp *mrc,
1064                                  u32 *filled, u32 *avail)
1065 {
1066         u32 count = nvdev->recv_completion_cnt;
1067
1068         if (mrc->next >= mrc->first)
1069                 *filled = mrc->next - mrc->first;
1070         else
1071                 *filled = (count - mrc->first) + mrc->next;
1072
1073         *avail = count - *filled - 1;
1074 }
1075
1076 /* Add receive complete to ring to send to host. */
1077 static void enq_receive_complete(struct net_device *ndev,
1078                                  struct netvsc_device *nvdev, u16 q_idx,
1079                                  u64 tid, u32 status)
1080 {
1081         struct netvsc_channel *nvchan = &nvdev->chan_table[q_idx];
1082         struct multi_recv_comp *mrc = &nvchan->mrc;
1083         struct recv_comp_data *rcd;
1084         u32 filled, avail;
1085
1086         recv_comp_slot_avail(nvdev, mrc, &filled, &avail);
1087
1088         if (unlikely(filled > NAPI_POLL_WEIGHT)) {
1089                 send_recv_completions(ndev, nvdev, nvchan);
1090                 recv_comp_slot_avail(nvdev, mrc, &filled, &avail);
1091         }
1092
1093         if (unlikely(!avail)) {
1094                 netdev_err(ndev, "Recv_comp full buf q:%hd, tid:%llx\n",
1095                            q_idx, tid);
1096                 return;
1097         }
1098
1099         rcd = mrc->slots + mrc->next;
1100         rcd->tid = tid;
1101         rcd->status = status;
1102
1103         if (++mrc->next == nvdev->recv_completion_cnt)
1104                 mrc->next = 0;
1105 }
1106
1107 static int netvsc_receive(struct net_device *ndev,
1108                           struct netvsc_device *net_device,
1109                           struct net_device_context *net_device_ctx,
1110                           struct hv_device *device,
1111                           struct vmbus_channel *channel,
1112                           const struct vmpacket_descriptor *desc,
1113                           struct nvsp_message *nvsp)
1114 {
1115         const struct vmtransfer_page_packet_header *vmxferpage_packet
1116                 = container_of(desc, const struct vmtransfer_page_packet_header, d);
1117         u16 q_idx = channel->offermsg.offer.sub_channel_index;
1118         char *recv_buf = net_device->recv_buf;
1119         u32 status = NVSP_STAT_SUCCESS;
1120         int i;
1121         int count = 0;
1122
1123         /* Make sure this is a valid nvsp packet */
1124         if (unlikely(nvsp->hdr.msg_type != NVSP_MSG1_TYPE_SEND_RNDIS_PKT)) {
1125                 netif_err(net_device_ctx, rx_err, ndev,
1126                           "Unknown nvsp packet type received %u\n",
1127                           nvsp->hdr.msg_type);
1128                 return 0;
1129         }
1130
1131         if (unlikely(vmxferpage_packet->xfer_pageset_id != NETVSC_RECEIVE_BUFFER_ID)) {
1132                 netif_err(net_device_ctx, rx_err, ndev,
1133                           "Invalid xfer page set id - expecting %x got %x\n",
1134                           NETVSC_RECEIVE_BUFFER_ID,
1135                           vmxferpage_packet->xfer_pageset_id);
1136                 return 0;
1137         }
1138
1139         count = vmxferpage_packet->range_cnt;
1140
1141         /* Each range represents 1 RNDIS pkt that contains 1 ethernet frame */
1142         for (i = 0; i < count; i++) {
1143                 void *data = recv_buf
1144                         + vmxferpage_packet->ranges[i].byte_offset;
1145                 u32 buflen = vmxferpage_packet->ranges[i].byte_count;
1146
1147                 /* Pass it to the upper layer */
1148                 status = rndis_filter_receive(ndev, net_device, device,
1149                                               channel, data, buflen);
1150         }
1151
1152         enq_receive_complete(ndev, net_device, q_idx,
1153                              vmxferpage_packet->d.trans_id, status);
1154
1155         return count;
1156 }
1157
1158 static void netvsc_send_table(struct hv_device *hdev,
1159                               struct nvsp_message *nvmsg)
1160 {
1161         struct net_device *ndev = hv_get_drvdata(hdev);
1162         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1163         int i;
1164         u32 count, *tab;
1165
1166         count = nvmsg->msg.v5_msg.send_table.count;
1167         if (count != VRSS_SEND_TAB_SIZE) {
1168                 netdev_err(ndev, "Received wrong send-table size:%u\n", count);
1169                 return;
1170         }
1171
1172         tab = (u32 *)((unsigned long)&nvmsg->msg.v5_msg.send_table +
1173                       nvmsg->msg.v5_msg.send_table.offset);
1174
1175         for (i = 0; i < count; i++)
1176                 net_device_ctx->tx_table[i] = tab[i];
1177 }
1178
1179 static void netvsc_send_vf(struct net_device_context *net_device_ctx,
1180                            struct nvsp_message *nvmsg)
1181 {
1182         net_device_ctx->vf_alloc = nvmsg->msg.v4_msg.vf_assoc.allocated;
1183         net_device_ctx->vf_serial = nvmsg->msg.v4_msg.vf_assoc.serial;
1184 }
1185
1186 static inline void netvsc_receive_inband(struct hv_device *hdev,
1187                                  struct net_device_context *net_device_ctx,
1188                                  struct nvsp_message *nvmsg)
1189 {
1190         switch (nvmsg->hdr.msg_type) {
1191         case NVSP_MSG5_TYPE_SEND_INDIRECTION_TABLE:
1192                 netvsc_send_table(hdev, nvmsg);
1193                 break;
1194
1195         case NVSP_MSG4_TYPE_SEND_VF_ASSOCIATION:
1196                 netvsc_send_vf(net_device_ctx, nvmsg);
1197                 break;
1198         }
1199 }
1200
1201 static int netvsc_process_raw_pkt(struct hv_device *device,
1202                                   struct vmbus_channel *channel,
1203                                   struct netvsc_device *net_device,
1204                                   struct net_device *ndev,
1205                                   const struct vmpacket_descriptor *desc,
1206                                   int budget)
1207 {
1208         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1209         struct nvsp_message *nvmsg = hv_pkt_data(desc);
1210
1211         switch (desc->type) {
1212         case VM_PKT_COMP:
1213                 netvsc_send_completion(net_device, channel, device,
1214                                        desc, budget);
1215                 break;
1216
1217         case VM_PKT_DATA_USING_XFER_PAGES:
1218                 return netvsc_receive(ndev, net_device, net_device_ctx,
1219                                       device, channel, desc, nvmsg);
1220                 break;
1221
1222         case VM_PKT_DATA_INBAND:
1223                 netvsc_receive_inband(device, net_device_ctx, nvmsg);
1224                 break;
1225
1226         default:
1227                 netdev_err(ndev, "unhandled packet type %d, tid %llx\n",
1228                            desc->type, desc->trans_id);
1229                 break;
1230         }
1231
1232         return 0;
1233 }
1234
1235 static struct hv_device *netvsc_channel_to_device(struct vmbus_channel *channel)
1236 {
1237         struct vmbus_channel *primary = channel->primary_channel;
1238
1239         return primary ? primary->device_obj : channel->device_obj;
1240 }
1241
1242 /* Network processing softirq
1243  * Process data in incoming ring buffer from host
1244  * Stops when ring is empty or budget is met or exceeded.
1245  */
1246 int netvsc_poll(struct napi_struct *napi, int budget)
1247 {
1248         struct netvsc_channel *nvchan
1249                 = container_of(napi, struct netvsc_channel, napi);
1250         struct netvsc_device *net_device = nvchan->net_device;
1251         struct vmbus_channel *channel = nvchan->channel;
1252         struct hv_device *device = netvsc_channel_to_device(channel);
1253         struct net_device *ndev = hv_get_drvdata(device);
1254         int work_done = 0;
1255         int ret;
1256
1257         /* If starting a new interval */
1258         if (!nvchan->desc)
1259                 nvchan->desc = hv_pkt_iter_first(channel);
1260
1261         while (nvchan->desc && work_done < budget) {
1262                 work_done += netvsc_process_raw_pkt(device, channel, net_device,
1263                                                     ndev, nvchan->desc, budget);
1264                 nvchan->desc = hv_pkt_iter_next(channel, nvchan->desc);
1265         }
1266
1267         /* Send any pending receive completions */
1268         ret = send_recv_completions(ndev, net_device, nvchan);
1269
1270         /* If it did not exhaust NAPI budget this time
1271          *  and not doing busy poll
1272          * then re-enable host interrupts
1273          *  and reschedule if ring is not empty
1274          *   or sending receive completion failed.
1275          */
1276         if (work_done < budget &&
1277             napi_complete_done(napi, work_done) &&
1278             (ret || hv_end_read(&channel->inbound)) &&
1279             napi_schedule_prep(napi)) {
1280                 hv_begin_read(&channel->inbound);
1281                 __napi_schedule(napi);
1282         }
1283
1284         /* Driver may overshoot since multiple packets per descriptor */
1285         return min(work_done, budget);
1286 }
1287
1288 /* Call back when data is available in host ring buffer.
1289  * Processing is deferred until network softirq (NAPI)
1290  */
1291 void netvsc_channel_cb(void *context)
1292 {
1293         struct netvsc_channel *nvchan = context;
1294         struct vmbus_channel *channel = nvchan->channel;
1295         struct hv_ring_buffer_info *rbi = &channel->inbound;
1296
1297         /* preload first vmpacket descriptor */
1298         prefetch(hv_get_ring_buffer(rbi) + rbi->priv_read_index);
1299
1300         if (napi_schedule_prep(&nvchan->napi)) {
1301                 /* disable interupts from host */
1302                 hv_begin_read(rbi);
1303
1304                 __napi_schedule_irqoff(&nvchan->napi);
1305         }
1306 }
1307
1308 /*
1309  * netvsc_device_add - Callback when the device belonging to this
1310  * driver is added
1311  */
1312 struct netvsc_device *netvsc_device_add(struct hv_device *device,
1313                                 const struct netvsc_device_info *device_info)
1314 {
1315         int i, ret = 0;
1316         int ring_size = device_info->ring_size;
1317         struct netvsc_device *net_device;
1318         struct net_device *ndev = hv_get_drvdata(device);
1319         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1320
1321         net_device = alloc_net_device();
1322         if (!net_device)
1323                 return ERR_PTR(-ENOMEM);
1324
1325         for (i = 0; i < VRSS_SEND_TAB_SIZE; i++)
1326                 net_device_ctx->tx_table[i] = 0;
1327
1328         net_device->ring_size = ring_size;
1329
1330         /* Because the device uses NAPI, all the interrupt batching and
1331          * control is done via Net softirq, not the channel handling
1332          */
1333         set_channel_read_mode(device->channel, HV_CALL_ISR);
1334
1335         /* If we're reopening the device we may have multiple queues, fill the
1336          * chn_table with the default channel to use it before subchannels are
1337          * opened.
1338          * Initialize the channel state before we open;
1339          * we can be interrupted as soon as we open the channel.
1340          */
1341
1342         for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
1343                 struct netvsc_channel *nvchan = &net_device->chan_table[i];
1344
1345                 nvchan->channel = device->channel;
1346                 nvchan->net_device = net_device;
1347                 u64_stats_init(&nvchan->tx_stats.syncp);
1348                 u64_stats_init(&nvchan->rx_stats.syncp);
1349         }
1350
1351         /* Enable NAPI handler before init callbacks */
1352         netif_napi_add(ndev, &net_device->chan_table[0].napi,
1353                        netvsc_poll, NAPI_POLL_WEIGHT);
1354
1355         /* Open the channel */
1356         ret = vmbus_open(device->channel, ring_size * PAGE_SIZE,
1357                          ring_size * PAGE_SIZE, NULL, 0,
1358                          netvsc_channel_cb,
1359                          net_device->chan_table);
1360
1361         if (ret != 0) {
1362                 netdev_err(ndev, "unable to open channel: %d\n", ret);
1363                 goto cleanup;
1364         }
1365
1366         /* Channel is opened */
1367         netdev_dbg(ndev, "hv_netvsc channel opened successfully\n");
1368
1369         napi_enable(&net_device->chan_table[0].napi);
1370
1371         /* Connect with the NetVsp */
1372         ret = netvsc_connect_vsp(device, net_device, device_info);
1373         if (ret != 0) {
1374                 netdev_err(ndev,
1375                         "unable to connect to NetVSP - %d\n", ret);
1376                 goto close;
1377         }
1378
1379         /* Writing nvdev pointer unlocks netvsc_send(), make sure chn_table is
1380          * populated.
1381          */
1382         rcu_assign_pointer(net_device_ctx->nvdev, net_device);
1383
1384         return net_device;
1385
1386 close:
1387         RCU_INIT_POINTER(net_device_ctx->nvdev, NULL);
1388         napi_disable(&net_device->chan_table[0].napi);
1389
1390         /* Now, we can close the channel safely */
1391         vmbus_close(device->channel);
1392
1393 cleanup:
1394         netif_napi_del(&net_device->chan_table[0].napi);
1395         free_netvsc_device(&net_device->rcu);
1396
1397         return ERR_PTR(ret);
1398 }