Merge tag 'libnvdimm-for-5.18' of git://git.kernel.org/pub/scm/linux/kernel/git/nvdim...
[linux-2.6-microblaze.git] / drivers / net / hyperv / netvsc.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2009, Microsoft Corporation.
4  *
5  * Authors:
6  *   Haiyang Zhang <haiyangz@microsoft.com>
7  *   Hank Janssen  <hjanssen@microsoft.com>
8  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10
11 #include <linux/kernel.h>
12 #include <linux/sched.h>
13 #include <linux/wait.h>
14 #include <linux/mm.h>
15 #include <linux/delay.h>
16 #include <linux/io.h>
17 #include <linux/slab.h>
18 #include <linux/netdevice.h>
19 #include <linux/if_ether.h>
20 #include <linux/vmalloc.h>
21 #include <linux/rtnetlink.h>
22 #include <linux/prefetch.h>
23
24 #include <asm/sync_bitops.h>
25 #include <asm/mshyperv.h>
26
27 #include "hyperv_net.h"
28 #include "netvsc_trace.h"
29
30 /*
31  * Switch the data path from the synthetic interface to the VF
32  * interface.
33  */
34 int netvsc_switch_datapath(struct net_device *ndev, bool vf)
35 {
36         struct net_device_context *net_device_ctx = netdev_priv(ndev);
37         struct hv_device *dev = net_device_ctx->device_ctx;
38         struct netvsc_device *nv_dev = rtnl_dereference(net_device_ctx->nvdev);
39         struct nvsp_message *init_pkt = &nv_dev->channel_init_pkt;
40         int ret, retry = 0;
41
42         /* Block sending traffic to VF if it's about to be gone */
43         if (!vf)
44                 net_device_ctx->data_path_is_vf = vf;
45
46         memset(init_pkt, 0, sizeof(struct nvsp_message));
47         init_pkt->hdr.msg_type = NVSP_MSG4_TYPE_SWITCH_DATA_PATH;
48         if (vf)
49                 init_pkt->msg.v4_msg.active_dp.active_datapath =
50                         NVSP_DATAPATH_VF;
51         else
52                 init_pkt->msg.v4_msg.active_dp.active_datapath =
53                         NVSP_DATAPATH_SYNTHETIC;
54
55 again:
56         trace_nvsp_send(ndev, init_pkt);
57
58         ret = vmbus_sendpacket(dev->channel, init_pkt,
59                                sizeof(struct nvsp_message),
60                                (unsigned long)init_pkt, VM_PKT_DATA_INBAND,
61                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
62
63         /* If failed to switch to/from VF, let data_path_is_vf stay false,
64          * so we use synthetic path to send data.
65          */
66         if (ret) {
67                 if (ret != -EAGAIN) {
68                         netdev_err(ndev,
69                                    "Unable to send sw datapath msg, err: %d\n",
70                                    ret);
71                         return ret;
72                 }
73
74                 if (retry++ < RETRY_MAX) {
75                         usleep_range(RETRY_US_LO, RETRY_US_HI);
76                         goto again;
77                 } else {
78                         netdev_err(
79                                 ndev,
80                                 "Retry failed to send sw datapath msg, err: %d\n",
81                                 ret);
82                         return ret;
83                 }
84         }
85
86         wait_for_completion(&nv_dev->channel_init_wait);
87         net_device_ctx->data_path_is_vf = vf;
88
89         return 0;
90 }
91
92 /* Worker to setup sub channels on initial setup
93  * Initial hotplug event occurs in softirq context
94  * and can't wait for channels.
95  */
96 static void netvsc_subchan_work(struct work_struct *w)
97 {
98         struct netvsc_device *nvdev =
99                 container_of(w, struct netvsc_device, subchan_work);
100         struct rndis_device *rdev;
101         int i, ret;
102
103         /* Avoid deadlock with device removal already under RTNL */
104         if (!rtnl_trylock()) {
105                 schedule_work(w);
106                 return;
107         }
108
109         rdev = nvdev->extension;
110         if (rdev) {
111                 ret = rndis_set_subchannel(rdev->ndev, nvdev, NULL);
112                 if (ret == 0) {
113                         netif_device_attach(rdev->ndev);
114                 } else {
115                         /* fallback to only primary channel */
116                         for (i = 1; i < nvdev->num_chn; i++)
117                                 netif_napi_del(&nvdev->chan_table[i].napi);
118
119                         nvdev->max_chn = 1;
120                         nvdev->num_chn = 1;
121                 }
122         }
123
124         rtnl_unlock();
125 }
126
127 static struct netvsc_device *alloc_net_device(void)
128 {
129         struct netvsc_device *net_device;
130
131         net_device = kzalloc(sizeof(struct netvsc_device), GFP_KERNEL);
132         if (!net_device)
133                 return NULL;
134
135         init_waitqueue_head(&net_device->wait_drain);
136         net_device->destroy = false;
137         net_device->tx_disable = true;
138
139         net_device->max_pkt = RNDIS_MAX_PKT_DEFAULT;
140         net_device->pkt_align = RNDIS_PKT_ALIGN_DEFAULT;
141
142         init_completion(&net_device->channel_init_wait);
143         init_waitqueue_head(&net_device->subchan_open);
144         INIT_WORK(&net_device->subchan_work, netvsc_subchan_work);
145
146         return net_device;
147 }
148
149 static void free_netvsc_device(struct rcu_head *head)
150 {
151         struct netvsc_device *nvdev
152                 = container_of(head, struct netvsc_device, rcu);
153         int i;
154
155         kfree(nvdev->extension);
156
157         if (nvdev->recv_original_buf)
158                 vfree(nvdev->recv_original_buf);
159         else
160                 vfree(nvdev->recv_buf);
161
162         if (nvdev->send_original_buf)
163                 vfree(nvdev->send_original_buf);
164         else
165                 vfree(nvdev->send_buf);
166
167         bitmap_free(nvdev->send_section_map);
168
169         for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
170                 xdp_rxq_info_unreg(&nvdev->chan_table[i].xdp_rxq);
171                 kfree(nvdev->chan_table[i].recv_buf);
172                 vfree(nvdev->chan_table[i].mrc.slots);
173         }
174
175         kfree(nvdev);
176 }
177
178 static void free_netvsc_device_rcu(struct netvsc_device *nvdev)
179 {
180         call_rcu(&nvdev->rcu, free_netvsc_device);
181 }
182
183 static void netvsc_revoke_recv_buf(struct hv_device *device,
184                                    struct netvsc_device *net_device,
185                                    struct net_device *ndev)
186 {
187         struct nvsp_message *revoke_packet;
188         int ret;
189
190         /*
191          * If we got a section count, it means we received a
192          * SendReceiveBufferComplete msg (ie sent
193          * NvspMessage1TypeSendReceiveBuffer msg) therefore, we need
194          * to send a revoke msg here
195          */
196         if (net_device->recv_section_cnt) {
197                 /* Send the revoke receive buffer */
198                 revoke_packet = &net_device->revoke_packet;
199                 memset(revoke_packet, 0, sizeof(struct nvsp_message));
200
201                 revoke_packet->hdr.msg_type =
202                         NVSP_MSG1_TYPE_REVOKE_RECV_BUF;
203                 revoke_packet->msg.v1_msg.
204                 revoke_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
205
206                 trace_nvsp_send(ndev, revoke_packet);
207
208                 ret = vmbus_sendpacket(device->channel,
209                                        revoke_packet,
210                                        sizeof(struct nvsp_message),
211                                        VMBUS_RQST_ID_NO_RESPONSE,
212                                        VM_PKT_DATA_INBAND, 0);
213                 /* If the failure is because the channel is rescinded;
214                  * ignore the failure since we cannot send on a rescinded
215                  * channel. This would allow us to properly cleanup
216                  * even when the channel is rescinded.
217                  */
218                 if (device->channel->rescind)
219                         ret = 0;
220                 /*
221                  * If we failed here, we might as well return and
222                  * have a leak rather than continue and a bugchk
223                  */
224                 if (ret != 0) {
225                         netdev_err(ndev, "unable to send "
226                                 "revoke receive buffer to netvsp\n");
227                         return;
228                 }
229                 net_device->recv_section_cnt = 0;
230         }
231 }
232
233 static void netvsc_revoke_send_buf(struct hv_device *device,
234                                    struct netvsc_device *net_device,
235                                    struct net_device *ndev)
236 {
237         struct nvsp_message *revoke_packet;
238         int ret;
239
240         /* Deal with the send buffer we may have setup.
241          * If we got a  send section size, it means we received a
242          * NVSP_MSG1_TYPE_SEND_SEND_BUF_COMPLETE msg (ie sent
243          * NVSP_MSG1_TYPE_SEND_SEND_BUF msg) therefore, we need
244          * to send a revoke msg here
245          */
246         if (net_device->send_section_cnt) {
247                 /* Send the revoke receive buffer */
248                 revoke_packet = &net_device->revoke_packet;
249                 memset(revoke_packet, 0, sizeof(struct nvsp_message));
250
251                 revoke_packet->hdr.msg_type =
252                         NVSP_MSG1_TYPE_REVOKE_SEND_BUF;
253                 revoke_packet->msg.v1_msg.revoke_send_buf.id =
254                         NETVSC_SEND_BUFFER_ID;
255
256                 trace_nvsp_send(ndev, revoke_packet);
257
258                 ret = vmbus_sendpacket(device->channel,
259                                        revoke_packet,
260                                        sizeof(struct nvsp_message),
261                                        VMBUS_RQST_ID_NO_RESPONSE,
262                                        VM_PKT_DATA_INBAND, 0);
263
264                 /* If the failure is because the channel is rescinded;
265                  * ignore the failure since we cannot send on a rescinded
266                  * channel. This would allow us to properly cleanup
267                  * even when the channel is rescinded.
268                  */
269                 if (device->channel->rescind)
270                         ret = 0;
271
272                 /* If we failed here, we might as well return and
273                  * have a leak rather than continue and a bugchk
274                  */
275                 if (ret != 0) {
276                         netdev_err(ndev, "unable to send "
277                                    "revoke send buffer to netvsp\n");
278                         return;
279                 }
280                 net_device->send_section_cnt = 0;
281         }
282 }
283
284 static void netvsc_teardown_recv_gpadl(struct hv_device *device,
285                                        struct netvsc_device *net_device,
286                                        struct net_device *ndev)
287 {
288         int ret;
289
290         if (net_device->recv_buf_gpadl_handle.gpadl_handle) {
291                 ret = vmbus_teardown_gpadl(device->channel,
292                                            &net_device->recv_buf_gpadl_handle);
293
294                 /* If we failed here, we might as well return and have a leak
295                  * rather than continue and a bugchk
296                  */
297                 if (ret != 0) {
298                         netdev_err(ndev,
299                                    "unable to teardown receive buffer's gpadl\n");
300                         return;
301                 }
302         }
303 }
304
305 static void netvsc_teardown_send_gpadl(struct hv_device *device,
306                                        struct netvsc_device *net_device,
307                                        struct net_device *ndev)
308 {
309         int ret;
310
311         if (net_device->send_buf_gpadl_handle.gpadl_handle) {
312                 ret = vmbus_teardown_gpadl(device->channel,
313                                            &net_device->send_buf_gpadl_handle);
314
315                 /* If we failed here, we might as well return and have a leak
316                  * rather than continue and a bugchk
317                  */
318                 if (ret != 0) {
319                         netdev_err(ndev,
320                                    "unable to teardown send buffer's gpadl\n");
321                         return;
322                 }
323         }
324 }
325
326 int netvsc_alloc_recv_comp_ring(struct netvsc_device *net_device, u32 q_idx)
327 {
328         struct netvsc_channel *nvchan = &net_device->chan_table[q_idx];
329         int node = cpu_to_node(nvchan->channel->target_cpu);
330         size_t size;
331
332         size = net_device->recv_completion_cnt * sizeof(struct recv_comp_data);
333         nvchan->mrc.slots = vzalloc_node(size, node);
334         if (!nvchan->mrc.slots)
335                 nvchan->mrc.slots = vzalloc(size);
336
337         return nvchan->mrc.slots ? 0 : -ENOMEM;
338 }
339
340 static int netvsc_init_buf(struct hv_device *device,
341                            struct netvsc_device *net_device,
342                            const struct netvsc_device_info *device_info)
343 {
344         struct nvsp_1_message_send_receive_buffer_complete *resp;
345         struct net_device *ndev = hv_get_drvdata(device);
346         struct nvsp_message *init_packet;
347         unsigned int buf_size;
348         int i, ret = 0;
349         void *vaddr;
350
351         /* Get receive buffer area. */
352         buf_size = device_info->recv_sections * device_info->recv_section_size;
353         buf_size = roundup(buf_size, PAGE_SIZE);
354
355         /* Legacy hosts only allow smaller receive buffer */
356         if (net_device->nvsp_version <= NVSP_PROTOCOL_VERSION_2)
357                 buf_size = min_t(unsigned int, buf_size,
358                                  NETVSC_RECEIVE_BUFFER_SIZE_LEGACY);
359
360         net_device->recv_buf = vzalloc(buf_size);
361         if (!net_device->recv_buf) {
362                 netdev_err(ndev,
363                            "unable to allocate receive buffer of size %u\n",
364                            buf_size);
365                 ret = -ENOMEM;
366                 goto cleanup;
367         }
368
369         net_device->recv_buf_size = buf_size;
370
371         /*
372          * Establish the gpadl handle for this buffer on this
373          * channel.  Note: This call uses the vmbus connection rather
374          * than the channel to establish the gpadl handle.
375          */
376         ret = vmbus_establish_gpadl(device->channel, net_device->recv_buf,
377                                     buf_size,
378                                     &net_device->recv_buf_gpadl_handle);
379         if (ret != 0) {
380                 netdev_err(ndev,
381                         "unable to establish receive buffer's gpadl\n");
382                 goto cleanup;
383         }
384
385         if (hv_isolation_type_snp()) {
386                 vaddr = hv_map_memory(net_device->recv_buf, buf_size);
387                 if (!vaddr) {
388                         ret = -ENOMEM;
389                         goto cleanup;
390                 }
391
392                 net_device->recv_original_buf = net_device->recv_buf;
393                 net_device->recv_buf = vaddr;
394         }
395
396         /* Notify the NetVsp of the gpadl handle */
397         init_packet = &net_device->channel_init_pkt;
398         memset(init_packet, 0, sizeof(struct nvsp_message));
399         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_RECV_BUF;
400         init_packet->msg.v1_msg.send_recv_buf.
401                 gpadl_handle = net_device->recv_buf_gpadl_handle.gpadl_handle;
402         init_packet->msg.v1_msg.
403                 send_recv_buf.id = NETVSC_RECEIVE_BUFFER_ID;
404
405         trace_nvsp_send(ndev, init_packet);
406
407         /* Send the gpadl notification request */
408         ret = vmbus_sendpacket(device->channel, init_packet,
409                                sizeof(struct nvsp_message),
410                                (unsigned long)init_packet,
411                                VM_PKT_DATA_INBAND,
412                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
413         if (ret != 0) {
414                 netdev_err(ndev,
415                         "unable to send receive buffer's gpadl to netvsp\n");
416                 goto cleanup;
417         }
418
419         wait_for_completion(&net_device->channel_init_wait);
420
421         /* Check the response */
422         resp = &init_packet->msg.v1_msg.send_recv_buf_complete;
423         if (resp->status != NVSP_STAT_SUCCESS) {
424                 netdev_err(ndev,
425                            "Unable to complete receive buffer initialization with NetVsp - status %d\n",
426                            resp->status);
427                 ret = -EINVAL;
428                 goto cleanup;
429         }
430
431         /* Parse the response */
432         netdev_dbg(ndev, "Receive sections: %u sub_allocs: size %u count: %u\n",
433                    resp->num_sections, resp->sections[0].sub_alloc_size,
434                    resp->sections[0].num_sub_allocs);
435
436         /* There should only be one section for the entire receive buffer */
437         if (resp->num_sections != 1 || resp->sections[0].offset != 0) {
438                 ret = -EINVAL;
439                 goto cleanup;
440         }
441
442         net_device->recv_section_size = resp->sections[0].sub_alloc_size;
443         net_device->recv_section_cnt = resp->sections[0].num_sub_allocs;
444
445         /* Ensure buffer will not overflow */
446         if (net_device->recv_section_size < NETVSC_MTU_MIN || (u64)net_device->recv_section_size *
447             (u64)net_device->recv_section_cnt > (u64)buf_size) {
448                 netdev_err(ndev, "invalid recv_section_size %u\n",
449                            net_device->recv_section_size);
450                 ret = -EINVAL;
451                 goto cleanup;
452         }
453
454         for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
455                 struct netvsc_channel *nvchan = &net_device->chan_table[i];
456
457                 nvchan->recv_buf = kzalloc(net_device->recv_section_size, GFP_KERNEL);
458                 if (nvchan->recv_buf == NULL) {
459                         ret = -ENOMEM;
460                         goto cleanup;
461                 }
462         }
463
464         /* Setup receive completion ring.
465          * Add 1 to the recv_section_cnt because at least one entry in a
466          * ring buffer has to be empty.
467          */
468         net_device->recv_completion_cnt = net_device->recv_section_cnt + 1;
469         ret = netvsc_alloc_recv_comp_ring(net_device, 0);
470         if (ret)
471                 goto cleanup;
472
473         /* Now setup the send buffer. */
474         buf_size = device_info->send_sections * device_info->send_section_size;
475         buf_size = round_up(buf_size, PAGE_SIZE);
476
477         net_device->send_buf = vzalloc(buf_size);
478         if (!net_device->send_buf) {
479                 netdev_err(ndev, "unable to allocate send buffer of size %u\n",
480                            buf_size);
481                 ret = -ENOMEM;
482                 goto cleanup;
483         }
484         net_device->send_buf_size = buf_size;
485
486         /* Establish the gpadl handle for this buffer on this
487          * channel.  Note: This call uses the vmbus connection rather
488          * than the channel to establish the gpadl handle.
489          */
490         ret = vmbus_establish_gpadl(device->channel, net_device->send_buf,
491                                     buf_size,
492                                     &net_device->send_buf_gpadl_handle);
493         if (ret != 0) {
494                 netdev_err(ndev,
495                            "unable to establish send buffer's gpadl\n");
496                 goto cleanup;
497         }
498
499         if (hv_isolation_type_snp()) {
500                 vaddr = hv_map_memory(net_device->send_buf, buf_size);
501                 if (!vaddr) {
502                         ret = -ENOMEM;
503                         goto cleanup;
504                 }
505
506                 net_device->send_original_buf = net_device->send_buf;
507                 net_device->send_buf = vaddr;
508         }
509
510         /* Notify the NetVsp of the gpadl handle */
511         init_packet = &net_device->channel_init_pkt;
512         memset(init_packet, 0, sizeof(struct nvsp_message));
513         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_SEND_BUF;
514         init_packet->msg.v1_msg.send_send_buf.gpadl_handle =
515                 net_device->send_buf_gpadl_handle.gpadl_handle;
516         init_packet->msg.v1_msg.send_send_buf.id = NETVSC_SEND_BUFFER_ID;
517
518         trace_nvsp_send(ndev, init_packet);
519
520         /* Send the gpadl notification request */
521         ret = vmbus_sendpacket(device->channel, init_packet,
522                                sizeof(struct nvsp_message),
523                                (unsigned long)init_packet,
524                                VM_PKT_DATA_INBAND,
525                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
526         if (ret != 0) {
527                 netdev_err(ndev,
528                            "unable to send send buffer's gpadl to netvsp\n");
529                 goto cleanup;
530         }
531
532         wait_for_completion(&net_device->channel_init_wait);
533
534         /* Check the response */
535         if (init_packet->msg.v1_msg.
536             send_send_buf_complete.status != NVSP_STAT_SUCCESS) {
537                 netdev_err(ndev, "Unable to complete send buffer "
538                            "initialization with NetVsp - status %d\n",
539                            init_packet->msg.v1_msg.
540                            send_send_buf_complete.status);
541                 ret = -EINVAL;
542                 goto cleanup;
543         }
544
545         /* Parse the response */
546         net_device->send_section_size = init_packet->msg.
547                                 v1_msg.send_send_buf_complete.section_size;
548         if (net_device->send_section_size < NETVSC_MTU_MIN) {
549                 netdev_err(ndev, "invalid send_section_size %u\n",
550                            net_device->send_section_size);
551                 ret = -EINVAL;
552                 goto cleanup;
553         }
554
555         /* Section count is simply the size divided by the section size. */
556         net_device->send_section_cnt = buf_size / net_device->send_section_size;
557
558         netdev_dbg(ndev, "Send section size: %d, Section count:%d\n",
559                    net_device->send_section_size, net_device->send_section_cnt);
560
561         /* Setup state for managing the send buffer. */
562         net_device->send_section_map = bitmap_zalloc(net_device->send_section_cnt,
563                                                      GFP_KERNEL);
564         if (!net_device->send_section_map) {
565                 ret = -ENOMEM;
566                 goto cleanup;
567         }
568
569         goto exit;
570
571 cleanup:
572         netvsc_revoke_recv_buf(device, net_device, ndev);
573         netvsc_revoke_send_buf(device, net_device, ndev);
574         netvsc_teardown_recv_gpadl(device, net_device, ndev);
575         netvsc_teardown_send_gpadl(device, net_device, ndev);
576
577 exit:
578         return ret;
579 }
580
581 /* Negotiate NVSP protocol version */
582 static int negotiate_nvsp_ver(struct hv_device *device,
583                               struct netvsc_device *net_device,
584                               struct nvsp_message *init_packet,
585                               u32 nvsp_ver)
586 {
587         struct net_device *ndev = hv_get_drvdata(device);
588         int ret;
589
590         memset(init_packet, 0, sizeof(struct nvsp_message));
591         init_packet->hdr.msg_type = NVSP_MSG_TYPE_INIT;
592         init_packet->msg.init_msg.init.min_protocol_ver = nvsp_ver;
593         init_packet->msg.init_msg.init.max_protocol_ver = nvsp_ver;
594         trace_nvsp_send(ndev, init_packet);
595
596         /* Send the init request */
597         ret = vmbus_sendpacket(device->channel, init_packet,
598                                sizeof(struct nvsp_message),
599                                (unsigned long)init_packet,
600                                VM_PKT_DATA_INBAND,
601                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
602
603         if (ret != 0)
604                 return ret;
605
606         wait_for_completion(&net_device->channel_init_wait);
607
608         if (init_packet->msg.init_msg.init_complete.status !=
609             NVSP_STAT_SUCCESS)
610                 return -EINVAL;
611
612         if (nvsp_ver == NVSP_PROTOCOL_VERSION_1)
613                 return 0;
614
615         /* NVSPv2 or later: Send NDIS config */
616         memset(init_packet, 0, sizeof(struct nvsp_message));
617         init_packet->hdr.msg_type = NVSP_MSG2_TYPE_SEND_NDIS_CONFIG;
618         init_packet->msg.v2_msg.send_ndis_config.mtu = ndev->mtu + ETH_HLEN;
619         init_packet->msg.v2_msg.send_ndis_config.capability.ieee8021q = 1;
620
621         if (nvsp_ver >= NVSP_PROTOCOL_VERSION_5) {
622                 if (hv_is_isolation_supported())
623                         netdev_info(ndev, "SR-IOV not advertised by guests on the host supporting isolation\n");
624                 else
625                         init_packet->msg.v2_msg.send_ndis_config.capability.sriov = 1;
626
627                 /* Teaming bit is needed to receive link speed updates */
628                 init_packet->msg.v2_msg.send_ndis_config.capability.teaming = 1;
629         }
630
631         if (nvsp_ver >= NVSP_PROTOCOL_VERSION_61)
632                 init_packet->msg.v2_msg.send_ndis_config.capability.rsc = 1;
633
634         trace_nvsp_send(ndev, init_packet);
635
636         ret = vmbus_sendpacket(device->channel, init_packet,
637                                 sizeof(struct nvsp_message),
638                                 VMBUS_RQST_ID_NO_RESPONSE,
639                                 VM_PKT_DATA_INBAND, 0);
640
641         return ret;
642 }
643
644 static int netvsc_connect_vsp(struct hv_device *device,
645                               struct netvsc_device *net_device,
646                               const struct netvsc_device_info *device_info)
647 {
648         struct net_device *ndev = hv_get_drvdata(device);
649         static const u32 ver_list[] = {
650                 NVSP_PROTOCOL_VERSION_1, NVSP_PROTOCOL_VERSION_2,
651                 NVSP_PROTOCOL_VERSION_4, NVSP_PROTOCOL_VERSION_5,
652                 NVSP_PROTOCOL_VERSION_6, NVSP_PROTOCOL_VERSION_61
653         };
654         struct nvsp_message *init_packet;
655         int ndis_version, i, ret;
656
657         init_packet = &net_device->channel_init_pkt;
658
659         /* Negotiate the latest NVSP protocol supported */
660         for (i = ARRAY_SIZE(ver_list) - 1; i >= 0; i--)
661                 if (negotiate_nvsp_ver(device, net_device, init_packet,
662                                        ver_list[i])  == 0) {
663                         net_device->nvsp_version = ver_list[i];
664                         break;
665                 }
666
667         if (i < 0) {
668                 ret = -EPROTO;
669                 goto cleanup;
670         }
671
672         if (hv_is_isolation_supported() && net_device->nvsp_version < NVSP_PROTOCOL_VERSION_61) {
673                 netdev_err(ndev, "Invalid NVSP version 0x%x (expected >= 0x%x) from the host supporting isolation\n",
674                            net_device->nvsp_version, NVSP_PROTOCOL_VERSION_61);
675                 ret = -EPROTO;
676                 goto cleanup;
677         }
678
679         pr_debug("Negotiated NVSP version:%x\n", net_device->nvsp_version);
680
681         /* Send the ndis version */
682         memset(init_packet, 0, sizeof(struct nvsp_message));
683
684         if (net_device->nvsp_version <= NVSP_PROTOCOL_VERSION_4)
685                 ndis_version = 0x00060001;
686         else
687                 ndis_version = 0x0006001e;
688
689         init_packet->hdr.msg_type = NVSP_MSG1_TYPE_SEND_NDIS_VER;
690         init_packet->msg.v1_msg.
691                 send_ndis_ver.ndis_major_ver =
692                                 (ndis_version & 0xFFFF0000) >> 16;
693         init_packet->msg.v1_msg.
694                 send_ndis_ver.ndis_minor_ver =
695                                 ndis_version & 0xFFFF;
696
697         trace_nvsp_send(ndev, init_packet);
698
699         /* Send the init request */
700         ret = vmbus_sendpacket(device->channel, init_packet,
701                                 sizeof(struct nvsp_message),
702                                 VMBUS_RQST_ID_NO_RESPONSE,
703                                 VM_PKT_DATA_INBAND, 0);
704         if (ret != 0)
705                 goto cleanup;
706
707
708         ret = netvsc_init_buf(device, net_device, device_info);
709
710 cleanup:
711         return ret;
712 }
713
714 /*
715  * netvsc_device_remove - Callback when the root bus device is removed
716  */
717 void netvsc_device_remove(struct hv_device *device)
718 {
719         struct net_device *ndev = hv_get_drvdata(device);
720         struct net_device_context *net_device_ctx = netdev_priv(ndev);
721         struct netvsc_device *net_device
722                 = rtnl_dereference(net_device_ctx->nvdev);
723         int i;
724
725         /*
726          * Revoke receive buffer. If host is pre-Win2016 then tear down
727          * receive buffer GPADL. Do the same for send buffer.
728          */
729         netvsc_revoke_recv_buf(device, net_device, ndev);
730         if (vmbus_proto_version < VERSION_WIN10)
731                 netvsc_teardown_recv_gpadl(device, net_device, ndev);
732
733         netvsc_revoke_send_buf(device, net_device, ndev);
734         if (vmbus_proto_version < VERSION_WIN10)
735                 netvsc_teardown_send_gpadl(device, net_device, ndev);
736
737         RCU_INIT_POINTER(net_device_ctx->nvdev, NULL);
738
739         /* Disable NAPI and disassociate its context from the device. */
740         for (i = 0; i < net_device->num_chn; i++) {
741                 /* See also vmbus_reset_channel_cb(). */
742                 napi_disable(&net_device->chan_table[i].napi);
743                 netif_napi_del(&net_device->chan_table[i].napi);
744         }
745
746         /*
747          * At this point, no one should be accessing net_device
748          * except in here
749          */
750         netdev_dbg(ndev, "net device safe to remove\n");
751
752         /* Now, we can close the channel safely */
753         vmbus_close(device->channel);
754
755         /*
756          * If host is Win2016 or higher then we do the GPADL tear down
757          * here after VMBus is closed.
758         */
759         if (vmbus_proto_version >= VERSION_WIN10) {
760                 netvsc_teardown_recv_gpadl(device, net_device, ndev);
761                 netvsc_teardown_send_gpadl(device, net_device, ndev);
762         }
763
764         if (net_device->recv_original_buf)
765                 hv_unmap_memory(net_device->recv_buf);
766
767         if (net_device->send_original_buf)
768                 hv_unmap_memory(net_device->send_buf);
769
770         /* Release all resources */
771         free_netvsc_device_rcu(net_device);
772 }
773
774 #define RING_AVAIL_PERCENT_HIWATER 20
775 #define RING_AVAIL_PERCENT_LOWATER 10
776
777 static inline void netvsc_free_send_slot(struct netvsc_device *net_device,
778                                          u32 index)
779 {
780         sync_change_bit(index, net_device->send_section_map);
781 }
782
783 static void netvsc_send_tx_complete(struct net_device *ndev,
784                                     struct netvsc_device *net_device,
785                                     struct vmbus_channel *channel,
786                                     const struct vmpacket_descriptor *desc,
787                                     int budget)
788 {
789         struct net_device_context *ndev_ctx = netdev_priv(ndev);
790         struct sk_buff *skb;
791         u16 q_idx = 0;
792         int queue_sends;
793         u64 cmd_rqst;
794
795         cmd_rqst = channel->request_addr_callback(channel, (u64)desc->trans_id);
796         if (cmd_rqst == VMBUS_RQST_ERROR) {
797                 netdev_err(ndev, "Incorrect transaction id\n");
798                 return;
799         }
800
801         skb = (struct sk_buff *)(unsigned long)cmd_rqst;
802
803         /* Notify the layer above us */
804         if (likely(skb)) {
805                 struct hv_netvsc_packet *packet
806                         = (struct hv_netvsc_packet *)skb->cb;
807                 u32 send_index = packet->send_buf_index;
808                 struct netvsc_stats *tx_stats;
809
810                 if (send_index != NETVSC_INVALID_INDEX)
811                         netvsc_free_send_slot(net_device, send_index);
812                 q_idx = packet->q_idx;
813
814                 tx_stats = &net_device->chan_table[q_idx].tx_stats;
815
816                 u64_stats_update_begin(&tx_stats->syncp);
817                 tx_stats->packets += packet->total_packets;
818                 tx_stats->bytes += packet->total_bytes;
819                 u64_stats_update_end(&tx_stats->syncp);
820
821                 netvsc_dma_unmap(ndev_ctx->device_ctx, packet);
822                 napi_consume_skb(skb, budget);
823         }
824
825         queue_sends =
826                 atomic_dec_return(&net_device->chan_table[q_idx].queue_sends);
827
828         if (unlikely(net_device->destroy)) {
829                 if (queue_sends == 0)
830                         wake_up(&net_device->wait_drain);
831         } else {
832                 struct netdev_queue *txq = netdev_get_tx_queue(ndev, q_idx);
833
834                 if (netif_tx_queue_stopped(txq) && !net_device->tx_disable &&
835                     (hv_get_avail_to_write_percent(&channel->outbound) >
836                      RING_AVAIL_PERCENT_HIWATER || queue_sends < 1)) {
837                         netif_tx_wake_queue(txq);
838                         ndev_ctx->eth_stats.wake_queue++;
839                 }
840         }
841 }
842
843 static void netvsc_send_completion(struct net_device *ndev,
844                                    struct netvsc_device *net_device,
845                                    struct vmbus_channel *incoming_channel,
846                                    const struct vmpacket_descriptor *desc,
847                                    int budget)
848 {
849         const struct nvsp_message *nvsp_packet;
850         u32 msglen = hv_pkt_datalen(desc);
851         struct nvsp_message *pkt_rqst;
852         u64 cmd_rqst;
853
854         /* First check if this is a VMBUS completion without data payload */
855         if (!msglen) {
856                 cmd_rqst = incoming_channel->request_addr_callback(incoming_channel,
857                                                                    (u64)desc->trans_id);
858                 if (cmd_rqst == VMBUS_RQST_ERROR) {
859                         netdev_err(ndev, "Invalid transaction id\n");
860                         return;
861                 }
862
863                 pkt_rqst = (struct nvsp_message *)(uintptr_t)cmd_rqst;
864                 switch (pkt_rqst->hdr.msg_type) {
865                 case NVSP_MSG4_TYPE_SWITCH_DATA_PATH:
866                         complete(&net_device->channel_init_wait);
867                         break;
868
869                 default:
870                         netdev_err(ndev, "Unexpected VMBUS completion!!\n");
871                 }
872                 return;
873         }
874
875         /* Ensure packet is big enough to read header fields */
876         if (msglen < sizeof(struct nvsp_message_header)) {
877                 netdev_err(ndev, "nvsp_message length too small: %u\n", msglen);
878                 return;
879         }
880
881         nvsp_packet = hv_pkt_data(desc);
882         switch (nvsp_packet->hdr.msg_type) {
883         case NVSP_MSG_TYPE_INIT_COMPLETE:
884                 if (msglen < sizeof(struct nvsp_message_header) +
885                                 sizeof(struct nvsp_message_init_complete)) {
886                         netdev_err(ndev, "nvsp_msg length too small: %u\n",
887                                    msglen);
888                         return;
889                 }
890                 fallthrough;
891
892         case NVSP_MSG1_TYPE_SEND_RECV_BUF_COMPLETE:
893                 if (msglen < sizeof(struct nvsp_message_header) +
894                                 sizeof(struct nvsp_1_message_send_receive_buffer_complete)) {
895                         netdev_err(ndev, "nvsp_msg1 length too small: %u\n",
896                                    msglen);
897                         return;
898                 }
899                 fallthrough;
900
901         case NVSP_MSG1_TYPE_SEND_SEND_BUF_COMPLETE:
902                 if (msglen < sizeof(struct nvsp_message_header) +
903                                 sizeof(struct nvsp_1_message_send_send_buffer_complete)) {
904                         netdev_err(ndev, "nvsp_msg1 length too small: %u\n",
905                                    msglen);
906                         return;
907                 }
908                 fallthrough;
909
910         case NVSP_MSG5_TYPE_SUBCHANNEL:
911                 if (msglen < sizeof(struct nvsp_message_header) +
912                                 sizeof(struct nvsp_5_subchannel_complete)) {
913                         netdev_err(ndev, "nvsp_msg5 length too small: %u\n",
914                                    msglen);
915                         return;
916                 }
917                 /* Copy the response back */
918                 memcpy(&net_device->channel_init_pkt, nvsp_packet,
919                        sizeof(struct nvsp_message));
920                 complete(&net_device->channel_init_wait);
921                 break;
922
923         case NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE:
924                 netvsc_send_tx_complete(ndev, net_device, incoming_channel,
925                                         desc, budget);
926                 break;
927
928         default:
929                 netdev_err(ndev,
930                            "Unknown send completion type %d received!!\n",
931                            nvsp_packet->hdr.msg_type);
932         }
933 }
934
935 static u32 netvsc_get_next_send_section(struct netvsc_device *net_device)
936 {
937         unsigned long *map_addr = net_device->send_section_map;
938         unsigned int i;
939
940         for_each_clear_bit(i, map_addr, net_device->send_section_cnt) {
941                 if (sync_test_and_set_bit(i, map_addr) == 0)
942                         return i;
943         }
944
945         return NETVSC_INVALID_INDEX;
946 }
947
948 static void netvsc_copy_to_send_buf(struct netvsc_device *net_device,
949                                     unsigned int section_index,
950                                     u32 pend_size,
951                                     struct hv_netvsc_packet *packet,
952                                     struct rndis_message *rndis_msg,
953                                     struct hv_page_buffer *pb,
954                                     bool xmit_more)
955 {
956         char *start = net_device->send_buf;
957         char *dest = start + (section_index * net_device->send_section_size)
958                      + pend_size;
959         int i;
960         u32 padding = 0;
961         u32 page_count = packet->cp_partial ? packet->rmsg_pgcnt :
962                 packet->page_buf_cnt;
963         u32 remain;
964
965         /* Add padding */
966         remain = packet->total_data_buflen & (net_device->pkt_align - 1);
967         if (xmit_more && remain) {
968                 padding = net_device->pkt_align - remain;
969                 rndis_msg->msg_len += padding;
970                 packet->total_data_buflen += padding;
971         }
972
973         for (i = 0; i < page_count; i++) {
974                 char *src = phys_to_virt(pb[i].pfn << HV_HYP_PAGE_SHIFT);
975                 u32 offset = pb[i].offset;
976                 u32 len = pb[i].len;
977
978                 memcpy(dest, (src + offset), len);
979                 dest += len;
980         }
981
982         if (padding)
983                 memset(dest, 0, padding);
984 }
985
986 void netvsc_dma_unmap(struct hv_device *hv_dev,
987                       struct hv_netvsc_packet *packet)
988 {
989         u32 page_count = packet->cp_partial ?
990                 packet->page_buf_cnt - packet->rmsg_pgcnt :
991                 packet->page_buf_cnt;
992         int i;
993
994         if (!hv_is_isolation_supported())
995                 return;
996
997         if (!packet->dma_range)
998                 return;
999
1000         for (i = 0; i < page_count; i++)
1001                 dma_unmap_single(&hv_dev->device, packet->dma_range[i].dma,
1002                                  packet->dma_range[i].mapping_size,
1003                                  DMA_TO_DEVICE);
1004
1005         kfree(packet->dma_range);
1006 }
1007
1008 /* netvsc_dma_map - Map swiotlb bounce buffer with data page of
1009  * packet sent by vmbus_sendpacket_pagebuffer() in the Isolation
1010  * VM.
1011  *
1012  * In isolation VM, netvsc send buffer has been marked visible to
1013  * host and so the data copied to send buffer doesn't need to use
1014  * bounce buffer. The data pages handled by vmbus_sendpacket_pagebuffer()
1015  * may not be copied to send buffer and so these pages need to be
1016  * mapped with swiotlb bounce buffer. netvsc_dma_map() is to do
1017  * that. The pfns in the struct hv_page_buffer need to be converted
1018  * to bounce buffer's pfn. The loop here is necessary because the
1019  * entries in the page buffer array are not necessarily full
1020  * pages of data.  Each entry in the array has a separate offset and
1021  * len that may be non-zero, even for entries in the middle of the
1022  * array.  And the entries are not physically contiguous.  So each
1023  * entry must be individually mapped rather than as a contiguous unit.
1024  * So not use dma_map_sg() here.
1025  */
1026 static int netvsc_dma_map(struct hv_device *hv_dev,
1027                           struct hv_netvsc_packet *packet,
1028                           struct hv_page_buffer *pb)
1029 {
1030         u32 page_count =  packet->cp_partial ?
1031                 packet->page_buf_cnt - packet->rmsg_pgcnt :
1032                 packet->page_buf_cnt;
1033         dma_addr_t dma;
1034         int i;
1035
1036         if (!hv_is_isolation_supported())
1037                 return 0;
1038
1039         packet->dma_range = kcalloc(page_count,
1040                                     sizeof(*packet->dma_range),
1041                                     GFP_KERNEL);
1042         if (!packet->dma_range)
1043                 return -ENOMEM;
1044
1045         for (i = 0; i < page_count; i++) {
1046                 char *src = phys_to_virt((pb[i].pfn << HV_HYP_PAGE_SHIFT)
1047                                          + pb[i].offset);
1048                 u32 len = pb[i].len;
1049
1050                 dma = dma_map_single(&hv_dev->device, src, len,
1051                                      DMA_TO_DEVICE);
1052                 if (dma_mapping_error(&hv_dev->device, dma)) {
1053                         kfree(packet->dma_range);
1054                         return -ENOMEM;
1055                 }
1056
1057                 /* pb[].offset and pb[].len are not changed during dma mapping
1058                  * and so not reassign.
1059                  */
1060                 packet->dma_range[i].dma = dma;
1061                 packet->dma_range[i].mapping_size = len;
1062                 pb[i].pfn = dma >> HV_HYP_PAGE_SHIFT;
1063         }
1064
1065         return 0;
1066 }
1067
1068 static inline int netvsc_send_pkt(
1069         struct hv_device *device,
1070         struct hv_netvsc_packet *packet,
1071         struct netvsc_device *net_device,
1072         struct hv_page_buffer *pb,
1073         struct sk_buff *skb)
1074 {
1075         struct nvsp_message nvmsg;
1076         struct nvsp_1_message_send_rndis_packet *rpkt =
1077                 &nvmsg.msg.v1_msg.send_rndis_pkt;
1078         struct netvsc_channel * const nvchan =
1079                 &net_device->chan_table[packet->q_idx];
1080         struct vmbus_channel *out_channel = nvchan->channel;
1081         struct net_device *ndev = hv_get_drvdata(device);
1082         struct net_device_context *ndev_ctx = netdev_priv(ndev);
1083         struct netdev_queue *txq = netdev_get_tx_queue(ndev, packet->q_idx);
1084         u64 req_id;
1085         int ret;
1086         u32 ring_avail = hv_get_avail_to_write_percent(&out_channel->outbound);
1087
1088         memset(&nvmsg, 0, sizeof(struct nvsp_message));
1089         nvmsg.hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT;
1090         if (skb)
1091                 rpkt->channel_type = 0;         /* 0 is RMC_DATA */
1092         else
1093                 rpkt->channel_type = 1;         /* 1 is RMC_CONTROL */
1094
1095         rpkt->send_buf_section_index = packet->send_buf_index;
1096         if (packet->send_buf_index == NETVSC_INVALID_INDEX)
1097                 rpkt->send_buf_section_size = 0;
1098         else
1099                 rpkt->send_buf_section_size = packet->total_data_buflen;
1100
1101         req_id = (ulong)skb;
1102
1103         if (out_channel->rescind)
1104                 return -ENODEV;
1105
1106         trace_nvsp_send_pkt(ndev, out_channel, rpkt);
1107
1108         packet->dma_range = NULL;
1109         if (packet->page_buf_cnt) {
1110                 if (packet->cp_partial)
1111                         pb += packet->rmsg_pgcnt;
1112
1113                 ret = netvsc_dma_map(ndev_ctx->device_ctx, packet, pb);
1114                 if (ret) {
1115                         ret = -EAGAIN;
1116                         goto exit;
1117                 }
1118
1119                 ret = vmbus_sendpacket_pagebuffer(out_channel,
1120                                                   pb, packet->page_buf_cnt,
1121                                                   &nvmsg, sizeof(nvmsg),
1122                                                   req_id);
1123
1124                 if (ret)
1125                         netvsc_dma_unmap(ndev_ctx->device_ctx, packet);
1126         } else {
1127                 ret = vmbus_sendpacket(out_channel,
1128                                        &nvmsg, sizeof(nvmsg),
1129                                        req_id, VM_PKT_DATA_INBAND,
1130                                        VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1131         }
1132
1133 exit:
1134         if (ret == 0) {
1135                 atomic_inc_return(&nvchan->queue_sends);
1136
1137                 if (ring_avail < RING_AVAIL_PERCENT_LOWATER) {
1138                         netif_tx_stop_queue(txq);
1139                         ndev_ctx->eth_stats.stop_queue++;
1140                 }
1141         } else if (ret == -EAGAIN) {
1142                 netif_tx_stop_queue(txq);
1143                 ndev_ctx->eth_stats.stop_queue++;
1144         } else {
1145                 netdev_err(ndev,
1146                            "Unable to send packet pages %u len %u, ret %d\n",
1147                            packet->page_buf_cnt, packet->total_data_buflen,
1148                            ret);
1149         }
1150
1151         if (netif_tx_queue_stopped(txq) &&
1152             atomic_read(&nvchan->queue_sends) < 1 &&
1153             !net_device->tx_disable) {
1154                 netif_tx_wake_queue(txq);
1155                 ndev_ctx->eth_stats.wake_queue++;
1156                 if (ret == -EAGAIN)
1157                         ret = -ENOSPC;
1158         }
1159
1160         return ret;
1161 }
1162
1163 /* Move packet out of multi send data (msd), and clear msd */
1164 static inline void move_pkt_msd(struct hv_netvsc_packet **msd_send,
1165                                 struct sk_buff **msd_skb,
1166                                 struct multi_send_data *msdp)
1167 {
1168         *msd_skb = msdp->skb;
1169         *msd_send = msdp->pkt;
1170         msdp->skb = NULL;
1171         msdp->pkt = NULL;
1172         msdp->count = 0;
1173 }
1174
1175 /* RCU already held by caller */
1176 /* Batching/bouncing logic is designed to attempt to optimize
1177  * performance.
1178  *
1179  * For small, non-LSO packets we copy the packet to a send buffer
1180  * which is pre-registered with the Hyper-V side. This enables the
1181  * hypervisor to avoid remapping the aperture to access the packet
1182  * descriptor and data.
1183  *
1184  * If we already started using a buffer and the netdev is transmitting
1185  * a burst of packets, keep on copying into the buffer until it is
1186  * full or we are done collecting a burst. If there is an existing
1187  * buffer with space for the RNDIS descriptor but not the packet, copy
1188  * the RNDIS descriptor to the buffer, keeping the packet in place.
1189  *
1190  * If we do batching and send more than one packet using a single
1191  * NetVSC message, free the SKBs of the packets copied, except for the
1192  * last packet. This is done to streamline the handling of the case
1193  * where the last packet only had the RNDIS descriptor copied to the
1194  * send buffer, with the data pointers included in the NetVSC message.
1195  */
1196 int netvsc_send(struct net_device *ndev,
1197                 struct hv_netvsc_packet *packet,
1198                 struct rndis_message *rndis_msg,
1199                 struct hv_page_buffer *pb,
1200                 struct sk_buff *skb,
1201                 bool xdp_tx)
1202 {
1203         struct net_device_context *ndev_ctx = netdev_priv(ndev);
1204         struct netvsc_device *net_device
1205                 = rcu_dereference_bh(ndev_ctx->nvdev);
1206         struct hv_device *device = ndev_ctx->device_ctx;
1207         int ret = 0;
1208         struct netvsc_channel *nvchan;
1209         u32 pktlen = packet->total_data_buflen, msd_len = 0;
1210         unsigned int section_index = NETVSC_INVALID_INDEX;
1211         struct multi_send_data *msdp;
1212         struct hv_netvsc_packet *msd_send = NULL, *cur_send = NULL;
1213         struct sk_buff *msd_skb = NULL;
1214         bool try_batch, xmit_more;
1215
1216         /* If device is rescinded, return error and packet will get dropped. */
1217         if (unlikely(!net_device || net_device->destroy))
1218                 return -ENODEV;
1219
1220         nvchan = &net_device->chan_table[packet->q_idx];
1221         packet->send_buf_index = NETVSC_INVALID_INDEX;
1222         packet->cp_partial = false;
1223
1224         /* Send a control message or XDP packet directly without accessing
1225          * msd (Multi-Send Data) field which may be changed during data packet
1226          * processing.
1227          */
1228         if (!skb || xdp_tx)
1229                 return netvsc_send_pkt(device, packet, net_device, pb, skb);
1230
1231         /* batch packets in send buffer if possible */
1232         msdp = &nvchan->msd;
1233         if (msdp->pkt)
1234                 msd_len = msdp->pkt->total_data_buflen;
1235
1236         try_batch =  msd_len > 0 && msdp->count < net_device->max_pkt;
1237         if (try_batch && msd_len + pktlen + net_device->pkt_align <
1238             net_device->send_section_size) {
1239                 section_index = msdp->pkt->send_buf_index;
1240
1241         } else if (try_batch && msd_len + packet->rmsg_size <
1242                    net_device->send_section_size) {
1243                 section_index = msdp->pkt->send_buf_index;
1244                 packet->cp_partial = true;
1245
1246         } else if (pktlen + net_device->pkt_align <
1247                    net_device->send_section_size) {
1248                 section_index = netvsc_get_next_send_section(net_device);
1249                 if (unlikely(section_index == NETVSC_INVALID_INDEX)) {
1250                         ++ndev_ctx->eth_stats.tx_send_full;
1251                 } else {
1252                         move_pkt_msd(&msd_send, &msd_skb, msdp);
1253                         msd_len = 0;
1254                 }
1255         }
1256
1257         /* Keep aggregating only if stack says more data is coming
1258          * and not doing mixed modes send and not flow blocked
1259          */
1260         xmit_more = netdev_xmit_more() &&
1261                 !packet->cp_partial &&
1262                 !netif_xmit_stopped(netdev_get_tx_queue(ndev, packet->q_idx));
1263
1264         if (section_index != NETVSC_INVALID_INDEX) {
1265                 netvsc_copy_to_send_buf(net_device,
1266                                         section_index, msd_len,
1267                                         packet, rndis_msg, pb, xmit_more);
1268
1269                 packet->send_buf_index = section_index;
1270
1271                 if (packet->cp_partial) {
1272                         packet->page_buf_cnt -= packet->rmsg_pgcnt;
1273                         packet->total_data_buflen = msd_len + packet->rmsg_size;
1274                 } else {
1275                         packet->page_buf_cnt = 0;
1276                         packet->total_data_buflen += msd_len;
1277                 }
1278
1279                 if (msdp->pkt) {
1280                         packet->total_packets += msdp->pkt->total_packets;
1281                         packet->total_bytes += msdp->pkt->total_bytes;
1282                 }
1283
1284                 if (msdp->skb)
1285                         dev_consume_skb_any(msdp->skb);
1286
1287                 if (xmit_more) {
1288                         msdp->skb = skb;
1289                         msdp->pkt = packet;
1290                         msdp->count++;
1291                 } else {
1292                         cur_send = packet;
1293                         msdp->skb = NULL;
1294                         msdp->pkt = NULL;
1295                         msdp->count = 0;
1296                 }
1297         } else {
1298                 move_pkt_msd(&msd_send, &msd_skb, msdp);
1299                 cur_send = packet;
1300         }
1301
1302         if (msd_send) {
1303                 int m_ret = netvsc_send_pkt(device, msd_send, net_device,
1304                                             NULL, msd_skb);
1305
1306                 if (m_ret != 0) {
1307                         netvsc_free_send_slot(net_device,
1308                                               msd_send->send_buf_index);
1309                         dev_kfree_skb_any(msd_skb);
1310                 }
1311         }
1312
1313         if (cur_send)
1314                 ret = netvsc_send_pkt(device, cur_send, net_device, pb, skb);
1315
1316         if (ret != 0 && section_index != NETVSC_INVALID_INDEX)
1317                 netvsc_free_send_slot(net_device, section_index);
1318
1319         return ret;
1320 }
1321
1322 /* Send pending recv completions */
1323 static int send_recv_completions(struct net_device *ndev,
1324                                  struct netvsc_device *nvdev,
1325                                  struct netvsc_channel *nvchan)
1326 {
1327         struct multi_recv_comp *mrc = &nvchan->mrc;
1328         struct recv_comp_msg {
1329                 struct nvsp_message_header hdr;
1330                 u32 status;
1331         }  __packed;
1332         struct recv_comp_msg msg = {
1333                 .hdr.msg_type = NVSP_MSG1_TYPE_SEND_RNDIS_PKT_COMPLETE,
1334         };
1335         int ret;
1336
1337         while (mrc->first != mrc->next) {
1338                 const struct recv_comp_data *rcd
1339                         = mrc->slots + mrc->first;
1340
1341                 msg.status = rcd->status;
1342                 ret = vmbus_sendpacket(nvchan->channel, &msg, sizeof(msg),
1343                                        rcd->tid, VM_PKT_COMP, 0);
1344                 if (unlikely(ret)) {
1345                         struct net_device_context *ndev_ctx = netdev_priv(ndev);
1346
1347                         ++ndev_ctx->eth_stats.rx_comp_busy;
1348                         return ret;
1349                 }
1350
1351                 if (++mrc->first == nvdev->recv_completion_cnt)
1352                         mrc->first = 0;
1353         }
1354
1355         /* receive completion ring has been emptied */
1356         if (unlikely(nvdev->destroy))
1357                 wake_up(&nvdev->wait_drain);
1358
1359         return 0;
1360 }
1361
1362 /* Count how many receive completions are outstanding */
1363 static void recv_comp_slot_avail(const struct netvsc_device *nvdev,
1364                                  const struct multi_recv_comp *mrc,
1365                                  u32 *filled, u32 *avail)
1366 {
1367         u32 count = nvdev->recv_completion_cnt;
1368
1369         if (mrc->next >= mrc->first)
1370                 *filled = mrc->next - mrc->first;
1371         else
1372                 *filled = (count - mrc->first) + mrc->next;
1373
1374         *avail = count - *filled - 1;
1375 }
1376
1377 /* Add receive complete to ring to send to host. */
1378 static void enq_receive_complete(struct net_device *ndev,
1379                                  struct netvsc_device *nvdev, u16 q_idx,
1380                                  u64 tid, u32 status)
1381 {
1382         struct netvsc_channel *nvchan = &nvdev->chan_table[q_idx];
1383         struct multi_recv_comp *mrc = &nvchan->mrc;
1384         struct recv_comp_data *rcd;
1385         u32 filled, avail;
1386
1387         recv_comp_slot_avail(nvdev, mrc, &filled, &avail);
1388
1389         if (unlikely(filled > NAPI_POLL_WEIGHT)) {
1390                 send_recv_completions(ndev, nvdev, nvchan);
1391                 recv_comp_slot_avail(nvdev, mrc, &filled, &avail);
1392         }
1393
1394         if (unlikely(!avail)) {
1395                 netdev_err(ndev, "Recv_comp full buf q:%hd, tid:%llx\n",
1396                            q_idx, tid);
1397                 return;
1398         }
1399
1400         rcd = mrc->slots + mrc->next;
1401         rcd->tid = tid;
1402         rcd->status = status;
1403
1404         if (++mrc->next == nvdev->recv_completion_cnt)
1405                 mrc->next = 0;
1406 }
1407
1408 static int netvsc_receive(struct net_device *ndev,
1409                           struct netvsc_device *net_device,
1410                           struct netvsc_channel *nvchan,
1411                           const struct vmpacket_descriptor *desc)
1412 {
1413         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1414         struct vmbus_channel *channel = nvchan->channel;
1415         const struct vmtransfer_page_packet_header *vmxferpage_packet
1416                 = container_of(desc, const struct vmtransfer_page_packet_header, d);
1417         const struct nvsp_message *nvsp = hv_pkt_data(desc);
1418         u32 msglen = hv_pkt_datalen(desc);
1419         u16 q_idx = channel->offermsg.offer.sub_channel_index;
1420         char *recv_buf = net_device->recv_buf;
1421         u32 status = NVSP_STAT_SUCCESS;
1422         int i;
1423         int count = 0;
1424
1425         /* Ensure packet is big enough to read header fields */
1426         if (msglen < sizeof(struct nvsp_message_header)) {
1427                 netif_err(net_device_ctx, rx_err, ndev,
1428                           "invalid nvsp header, length too small: %u\n",
1429                           msglen);
1430                 return 0;
1431         }
1432
1433         /* Make sure this is a valid nvsp packet */
1434         if (unlikely(nvsp->hdr.msg_type != NVSP_MSG1_TYPE_SEND_RNDIS_PKT)) {
1435                 netif_err(net_device_ctx, rx_err, ndev,
1436                           "Unknown nvsp packet type received %u\n",
1437                           nvsp->hdr.msg_type);
1438                 return 0;
1439         }
1440
1441         /* Validate xfer page pkt header */
1442         if ((desc->offset8 << 3) < sizeof(struct vmtransfer_page_packet_header)) {
1443                 netif_err(net_device_ctx, rx_err, ndev,
1444                           "Invalid xfer page pkt, offset too small: %u\n",
1445                           desc->offset8 << 3);
1446                 return 0;
1447         }
1448
1449         if (unlikely(vmxferpage_packet->xfer_pageset_id != NETVSC_RECEIVE_BUFFER_ID)) {
1450                 netif_err(net_device_ctx, rx_err, ndev,
1451                           "Invalid xfer page set id - expecting %x got %x\n",
1452                           NETVSC_RECEIVE_BUFFER_ID,
1453                           vmxferpage_packet->xfer_pageset_id);
1454                 return 0;
1455         }
1456
1457         count = vmxferpage_packet->range_cnt;
1458
1459         /* Check count for a valid value */
1460         if (NETVSC_XFER_HEADER_SIZE(count) > desc->offset8 << 3) {
1461                 netif_err(net_device_ctx, rx_err, ndev,
1462                           "Range count is not valid: %d\n",
1463                           count);
1464                 return 0;
1465         }
1466
1467         /* Each range represents 1 RNDIS pkt that contains 1 ethernet frame */
1468         for (i = 0; i < count; i++) {
1469                 u32 offset = vmxferpage_packet->ranges[i].byte_offset;
1470                 u32 buflen = vmxferpage_packet->ranges[i].byte_count;
1471                 void *data;
1472                 int ret;
1473
1474                 if (unlikely(offset > net_device->recv_buf_size ||
1475                              buflen > net_device->recv_buf_size - offset)) {
1476                         nvchan->rsc.cnt = 0;
1477                         status = NVSP_STAT_FAIL;
1478                         netif_err(net_device_ctx, rx_err, ndev,
1479                                   "Packet offset:%u + len:%u too big\n",
1480                                   offset, buflen);
1481
1482                         continue;
1483                 }
1484
1485                 /* We're going to copy (sections of) the packet into nvchan->recv_buf;
1486                  * make sure that nvchan->recv_buf is large enough to hold the packet.
1487                  */
1488                 if (unlikely(buflen > net_device->recv_section_size)) {
1489                         nvchan->rsc.cnt = 0;
1490                         status = NVSP_STAT_FAIL;
1491                         netif_err(net_device_ctx, rx_err, ndev,
1492                                   "Packet too big: buflen=%u recv_section_size=%u\n",
1493                                   buflen, net_device->recv_section_size);
1494
1495                         continue;
1496                 }
1497
1498                 data = recv_buf + offset;
1499
1500                 nvchan->rsc.is_last = (i == count - 1);
1501
1502                 trace_rndis_recv(ndev, q_idx, data);
1503
1504                 /* Pass it to the upper layer */
1505                 ret = rndis_filter_receive(ndev, net_device,
1506                                            nvchan, data, buflen);
1507
1508                 if (unlikely(ret != NVSP_STAT_SUCCESS)) {
1509                         /* Drop incomplete packet */
1510                         nvchan->rsc.cnt = 0;
1511                         status = NVSP_STAT_FAIL;
1512                 }
1513         }
1514
1515         enq_receive_complete(ndev, net_device, q_idx,
1516                              vmxferpage_packet->d.trans_id, status);
1517
1518         return count;
1519 }
1520
1521 static void netvsc_send_table(struct net_device *ndev,
1522                               struct netvsc_device *nvscdev,
1523                               const struct nvsp_message *nvmsg,
1524                               u32 msglen)
1525 {
1526         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1527         u32 count, offset, *tab;
1528         int i;
1529
1530         /* Ensure packet is big enough to read send_table fields */
1531         if (msglen < sizeof(struct nvsp_message_header) +
1532                      sizeof(struct nvsp_5_send_indirect_table)) {
1533                 netdev_err(ndev, "nvsp_v5_msg length too small: %u\n", msglen);
1534                 return;
1535         }
1536
1537         count = nvmsg->msg.v5_msg.send_table.count;
1538         offset = nvmsg->msg.v5_msg.send_table.offset;
1539
1540         if (count != VRSS_SEND_TAB_SIZE) {
1541                 netdev_err(ndev, "Received wrong send-table size:%u\n", count);
1542                 return;
1543         }
1544
1545         /* If negotiated version <= NVSP_PROTOCOL_VERSION_6, the offset may be
1546          * wrong due to a host bug. So fix the offset here.
1547          */
1548         if (nvscdev->nvsp_version <= NVSP_PROTOCOL_VERSION_6 &&
1549             msglen >= sizeof(struct nvsp_message_header) +
1550             sizeof(union nvsp_6_message_uber) + count * sizeof(u32))
1551                 offset = sizeof(struct nvsp_message_header) +
1552                          sizeof(union nvsp_6_message_uber);
1553
1554         /* Boundary check for all versions */
1555         if (msglen < count * sizeof(u32) || offset > msglen - count * sizeof(u32)) {
1556                 netdev_err(ndev, "Received send-table offset too big:%u\n",
1557                            offset);
1558                 return;
1559         }
1560
1561         tab = (void *)nvmsg + offset;
1562
1563         for (i = 0; i < count; i++)
1564                 net_device_ctx->tx_table[i] = tab[i];
1565 }
1566
1567 static void netvsc_send_vf(struct net_device *ndev,
1568                            const struct nvsp_message *nvmsg,
1569                            u32 msglen)
1570 {
1571         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1572
1573         /* Ensure packet is big enough to read its fields */
1574         if (msglen < sizeof(struct nvsp_message_header) +
1575                      sizeof(struct nvsp_4_send_vf_association)) {
1576                 netdev_err(ndev, "nvsp_v4_msg length too small: %u\n", msglen);
1577                 return;
1578         }
1579
1580         net_device_ctx->vf_alloc = nvmsg->msg.v4_msg.vf_assoc.allocated;
1581         net_device_ctx->vf_serial = nvmsg->msg.v4_msg.vf_assoc.serial;
1582         netdev_info(ndev, "VF slot %u %s\n",
1583                     net_device_ctx->vf_serial,
1584                     net_device_ctx->vf_alloc ? "added" : "removed");
1585 }
1586
1587 static void netvsc_receive_inband(struct net_device *ndev,
1588                                   struct netvsc_device *nvscdev,
1589                                   const struct vmpacket_descriptor *desc)
1590 {
1591         const struct nvsp_message *nvmsg = hv_pkt_data(desc);
1592         u32 msglen = hv_pkt_datalen(desc);
1593
1594         /* Ensure packet is big enough to read header fields */
1595         if (msglen < sizeof(struct nvsp_message_header)) {
1596                 netdev_err(ndev, "inband nvsp_message length too small: %u\n", msglen);
1597                 return;
1598         }
1599
1600         switch (nvmsg->hdr.msg_type) {
1601         case NVSP_MSG5_TYPE_SEND_INDIRECTION_TABLE:
1602                 netvsc_send_table(ndev, nvscdev, nvmsg, msglen);
1603                 break;
1604
1605         case NVSP_MSG4_TYPE_SEND_VF_ASSOCIATION:
1606                 if (hv_is_isolation_supported())
1607                         netdev_err(ndev, "Ignore VF_ASSOCIATION msg from the host supporting isolation\n");
1608                 else
1609                         netvsc_send_vf(ndev, nvmsg, msglen);
1610                 break;
1611         }
1612 }
1613
1614 static int netvsc_process_raw_pkt(struct hv_device *device,
1615                                   struct netvsc_channel *nvchan,
1616                                   struct netvsc_device *net_device,
1617                                   struct net_device *ndev,
1618                                   const struct vmpacket_descriptor *desc,
1619                                   int budget)
1620 {
1621         struct vmbus_channel *channel = nvchan->channel;
1622         const struct nvsp_message *nvmsg = hv_pkt_data(desc);
1623
1624         trace_nvsp_recv(ndev, channel, nvmsg);
1625
1626         switch (desc->type) {
1627         case VM_PKT_COMP:
1628                 netvsc_send_completion(ndev, net_device, channel, desc, budget);
1629                 break;
1630
1631         case VM_PKT_DATA_USING_XFER_PAGES:
1632                 return netvsc_receive(ndev, net_device, nvchan, desc);
1633
1634         case VM_PKT_DATA_INBAND:
1635                 netvsc_receive_inband(ndev, net_device, desc);
1636                 break;
1637
1638         default:
1639                 netdev_err(ndev, "unhandled packet type %d, tid %llx\n",
1640                            desc->type, desc->trans_id);
1641                 break;
1642         }
1643
1644         return 0;
1645 }
1646
1647 static struct hv_device *netvsc_channel_to_device(struct vmbus_channel *channel)
1648 {
1649         struct vmbus_channel *primary = channel->primary_channel;
1650
1651         return primary ? primary->device_obj : channel->device_obj;
1652 }
1653
1654 /* Network processing softirq
1655  * Process data in incoming ring buffer from host
1656  * Stops when ring is empty or budget is met or exceeded.
1657  */
1658 int netvsc_poll(struct napi_struct *napi, int budget)
1659 {
1660         struct netvsc_channel *nvchan
1661                 = container_of(napi, struct netvsc_channel, napi);
1662         struct netvsc_device *net_device = nvchan->net_device;
1663         struct vmbus_channel *channel = nvchan->channel;
1664         struct hv_device *device = netvsc_channel_to_device(channel);
1665         struct net_device *ndev = hv_get_drvdata(device);
1666         int work_done = 0;
1667         int ret;
1668
1669         /* If starting a new interval */
1670         if (!nvchan->desc)
1671                 nvchan->desc = hv_pkt_iter_first(channel);
1672
1673         while (nvchan->desc && work_done < budget) {
1674                 work_done += netvsc_process_raw_pkt(device, nvchan, net_device,
1675                                                     ndev, nvchan->desc, budget);
1676                 nvchan->desc = hv_pkt_iter_next(channel, nvchan->desc);
1677         }
1678
1679         /* Send any pending receive completions */
1680         ret = send_recv_completions(ndev, net_device, nvchan);
1681
1682         /* If it did not exhaust NAPI budget this time
1683          *  and not doing busy poll
1684          * then re-enable host interrupts
1685          *  and reschedule if ring is not empty
1686          *   or sending receive completion failed.
1687          */
1688         if (work_done < budget &&
1689             napi_complete_done(napi, work_done) &&
1690             (ret || hv_end_read(&channel->inbound)) &&
1691             napi_schedule_prep(napi)) {
1692                 hv_begin_read(&channel->inbound);
1693                 __napi_schedule(napi);
1694         }
1695
1696         /* Driver may overshoot since multiple packets per descriptor */
1697         return min(work_done, budget);
1698 }
1699
1700 /* Call back when data is available in host ring buffer.
1701  * Processing is deferred until network softirq (NAPI)
1702  */
1703 void netvsc_channel_cb(void *context)
1704 {
1705         struct netvsc_channel *nvchan = context;
1706         struct vmbus_channel *channel = nvchan->channel;
1707         struct hv_ring_buffer_info *rbi = &channel->inbound;
1708
1709         /* preload first vmpacket descriptor */
1710         prefetch(hv_get_ring_buffer(rbi) + rbi->priv_read_index);
1711
1712         if (napi_schedule_prep(&nvchan->napi)) {
1713                 /* disable interrupts from host */
1714                 hv_begin_read(rbi);
1715
1716                 __napi_schedule_irqoff(&nvchan->napi);
1717         }
1718 }
1719
1720 /*
1721  * netvsc_device_add - Callback when the device belonging to this
1722  * driver is added
1723  */
1724 struct netvsc_device *netvsc_device_add(struct hv_device *device,
1725                                 const struct netvsc_device_info *device_info)
1726 {
1727         int i, ret = 0;
1728         struct netvsc_device *net_device;
1729         struct net_device *ndev = hv_get_drvdata(device);
1730         struct net_device_context *net_device_ctx = netdev_priv(ndev);
1731
1732         net_device = alloc_net_device();
1733         if (!net_device)
1734                 return ERR_PTR(-ENOMEM);
1735
1736         for (i = 0; i < VRSS_SEND_TAB_SIZE; i++)
1737                 net_device_ctx->tx_table[i] = 0;
1738
1739         /* Because the device uses NAPI, all the interrupt batching and
1740          * control is done via Net softirq, not the channel handling
1741          */
1742         set_channel_read_mode(device->channel, HV_CALL_ISR);
1743
1744         /* If we're reopening the device we may have multiple queues, fill the
1745          * chn_table with the default channel to use it before subchannels are
1746          * opened.
1747          * Initialize the channel state before we open;
1748          * we can be interrupted as soon as we open the channel.
1749          */
1750
1751         for (i = 0; i < VRSS_CHANNEL_MAX; i++) {
1752                 struct netvsc_channel *nvchan = &net_device->chan_table[i];
1753
1754                 nvchan->channel = device->channel;
1755                 nvchan->net_device = net_device;
1756                 u64_stats_init(&nvchan->tx_stats.syncp);
1757                 u64_stats_init(&nvchan->rx_stats.syncp);
1758
1759                 ret = xdp_rxq_info_reg(&nvchan->xdp_rxq, ndev, i, 0);
1760
1761                 if (ret) {
1762                         netdev_err(ndev, "xdp_rxq_info_reg fail: %d\n", ret);
1763                         goto cleanup2;
1764                 }
1765
1766                 ret = xdp_rxq_info_reg_mem_model(&nvchan->xdp_rxq,
1767                                                  MEM_TYPE_PAGE_SHARED, NULL);
1768
1769                 if (ret) {
1770                         netdev_err(ndev, "xdp reg_mem_model fail: %d\n", ret);
1771                         goto cleanup2;
1772                 }
1773         }
1774
1775         /* Enable NAPI handler before init callbacks */
1776         netif_napi_add(ndev, &net_device->chan_table[0].napi,
1777                        netvsc_poll, NAPI_POLL_WEIGHT);
1778
1779         /* Open the channel */
1780         device->channel->next_request_id_callback = vmbus_next_request_id;
1781         device->channel->request_addr_callback = vmbus_request_addr;
1782         device->channel->rqstor_size = netvsc_rqstor_size(netvsc_ring_bytes);
1783         device->channel->max_pkt_size = NETVSC_MAX_PKT_SIZE;
1784
1785         ret = vmbus_open(device->channel, netvsc_ring_bytes,
1786                          netvsc_ring_bytes,  NULL, 0,
1787                          netvsc_channel_cb, net_device->chan_table);
1788
1789         if (ret != 0) {
1790                 netdev_err(ndev, "unable to open channel: %d\n", ret);
1791                 goto cleanup;
1792         }
1793
1794         /* Channel is opened */
1795         netdev_dbg(ndev, "hv_netvsc channel opened successfully\n");
1796
1797         napi_enable(&net_device->chan_table[0].napi);
1798
1799         /* Connect with the NetVsp */
1800         ret = netvsc_connect_vsp(device, net_device, device_info);
1801         if (ret != 0) {
1802                 netdev_err(ndev,
1803                         "unable to connect to NetVSP - %d\n", ret);
1804                 goto close;
1805         }
1806
1807         /* Writing nvdev pointer unlocks netvsc_send(), make sure chn_table is
1808          * populated.
1809          */
1810         rcu_assign_pointer(net_device_ctx->nvdev, net_device);
1811
1812         return net_device;
1813
1814 close:
1815         RCU_INIT_POINTER(net_device_ctx->nvdev, NULL);
1816         napi_disable(&net_device->chan_table[0].napi);
1817
1818         /* Now, we can close the channel safely */
1819         vmbus_close(device->channel);
1820
1821 cleanup:
1822         netif_napi_del(&net_device->chan_table[0].napi);
1823
1824 cleanup2:
1825         if (net_device->recv_original_buf)
1826                 hv_unmap_memory(net_device->recv_buf);
1827
1828         if (net_device->send_original_buf)
1829                 hv_unmap_memory(net_device->send_buf);
1830
1831         free_netvsc_device(&net_device->rcu);
1832
1833         return ERR_PTR(ret);
1834 }