arm64: defconfig: enable ZTE ZX related config
[cascardo/linux.git] / drivers / net / macvtap.c
1 #include <linux/etherdevice.h>
2 #include <linux/if_macvlan.h>
3 #include <linux/if_vlan.h>
4 #include <linux/interrupt.h>
5 #include <linux/nsproxy.h>
6 #include <linux/compat.h>
7 #include <linux/if_tun.h>
8 #include <linux/module.h>
9 #include <linux/skbuff.h>
10 #include <linux/cache.h>
11 #include <linux/sched.h>
12 #include <linux/types.h>
13 #include <linux/slab.h>
14 #include <linux/wait.h>
15 #include <linux/cdev.h>
16 #include <linux/idr.h>
17 #include <linux/fs.h>
18 #include <linux/uio.h>
19
20 #include <net/net_namespace.h>
21 #include <net/rtnetlink.h>
22 #include <net/sock.h>
23 #include <linux/virtio_net.h>
24 #include <linux/skb_array.h>
25
26 /*
27  * A macvtap queue is the central object of this driver, it connects
28  * an open character device to a macvlan interface. There can be
29  * multiple queues on one interface, which map back to queues
30  * implemented in hardware on the underlying device.
31  *
32  * macvtap_proto is used to allocate queues through the sock allocation
33  * mechanism.
34  *
35  */
36 struct macvtap_queue {
37         struct sock sk;
38         struct socket sock;
39         struct socket_wq wq;
40         int vnet_hdr_sz;
41         struct macvlan_dev __rcu *vlan;
42         struct file *file;
43         unsigned int flags;
44         u16 queue_index;
45         bool enabled;
46         struct list_head next;
47         struct skb_array skb_array;
48 };
49
50 #define MACVTAP_FEATURES (IFF_VNET_HDR | IFF_MULTI_QUEUE)
51
52 #define MACVTAP_VNET_LE 0x80000000
53 #define MACVTAP_VNET_BE 0x40000000
54
55 #ifdef CONFIG_TUN_VNET_CROSS_LE
56 static inline bool macvtap_legacy_is_little_endian(struct macvtap_queue *q)
57 {
58         return q->flags & MACVTAP_VNET_BE ? false :
59                 virtio_legacy_is_little_endian();
60 }
61
62 static long macvtap_get_vnet_be(struct macvtap_queue *q, int __user *sp)
63 {
64         int s = !!(q->flags & MACVTAP_VNET_BE);
65
66         if (put_user(s, sp))
67                 return -EFAULT;
68
69         return 0;
70 }
71
72 static long macvtap_set_vnet_be(struct macvtap_queue *q, int __user *sp)
73 {
74         int s;
75
76         if (get_user(s, sp))
77                 return -EFAULT;
78
79         if (s)
80                 q->flags |= MACVTAP_VNET_BE;
81         else
82                 q->flags &= ~MACVTAP_VNET_BE;
83
84         return 0;
85 }
86 #else
87 static inline bool macvtap_legacy_is_little_endian(struct macvtap_queue *q)
88 {
89         return virtio_legacy_is_little_endian();
90 }
91
92 static long macvtap_get_vnet_be(struct macvtap_queue *q, int __user *argp)
93 {
94         return -EINVAL;
95 }
96
97 static long macvtap_set_vnet_be(struct macvtap_queue *q, int __user *argp)
98 {
99         return -EINVAL;
100 }
101 #endif /* CONFIG_TUN_VNET_CROSS_LE */
102
103 static inline bool macvtap_is_little_endian(struct macvtap_queue *q)
104 {
105         return q->flags & MACVTAP_VNET_LE ||
106                 macvtap_legacy_is_little_endian(q);
107 }
108
109 static inline u16 macvtap16_to_cpu(struct macvtap_queue *q, __virtio16 val)
110 {
111         return __virtio16_to_cpu(macvtap_is_little_endian(q), val);
112 }
113
114 static inline __virtio16 cpu_to_macvtap16(struct macvtap_queue *q, u16 val)
115 {
116         return __cpu_to_virtio16(macvtap_is_little_endian(q), val);
117 }
118
119 static struct proto macvtap_proto = {
120         .name = "macvtap",
121         .owner = THIS_MODULE,
122         .obj_size = sizeof (struct macvtap_queue),
123 };
124
125 /*
126  * Variables for dealing with macvtaps device numbers.
127  */
128 static dev_t macvtap_major;
129 #define MACVTAP_NUM_DEVS (1U << MINORBITS)
130 static DEFINE_MUTEX(minor_lock);
131 static DEFINE_IDR(minor_idr);
132
133 #define GOODCOPY_LEN 128
134 static const void *macvtap_net_namespace(struct device *d)
135 {
136         struct net_device *dev = to_net_dev(d->parent);
137         return dev_net(dev);
138 }
139
140 static struct class macvtap_class = {
141         .name = "macvtap",
142         .owner = THIS_MODULE,
143         .ns_type = &net_ns_type_operations,
144         .namespace = macvtap_net_namespace,
145 };
146 static struct cdev macvtap_cdev;
147
148 static const struct proto_ops macvtap_socket_ops;
149
150 #define TUN_OFFLOADS (NETIF_F_HW_CSUM | NETIF_F_TSO_ECN | NETIF_F_TSO | \
151                       NETIF_F_TSO6 | NETIF_F_UFO)
152 #define RX_OFFLOADS (NETIF_F_GRO | NETIF_F_LRO)
153 #define TAP_FEATURES (NETIF_F_GSO | NETIF_F_SG | NETIF_F_FRAGLIST)
154
155 static struct macvlan_dev *macvtap_get_vlan_rcu(const struct net_device *dev)
156 {
157         return rcu_dereference(dev->rx_handler_data);
158 }
159
160 /*
161  * RCU usage:
162  * The macvtap_queue and the macvlan_dev are loosely coupled, the
163  * pointers from one to the other can only be read while rcu_read_lock
164  * or rtnl is held.
165  *
166  * Both the file and the macvlan_dev hold a reference on the macvtap_queue
167  * through sock_hold(&q->sk). When the macvlan_dev goes away first,
168  * q->vlan becomes inaccessible. When the files gets closed,
169  * macvtap_get_queue() fails.
170  *
171  * There may still be references to the struct sock inside of the
172  * queue from outbound SKBs, but these never reference back to the
173  * file or the dev. The data structure is freed through __sk_free
174  * when both our references and any pending SKBs are gone.
175  */
176
177 static int macvtap_enable_queue(struct net_device *dev, struct file *file,
178                                 struct macvtap_queue *q)
179 {
180         struct macvlan_dev *vlan = netdev_priv(dev);
181         int err = -EINVAL;
182
183         ASSERT_RTNL();
184
185         if (q->enabled)
186                 goto out;
187
188         err = 0;
189         rcu_assign_pointer(vlan->taps[vlan->numvtaps], q);
190         q->queue_index = vlan->numvtaps;
191         q->enabled = true;
192
193         vlan->numvtaps++;
194 out:
195         return err;
196 }
197
198 /* Requires RTNL */
199 static int macvtap_set_queue(struct net_device *dev, struct file *file,
200                              struct macvtap_queue *q)
201 {
202         struct macvlan_dev *vlan = netdev_priv(dev);
203
204         if (vlan->numqueues == MAX_MACVTAP_QUEUES)
205                 return -EBUSY;
206
207         rcu_assign_pointer(q->vlan, vlan);
208         rcu_assign_pointer(vlan->taps[vlan->numvtaps], q);
209         sock_hold(&q->sk);
210
211         q->file = file;
212         q->queue_index = vlan->numvtaps;
213         q->enabled = true;
214         file->private_data = q;
215         list_add_tail(&q->next, &vlan->queue_list);
216
217         vlan->numvtaps++;
218         vlan->numqueues++;
219
220         return 0;
221 }
222
223 static int macvtap_disable_queue(struct macvtap_queue *q)
224 {
225         struct macvlan_dev *vlan;
226         struct macvtap_queue *nq;
227
228         ASSERT_RTNL();
229         if (!q->enabled)
230                 return -EINVAL;
231
232         vlan = rtnl_dereference(q->vlan);
233
234         if (vlan) {
235                 int index = q->queue_index;
236                 BUG_ON(index >= vlan->numvtaps);
237                 nq = rtnl_dereference(vlan->taps[vlan->numvtaps - 1]);
238                 nq->queue_index = index;
239
240                 rcu_assign_pointer(vlan->taps[index], nq);
241                 RCU_INIT_POINTER(vlan->taps[vlan->numvtaps - 1], NULL);
242                 q->enabled = false;
243
244                 vlan->numvtaps--;
245         }
246
247         return 0;
248 }
249
250 /*
251  * The file owning the queue got closed, give up both
252  * the reference that the files holds as well as the
253  * one from the macvlan_dev if that still exists.
254  *
255  * Using the spinlock makes sure that we don't get
256  * to the queue again after destroying it.
257  */
258 static void macvtap_put_queue(struct macvtap_queue *q)
259 {
260         struct macvlan_dev *vlan;
261
262         rtnl_lock();
263         vlan = rtnl_dereference(q->vlan);
264
265         if (vlan) {
266                 if (q->enabled)
267                         BUG_ON(macvtap_disable_queue(q));
268
269                 vlan->numqueues--;
270                 RCU_INIT_POINTER(q->vlan, NULL);
271                 sock_put(&q->sk);
272                 list_del_init(&q->next);
273         }
274
275         rtnl_unlock();
276
277         synchronize_rcu();
278         skb_array_cleanup(&q->skb_array);
279         sock_put(&q->sk);
280 }
281
282 /*
283  * Select a queue based on the rxq of the device on which this packet
284  * arrived. If the incoming device is not mq, calculate a flow hash
285  * to select a queue. If all fails, find the first available queue.
286  * Cache vlan->numvtaps since it can become zero during the execution
287  * of this function.
288  */
289 static struct macvtap_queue *macvtap_get_queue(struct net_device *dev,
290                                                struct sk_buff *skb)
291 {
292         struct macvlan_dev *vlan = netdev_priv(dev);
293         struct macvtap_queue *tap = NULL;
294         /* Access to taps array is protected by rcu, but access to numvtaps
295          * isn't. Below we use it to lookup a queue, but treat it as a hint
296          * and validate that the result isn't NULL - in case we are
297          * racing against queue removal.
298          */
299         int numvtaps = ACCESS_ONCE(vlan->numvtaps);
300         __u32 rxq;
301
302         if (!numvtaps)
303                 goto out;
304
305         if (numvtaps == 1)
306                 goto single;
307
308         /* Check if we can use flow to select a queue */
309         rxq = skb_get_hash(skb);
310         if (rxq) {
311                 tap = rcu_dereference(vlan->taps[rxq % numvtaps]);
312                 goto out;
313         }
314
315         if (likely(skb_rx_queue_recorded(skb))) {
316                 rxq = skb_get_rx_queue(skb);
317
318                 while (unlikely(rxq >= numvtaps))
319                         rxq -= numvtaps;
320
321                 tap = rcu_dereference(vlan->taps[rxq]);
322                 goto out;
323         }
324
325 single:
326         tap = rcu_dereference(vlan->taps[0]);
327 out:
328         return tap;
329 }
330
331 /*
332  * The net_device is going away, give up the reference
333  * that it holds on all queues and safely set the pointer
334  * from the queues to NULL.
335  */
336 static void macvtap_del_queues(struct net_device *dev)
337 {
338         struct macvlan_dev *vlan = netdev_priv(dev);
339         struct macvtap_queue *q, *tmp;
340
341         ASSERT_RTNL();
342         list_for_each_entry_safe(q, tmp, &vlan->queue_list, next) {
343                 list_del_init(&q->next);
344                 RCU_INIT_POINTER(q->vlan, NULL);
345                 if (q->enabled)
346                         vlan->numvtaps--;
347                 vlan->numqueues--;
348                 sock_put(&q->sk);
349         }
350         BUG_ON(vlan->numvtaps);
351         BUG_ON(vlan->numqueues);
352         /* guarantee that any future macvtap_set_queue will fail */
353         vlan->numvtaps = MAX_MACVTAP_QUEUES;
354 }
355
356 static rx_handler_result_t macvtap_handle_frame(struct sk_buff **pskb)
357 {
358         struct sk_buff *skb = *pskb;
359         struct net_device *dev = skb->dev;
360         struct macvlan_dev *vlan;
361         struct macvtap_queue *q;
362         netdev_features_t features = TAP_FEATURES;
363
364         vlan = macvtap_get_vlan_rcu(dev);
365         if (!vlan)
366                 return RX_HANDLER_PASS;
367
368         q = macvtap_get_queue(dev, skb);
369         if (!q)
370                 return RX_HANDLER_PASS;
371
372         if (__skb_array_full(&q->skb_array))
373                 goto drop;
374
375         skb_push(skb, ETH_HLEN);
376
377         /* Apply the forward feature mask so that we perform segmentation
378          * according to users wishes.  This only works if VNET_HDR is
379          * enabled.
380          */
381         if (q->flags & IFF_VNET_HDR)
382                 features |= vlan->tap_features;
383         if (netif_needs_gso(skb, features)) {
384                 struct sk_buff *segs = __skb_gso_segment(skb, features, false);
385
386                 if (IS_ERR(segs))
387                         goto drop;
388
389                 if (!segs) {
390                         if (skb_array_produce(&q->skb_array, skb))
391                                 goto drop;
392                         goto wake_up;
393                 }
394
395                 consume_skb(skb);
396                 while (segs) {
397                         struct sk_buff *nskb = segs->next;
398
399                         segs->next = NULL;
400                         if (skb_array_produce(&q->skb_array, segs)) {
401                                 kfree_skb(segs);
402                                 kfree_skb_list(nskb);
403                                 break;
404                         }
405                         segs = nskb;
406                 }
407         } else {
408                 /* If we receive a partial checksum and the tap side
409                  * doesn't support checksum offload, compute the checksum.
410                  * Note: it doesn't matter which checksum feature to
411                  *        check, we either support them all or none.
412                  */
413                 if (skb->ip_summed == CHECKSUM_PARTIAL &&
414                     !(features & NETIF_F_CSUM_MASK) &&
415                     skb_checksum_help(skb))
416                         goto drop;
417                 if (skb_array_produce(&q->skb_array, skb))
418                         goto drop;
419         }
420
421 wake_up:
422         wake_up_interruptible_poll(sk_sleep(&q->sk), POLLIN | POLLRDNORM | POLLRDBAND);
423         return RX_HANDLER_CONSUMED;
424
425 drop:
426         /* Count errors/drops only here, thus don't care about args. */
427         macvlan_count_rx(vlan, 0, 0, 0);
428         kfree_skb(skb);
429         return RX_HANDLER_CONSUMED;
430 }
431
432 static int macvtap_get_minor(struct macvlan_dev *vlan)
433 {
434         int retval = -ENOMEM;
435
436         mutex_lock(&minor_lock);
437         retval = idr_alloc(&minor_idr, vlan, 1, MACVTAP_NUM_DEVS, GFP_KERNEL);
438         if (retval >= 0) {
439                 vlan->minor = retval;
440         } else if (retval == -ENOSPC) {
441                 printk(KERN_ERR "too many macvtap devices\n");
442                 retval = -EINVAL;
443         }
444         mutex_unlock(&minor_lock);
445         return retval < 0 ? retval : 0;
446 }
447
448 static void macvtap_free_minor(struct macvlan_dev *vlan)
449 {
450         mutex_lock(&minor_lock);
451         if (vlan->minor) {
452                 idr_remove(&minor_idr, vlan->minor);
453                 vlan->minor = 0;
454         }
455         mutex_unlock(&minor_lock);
456 }
457
458 static struct net_device *dev_get_by_macvtap_minor(int minor)
459 {
460         struct net_device *dev = NULL;
461         struct macvlan_dev *vlan;
462
463         mutex_lock(&minor_lock);
464         vlan = idr_find(&minor_idr, minor);
465         if (vlan) {
466                 dev = vlan->dev;
467                 dev_hold(dev);
468         }
469         mutex_unlock(&minor_lock);
470         return dev;
471 }
472
473 static int macvtap_newlink(struct net *src_net,
474                            struct net_device *dev,
475                            struct nlattr *tb[],
476                            struct nlattr *data[])
477 {
478         struct macvlan_dev *vlan = netdev_priv(dev);
479         int err;
480
481         INIT_LIST_HEAD(&vlan->queue_list);
482
483         /* Since macvlan supports all offloads by default, make
484          * tap support all offloads also.
485          */
486         vlan->tap_features = TUN_OFFLOADS;
487
488         err = netdev_rx_handler_register(dev, macvtap_handle_frame, vlan);
489         if (err)
490                 return err;
491
492         /* Don't put anything that may fail after macvlan_common_newlink
493          * because we can't undo what it does.
494          */
495         return macvlan_common_newlink(src_net, dev, tb, data);
496 }
497
498 static void macvtap_dellink(struct net_device *dev,
499                             struct list_head *head)
500 {
501         netdev_rx_handler_unregister(dev);
502         macvtap_del_queues(dev);
503         macvlan_dellink(dev, head);
504 }
505
506 static void macvtap_setup(struct net_device *dev)
507 {
508         macvlan_common_setup(dev);
509         dev->tx_queue_len = TUN_READQ_SIZE;
510 }
511
512 static struct rtnl_link_ops macvtap_link_ops __read_mostly = {
513         .kind           = "macvtap",
514         .setup          = macvtap_setup,
515         .newlink        = macvtap_newlink,
516         .dellink        = macvtap_dellink,
517 };
518
519
520 static void macvtap_sock_write_space(struct sock *sk)
521 {
522         wait_queue_head_t *wqueue;
523
524         if (!sock_writeable(sk) ||
525             !test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
526                 return;
527
528         wqueue = sk_sleep(sk);
529         if (wqueue && waitqueue_active(wqueue))
530                 wake_up_interruptible_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND);
531 }
532
533 static void macvtap_sock_destruct(struct sock *sk)
534 {
535         struct macvtap_queue *q = container_of(sk, struct macvtap_queue, sk);
536         struct sk_buff *skb;
537
538         while ((skb = skb_array_consume(&q->skb_array)) != NULL)
539                 kfree_skb(skb);
540 }
541
542 static int macvtap_open(struct inode *inode, struct file *file)
543 {
544         struct net *net = current->nsproxy->net_ns;
545         struct net_device *dev;
546         struct macvtap_queue *q;
547         int err = -ENODEV;
548
549         rtnl_lock();
550         dev = dev_get_by_macvtap_minor(iminor(inode));
551         if (!dev)
552                 goto err;
553
554         err = -ENOMEM;
555         q = (struct macvtap_queue *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
556                                              &macvtap_proto, 0);
557         if (!q)
558                 goto err;
559
560         RCU_INIT_POINTER(q->sock.wq, &q->wq);
561         init_waitqueue_head(&q->wq.wait);
562         q->sock.type = SOCK_RAW;
563         q->sock.state = SS_CONNECTED;
564         q->sock.file = file;
565         q->sock.ops = &macvtap_socket_ops;
566         sock_init_data(&q->sock, &q->sk);
567         q->sk.sk_write_space = macvtap_sock_write_space;
568         q->sk.sk_destruct = macvtap_sock_destruct;
569         q->flags = IFF_VNET_HDR | IFF_NO_PI | IFF_TAP;
570         q->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
571
572         /*
573          * so far only KVM virtio_net uses macvtap, enable zero copy between
574          * guest kernel and host kernel when lower device supports zerocopy
575          *
576          * The macvlan supports zerocopy iff the lower device supports zero
577          * copy so we don't have to look at the lower device directly.
578          */
579         if ((dev->features & NETIF_F_HIGHDMA) && (dev->features & NETIF_F_SG))
580                 sock_set_flag(&q->sk, SOCK_ZEROCOPY);
581
582         err = -ENOMEM;
583         if (skb_array_init(&q->skb_array, dev->tx_queue_len, GFP_KERNEL))
584                 goto err_array;
585
586         err = macvtap_set_queue(dev, file, q);
587         if (err)
588                 goto err_queue;
589
590         dev_put(dev);
591
592         rtnl_unlock();
593         return err;
594
595 err_queue:
596         skb_array_cleanup(&q->skb_array);
597 err_array:
598         sock_put(&q->sk);
599 err:
600         if (dev)
601                 dev_put(dev);
602
603         rtnl_unlock();
604         return err;
605 }
606
607 static int macvtap_release(struct inode *inode, struct file *file)
608 {
609         struct macvtap_queue *q = file->private_data;
610         macvtap_put_queue(q);
611         return 0;
612 }
613
614 static unsigned int macvtap_poll(struct file *file, poll_table * wait)
615 {
616         struct macvtap_queue *q = file->private_data;
617         unsigned int mask = POLLERR;
618
619         if (!q)
620                 goto out;
621
622         mask = 0;
623         poll_wait(file, &q->wq.wait, wait);
624
625         if (!skb_array_empty(&q->skb_array))
626                 mask |= POLLIN | POLLRDNORM;
627
628         if (sock_writeable(&q->sk) ||
629             (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &q->sock.flags) &&
630              sock_writeable(&q->sk)))
631                 mask |= POLLOUT | POLLWRNORM;
632
633 out:
634         return mask;
635 }
636
637 static inline struct sk_buff *macvtap_alloc_skb(struct sock *sk, size_t prepad,
638                                                 size_t len, size_t linear,
639                                                 int noblock, int *err)
640 {
641         struct sk_buff *skb;
642
643         /* Under a page?  Don't bother with paged skb. */
644         if (prepad + len < PAGE_SIZE || !linear)
645                 linear = len;
646
647         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
648                                    err, 0);
649         if (!skb)
650                 return NULL;
651
652         skb_reserve(skb, prepad);
653         skb_put(skb, linear);
654         skb->data_len = len - linear;
655         skb->len += len - linear;
656
657         return skb;
658 }
659
660 /* Neighbour code has some assumptions on HH_DATA_MOD alignment */
661 #define MACVTAP_RESERVE HH_DATA_OFF(ETH_HLEN)
662
663 /* Get packet from user space buffer */
664 static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
665                                 struct iov_iter *from, int noblock)
666 {
667         int good_linear = SKB_MAX_HEAD(MACVTAP_RESERVE);
668         struct sk_buff *skb;
669         struct macvlan_dev *vlan;
670         unsigned long total_len = iov_iter_count(from);
671         unsigned long len = total_len;
672         int err;
673         struct virtio_net_hdr vnet_hdr = { 0 };
674         int vnet_hdr_len = 0;
675         int copylen = 0;
676         int depth;
677         bool zerocopy = false;
678         size_t linear;
679         ssize_t n;
680
681         if (q->flags & IFF_VNET_HDR) {
682                 vnet_hdr_len = q->vnet_hdr_sz;
683
684                 err = -EINVAL;
685                 if (len < vnet_hdr_len)
686                         goto err;
687                 len -= vnet_hdr_len;
688
689                 err = -EFAULT;
690                 n = copy_from_iter(&vnet_hdr, sizeof(vnet_hdr), from);
691                 if (n != sizeof(vnet_hdr))
692                         goto err;
693                 iov_iter_advance(from, vnet_hdr_len - sizeof(vnet_hdr));
694                 if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
695                      macvtap16_to_cpu(q, vnet_hdr.csum_start) +
696                      macvtap16_to_cpu(q, vnet_hdr.csum_offset) + 2 >
697                              macvtap16_to_cpu(q, vnet_hdr.hdr_len))
698                         vnet_hdr.hdr_len = cpu_to_macvtap16(q,
699                                  macvtap16_to_cpu(q, vnet_hdr.csum_start) +
700                                  macvtap16_to_cpu(q, vnet_hdr.csum_offset) + 2);
701                 err = -EINVAL;
702                 if (macvtap16_to_cpu(q, vnet_hdr.hdr_len) > len)
703                         goto err;
704         }
705
706         err = -EINVAL;
707         if (unlikely(len < ETH_HLEN))
708                 goto err;
709
710         if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) {
711                 struct iov_iter i;
712
713                 copylen = vnet_hdr.hdr_len ?
714                         macvtap16_to_cpu(q, vnet_hdr.hdr_len) : GOODCOPY_LEN;
715                 if (copylen > good_linear)
716                         copylen = good_linear;
717                 else if (copylen < ETH_HLEN)
718                         copylen = ETH_HLEN;
719                 linear = copylen;
720                 i = *from;
721                 iov_iter_advance(&i, copylen);
722                 if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
723                         zerocopy = true;
724         }
725
726         if (!zerocopy) {
727                 copylen = len;
728                 linear = macvtap16_to_cpu(q, vnet_hdr.hdr_len);
729                 if (linear > good_linear)
730                         linear = good_linear;
731                 else if (linear < ETH_HLEN)
732                         linear = ETH_HLEN;
733         }
734
735         skb = macvtap_alloc_skb(&q->sk, MACVTAP_RESERVE, copylen,
736                                 linear, noblock, &err);
737         if (!skb)
738                 goto err;
739
740         if (zerocopy)
741                 err = zerocopy_sg_from_iter(skb, from);
742         else {
743                 err = skb_copy_datagram_from_iter(skb, 0, from, len);
744                 if (!err && m && m->msg_control) {
745                         struct ubuf_info *uarg = m->msg_control;
746                         uarg->callback(uarg, false);
747                 }
748         }
749
750         if (err)
751                 goto err_kfree;
752
753         skb_set_network_header(skb, ETH_HLEN);
754         skb_reset_mac_header(skb);
755         skb->protocol = eth_hdr(skb)->h_proto;
756
757         if (vnet_hdr_len) {
758                 err = virtio_net_hdr_to_skb(skb, &vnet_hdr,
759                                             macvtap_is_little_endian(q));
760                 if (err)
761                         goto err_kfree;
762         }
763
764         skb_probe_transport_header(skb, ETH_HLEN);
765
766         /* Move network header to the right position for VLAN tagged packets */
767         if ((skb->protocol == htons(ETH_P_8021Q) ||
768              skb->protocol == htons(ETH_P_8021AD)) &&
769             __vlan_get_protocol(skb, skb->protocol, &depth) != 0)
770                 skb_set_network_header(skb, depth);
771
772         rcu_read_lock();
773         vlan = rcu_dereference(q->vlan);
774         /* copy skb_ubuf_info for callback when skb has no error */
775         if (zerocopy) {
776                 skb_shinfo(skb)->destructor_arg = m->msg_control;
777                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
778                 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
779         }
780         if (vlan) {
781                 skb->dev = vlan->dev;
782                 dev_queue_xmit(skb);
783         } else {
784                 kfree_skb(skb);
785         }
786         rcu_read_unlock();
787
788         return total_len;
789
790 err_kfree:
791         kfree_skb(skb);
792
793 err:
794         rcu_read_lock();
795         vlan = rcu_dereference(q->vlan);
796         if (vlan)
797                 this_cpu_inc(vlan->pcpu_stats->tx_dropped);
798         rcu_read_unlock();
799
800         return err;
801 }
802
803 static ssize_t macvtap_write_iter(struct kiocb *iocb, struct iov_iter *from)
804 {
805         struct file *file = iocb->ki_filp;
806         struct macvtap_queue *q = file->private_data;
807
808         return macvtap_get_user(q, NULL, from, file->f_flags & O_NONBLOCK);
809 }
810
811 /* Put packet to the user space buffer */
812 static ssize_t macvtap_put_user(struct macvtap_queue *q,
813                                 const struct sk_buff *skb,
814                                 struct iov_iter *iter)
815 {
816         int ret;
817         int vnet_hdr_len = 0;
818         int vlan_offset = 0;
819         int total;
820
821         if (q->flags & IFF_VNET_HDR) {
822                 struct virtio_net_hdr vnet_hdr;
823                 vnet_hdr_len = q->vnet_hdr_sz;
824                 if (iov_iter_count(iter) < vnet_hdr_len)
825                         return -EINVAL;
826
827                 ret = virtio_net_hdr_from_skb(skb, &vnet_hdr,
828                                               macvtap_is_little_endian(q));
829                 if (ret)
830                         BUG();
831
832                 if (copy_to_iter(&vnet_hdr, sizeof(vnet_hdr), iter) !=
833                     sizeof(vnet_hdr))
834                         return -EFAULT;
835
836                 iov_iter_advance(iter, vnet_hdr_len - sizeof(vnet_hdr));
837         }
838         total = vnet_hdr_len;
839         total += skb->len;
840
841         if (skb_vlan_tag_present(skb)) {
842                 struct {
843                         __be16 h_vlan_proto;
844                         __be16 h_vlan_TCI;
845                 } veth;
846                 veth.h_vlan_proto = skb->vlan_proto;
847                 veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
848
849                 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
850                 total += VLAN_HLEN;
851
852                 ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
853                 if (ret || !iov_iter_count(iter))
854                         goto done;
855
856                 ret = copy_to_iter(&veth, sizeof(veth), iter);
857                 if (ret != sizeof(veth) || !iov_iter_count(iter))
858                         goto done;
859         }
860
861         ret = skb_copy_datagram_iter(skb, vlan_offset, iter,
862                                      skb->len - vlan_offset);
863
864 done:
865         return ret ? ret : total;
866 }
867
868 static ssize_t macvtap_do_read(struct macvtap_queue *q,
869                                struct iov_iter *to,
870                                int noblock)
871 {
872         DEFINE_WAIT(wait);
873         struct sk_buff *skb;
874         ssize_t ret = 0;
875
876         if (!iov_iter_count(to))
877                 return 0;
878
879         while (1) {
880                 if (!noblock)
881                         prepare_to_wait(sk_sleep(&q->sk), &wait,
882                                         TASK_INTERRUPTIBLE);
883
884                 /* Read frames from the queue */
885                 skb = skb_array_consume(&q->skb_array);
886                 if (skb)
887                         break;
888                 if (noblock) {
889                         ret = -EAGAIN;
890                         break;
891                 }
892                 if (signal_pending(current)) {
893                         ret = -ERESTARTSYS;
894                         break;
895                 }
896                 /* Nothing to read, let's sleep */
897                 schedule();
898         }
899         if (!noblock)
900                 finish_wait(sk_sleep(&q->sk), &wait);
901
902         if (skb) {
903                 ret = macvtap_put_user(q, skb, to);
904                 if (unlikely(ret < 0))
905                         kfree_skb(skb);
906                 else
907                         consume_skb(skb);
908         }
909         return ret;
910 }
911
912 static ssize_t macvtap_read_iter(struct kiocb *iocb, struct iov_iter *to)
913 {
914         struct file *file = iocb->ki_filp;
915         struct macvtap_queue *q = file->private_data;
916         ssize_t len = iov_iter_count(to), ret;
917
918         ret = macvtap_do_read(q, to, file->f_flags & O_NONBLOCK);
919         ret = min_t(ssize_t, ret, len);
920         if (ret > 0)
921                 iocb->ki_pos = ret;
922         return ret;
923 }
924
925 static struct macvlan_dev *macvtap_get_vlan(struct macvtap_queue *q)
926 {
927         struct macvlan_dev *vlan;
928
929         ASSERT_RTNL();
930         vlan = rtnl_dereference(q->vlan);
931         if (vlan)
932                 dev_hold(vlan->dev);
933
934         return vlan;
935 }
936
937 static void macvtap_put_vlan(struct macvlan_dev *vlan)
938 {
939         dev_put(vlan->dev);
940 }
941
942 static int macvtap_ioctl_set_queue(struct file *file, unsigned int flags)
943 {
944         struct macvtap_queue *q = file->private_data;
945         struct macvlan_dev *vlan;
946         int ret;
947
948         vlan = macvtap_get_vlan(q);
949         if (!vlan)
950                 return -EINVAL;
951
952         if (flags & IFF_ATTACH_QUEUE)
953                 ret = macvtap_enable_queue(vlan->dev, file, q);
954         else if (flags & IFF_DETACH_QUEUE)
955                 ret = macvtap_disable_queue(q);
956         else
957                 ret = -EINVAL;
958
959         macvtap_put_vlan(vlan);
960         return ret;
961 }
962
963 static int set_offload(struct macvtap_queue *q, unsigned long arg)
964 {
965         struct macvlan_dev *vlan;
966         netdev_features_t features;
967         netdev_features_t feature_mask = 0;
968
969         vlan = rtnl_dereference(q->vlan);
970         if (!vlan)
971                 return -ENOLINK;
972
973         features = vlan->dev->features;
974
975         if (arg & TUN_F_CSUM) {
976                 feature_mask = NETIF_F_HW_CSUM;
977
978                 if (arg & (TUN_F_TSO4 | TUN_F_TSO6)) {
979                         if (arg & TUN_F_TSO_ECN)
980                                 feature_mask |= NETIF_F_TSO_ECN;
981                         if (arg & TUN_F_TSO4)
982                                 feature_mask |= NETIF_F_TSO;
983                         if (arg & TUN_F_TSO6)
984                                 feature_mask |= NETIF_F_TSO6;
985                 }
986
987                 if (arg & TUN_F_UFO)
988                         feature_mask |= NETIF_F_UFO;
989         }
990
991         /* tun/tap driver inverts the usage for TSO offloads, where
992          * setting the TSO bit means that the userspace wants to
993          * accept TSO frames and turning it off means that user space
994          * does not support TSO.
995          * For macvtap, we have to invert it to mean the same thing.
996          * When user space turns off TSO, we turn off GSO/LRO so that
997          * user-space will not receive TSO frames.
998          */
999         if (feature_mask & (NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_UFO))
1000                 features |= RX_OFFLOADS;
1001         else
1002                 features &= ~RX_OFFLOADS;
1003
1004         /* tap_features are the same as features on tun/tap and
1005          * reflect user expectations.
1006          */
1007         vlan->tap_features = feature_mask;
1008         vlan->set_features = features;
1009         netdev_update_features(vlan->dev);
1010
1011         return 0;
1012 }
1013
1014 /*
1015  * provide compatibility with generic tun/tap interface
1016  */
1017 static long macvtap_ioctl(struct file *file, unsigned int cmd,
1018                           unsigned long arg)
1019 {
1020         struct macvtap_queue *q = file->private_data;
1021         struct macvlan_dev *vlan;
1022         void __user *argp = (void __user *)arg;
1023         struct ifreq __user *ifr = argp;
1024         unsigned int __user *up = argp;
1025         unsigned short u;
1026         int __user *sp = argp;
1027         struct sockaddr sa;
1028         int s;
1029         int ret;
1030
1031         switch (cmd) {
1032         case TUNSETIFF:
1033                 /* ignore the name, just look at flags */
1034                 if (get_user(u, &ifr->ifr_flags))
1035                         return -EFAULT;
1036
1037                 ret = 0;
1038                 if ((u & ~MACVTAP_FEATURES) != (IFF_NO_PI | IFF_TAP))
1039                         ret = -EINVAL;
1040                 else
1041                         q->flags = (q->flags & ~MACVTAP_FEATURES) | u;
1042
1043                 return ret;
1044
1045         case TUNGETIFF:
1046                 rtnl_lock();
1047                 vlan = macvtap_get_vlan(q);
1048                 if (!vlan) {
1049                         rtnl_unlock();
1050                         return -ENOLINK;
1051                 }
1052
1053                 ret = 0;
1054                 u = q->flags;
1055                 if (copy_to_user(&ifr->ifr_name, vlan->dev->name, IFNAMSIZ) ||
1056                     put_user(u, &ifr->ifr_flags))
1057                         ret = -EFAULT;
1058                 macvtap_put_vlan(vlan);
1059                 rtnl_unlock();
1060                 return ret;
1061
1062         case TUNSETQUEUE:
1063                 if (get_user(u, &ifr->ifr_flags))
1064                         return -EFAULT;
1065                 rtnl_lock();
1066                 ret = macvtap_ioctl_set_queue(file, u);
1067                 rtnl_unlock();
1068                 return ret;
1069
1070         case TUNGETFEATURES:
1071                 if (put_user(IFF_TAP | IFF_NO_PI | MACVTAP_FEATURES, up))
1072                         return -EFAULT;
1073                 return 0;
1074
1075         case TUNSETSNDBUF:
1076                 if (get_user(s, sp))
1077                         return -EFAULT;
1078
1079                 q->sk.sk_sndbuf = s;
1080                 return 0;
1081
1082         case TUNGETVNETHDRSZ:
1083                 s = q->vnet_hdr_sz;
1084                 if (put_user(s, sp))
1085                         return -EFAULT;
1086                 return 0;
1087
1088         case TUNSETVNETHDRSZ:
1089                 if (get_user(s, sp))
1090                         return -EFAULT;
1091                 if (s < (int)sizeof(struct virtio_net_hdr))
1092                         return -EINVAL;
1093
1094                 q->vnet_hdr_sz = s;
1095                 return 0;
1096
1097         case TUNGETVNETLE:
1098                 s = !!(q->flags & MACVTAP_VNET_LE);
1099                 if (put_user(s, sp))
1100                         return -EFAULT;
1101                 return 0;
1102
1103         case TUNSETVNETLE:
1104                 if (get_user(s, sp))
1105                         return -EFAULT;
1106                 if (s)
1107                         q->flags |= MACVTAP_VNET_LE;
1108                 else
1109                         q->flags &= ~MACVTAP_VNET_LE;
1110                 return 0;
1111
1112         case TUNGETVNETBE:
1113                 return macvtap_get_vnet_be(q, sp);
1114
1115         case TUNSETVNETBE:
1116                 return macvtap_set_vnet_be(q, sp);
1117
1118         case TUNSETOFFLOAD:
1119                 /* let the user check for future flags */
1120                 if (arg & ~(TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 |
1121                             TUN_F_TSO_ECN | TUN_F_UFO))
1122                         return -EINVAL;
1123
1124                 rtnl_lock();
1125                 ret = set_offload(q, arg);
1126                 rtnl_unlock();
1127                 return ret;
1128
1129         case SIOCGIFHWADDR:
1130                 rtnl_lock();
1131                 vlan = macvtap_get_vlan(q);
1132                 if (!vlan) {
1133                         rtnl_unlock();
1134                         return -ENOLINK;
1135                 }
1136                 ret = 0;
1137                 u = vlan->dev->type;
1138                 if (copy_to_user(&ifr->ifr_name, vlan->dev->name, IFNAMSIZ) ||
1139                     copy_to_user(&ifr->ifr_hwaddr.sa_data, vlan->dev->dev_addr, ETH_ALEN) ||
1140                     put_user(u, &ifr->ifr_hwaddr.sa_family))
1141                         ret = -EFAULT;
1142                 macvtap_put_vlan(vlan);
1143                 rtnl_unlock();
1144                 return ret;
1145
1146         case SIOCSIFHWADDR:
1147                 if (copy_from_user(&sa, &ifr->ifr_hwaddr, sizeof(sa)))
1148                         return -EFAULT;
1149                 rtnl_lock();
1150                 vlan = macvtap_get_vlan(q);
1151                 if (!vlan) {
1152                         rtnl_unlock();
1153                         return -ENOLINK;
1154                 }
1155                 ret = dev_set_mac_address(vlan->dev, &sa);
1156                 macvtap_put_vlan(vlan);
1157                 rtnl_unlock();
1158                 return ret;
1159
1160         default:
1161                 return -EINVAL;
1162         }
1163 }
1164
1165 #ifdef CONFIG_COMPAT
1166 static long macvtap_compat_ioctl(struct file *file, unsigned int cmd,
1167                                  unsigned long arg)
1168 {
1169         return macvtap_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1170 }
1171 #endif
1172
1173 static const struct file_operations macvtap_fops = {
1174         .owner          = THIS_MODULE,
1175         .open           = macvtap_open,
1176         .release        = macvtap_release,
1177         .read_iter      = macvtap_read_iter,
1178         .write_iter     = macvtap_write_iter,
1179         .poll           = macvtap_poll,
1180         .llseek         = no_llseek,
1181         .unlocked_ioctl = macvtap_ioctl,
1182 #ifdef CONFIG_COMPAT
1183         .compat_ioctl   = macvtap_compat_ioctl,
1184 #endif
1185 };
1186
1187 static int macvtap_sendmsg(struct socket *sock, struct msghdr *m,
1188                            size_t total_len)
1189 {
1190         struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
1191         return macvtap_get_user(q, m, &m->msg_iter, m->msg_flags & MSG_DONTWAIT);
1192 }
1193
1194 static int macvtap_recvmsg(struct socket *sock, struct msghdr *m,
1195                            size_t total_len, int flags)
1196 {
1197         struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
1198         int ret;
1199         if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
1200                 return -EINVAL;
1201         ret = macvtap_do_read(q, &m->msg_iter, flags & MSG_DONTWAIT);
1202         if (ret > total_len) {
1203                 m->msg_flags |= MSG_TRUNC;
1204                 ret = flags & MSG_TRUNC ? ret : total_len;
1205         }
1206         return ret;
1207 }
1208
1209 static int macvtap_peek_len(struct socket *sock)
1210 {
1211         struct macvtap_queue *q = container_of(sock, struct macvtap_queue,
1212                                                sock);
1213         return skb_array_peek_len(&q->skb_array);
1214 }
1215
1216 /* Ops structure to mimic raw sockets with tun */
1217 static const struct proto_ops macvtap_socket_ops = {
1218         .sendmsg = macvtap_sendmsg,
1219         .recvmsg = macvtap_recvmsg,
1220         .peek_len = macvtap_peek_len,
1221 };
1222
1223 /* Get an underlying socket object from tun file.  Returns error unless file is
1224  * attached to a device.  The returned object works like a packet socket, it
1225  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
1226  * holding a reference to the file for as long as the socket is in use. */
1227 struct socket *macvtap_get_socket(struct file *file)
1228 {
1229         struct macvtap_queue *q;
1230         if (file->f_op != &macvtap_fops)
1231                 return ERR_PTR(-EINVAL);
1232         q = file->private_data;
1233         if (!q)
1234                 return ERR_PTR(-EBADFD);
1235         return &q->sock;
1236 }
1237 EXPORT_SYMBOL_GPL(macvtap_get_socket);
1238
1239 static int macvtap_queue_resize(struct macvlan_dev *vlan)
1240 {
1241         struct net_device *dev = vlan->dev;
1242         struct macvtap_queue *q;
1243         struct skb_array **arrays;
1244         int n = vlan->numqueues;
1245         int ret, i = 0;
1246
1247         arrays = kmalloc(sizeof *arrays * n, GFP_KERNEL);
1248         if (!arrays)
1249                 return -ENOMEM;
1250
1251         list_for_each_entry(q, &vlan->queue_list, next)
1252                 arrays[i++] = &q->skb_array;
1253
1254         ret = skb_array_resize_multiple(arrays, n,
1255                                         dev->tx_queue_len, GFP_KERNEL);
1256
1257         kfree(arrays);
1258         return ret;
1259 }
1260
1261 static int macvtap_device_event(struct notifier_block *unused,
1262                                 unsigned long event, void *ptr)
1263 {
1264         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1265         struct macvlan_dev *vlan;
1266         struct device *classdev;
1267         dev_t devt;
1268         int err;
1269         char tap_name[IFNAMSIZ];
1270
1271         if (dev->rtnl_link_ops != &macvtap_link_ops)
1272                 return NOTIFY_DONE;
1273
1274         snprintf(tap_name, IFNAMSIZ, "tap%d", dev->ifindex);
1275         vlan = netdev_priv(dev);
1276
1277         switch (event) {
1278         case NETDEV_REGISTER:
1279                 /* Create the device node here after the network device has
1280                  * been registered but before register_netdevice has
1281                  * finished running.
1282                  */
1283                 err = macvtap_get_minor(vlan);
1284                 if (err)
1285                         return notifier_from_errno(err);
1286
1287                 devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
1288                 classdev = device_create(&macvtap_class, &dev->dev, devt,
1289                                          dev, tap_name);
1290                 if (IS_ERR(classdev)) {
1291                         macvtap_free_minor(vlan);
1292                         return notifier_from_errno(PTR_ERR(classdev));
1293                 }
1294                 err = sysfs_create_link(&dev->dev.kobj, &classdev->kobj,
1295                                         tap_name);
1296                 if (err)
1297                         return notifier_from_errno(err);
1298                 break;
1299         case NETDEV_UNREGISTER:
1300                 /* vlan->minor == 0 if NETDEV_REGISTER above failed */
1301                 if (vlan->minor == 0)
1302                         break;
1303                 sysfs_remove_link(&dev->dev.kobj, tap_name);
1304                 devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
1305                 device_destroy(&macvtap_class, devt);
1306                 macvtap_free_minor(vlan);
1307                 break;
1308         case NETDEV_CHANGE_TX_QUEUE_LEN:
1309                 if (macvtap_queue_resize(vlan))
1310                         return NOTIFY_BAD;
1311                 break;
1312         }
1313
1314         return NOTIFY_DONE;
1315 }
1316
1317 static struct notifier_block macvtap_notifier_block __read_mostly = {
1318         .notifier_call  = macvtap_device_event,
1319 };
1320
1321 static int macvtap_init(void)
1322 {
1323         int err;
1324
1325         err = alloc_chrdev_region(&macvtap_major, 0,
1326                                 MACVTAP_NUM_DEVS, "macvtap");
1327         if (err)
1328                 goto out1;
1329
1330         cdev_init(&macvtap_cdev, &macvtap_fops);
1331         err = cdev_add(&macvtap_cdev, macvtap_major, MACVTAP_NUM_DEVS);
1332         if (err)
1333                 goto out2;
1334
1335         err = class_register(&macvtap_class);
1336         if (err)
1337                 goto out3;
1338
1339         err = register_netdevice_notifier(&macvtap_notifier_block);
1340         if (err)
1341                 goto out4;
1342
1343         err = macvlan_link_register(&macvtap_link_ops);
1344         if (err)
1345                 goto out5;
1346
1347         return 0;
1348
1349 out5:
1350         unregister_netdevice_notifier(&macvtap_notifier_block);
1351 out4:
1352         class_unregister(&macvtap_class);
1353 out3:
1354         cdev_del(&macvtap_cdev);
1355 out2:
1356         unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
1357 out1:
1358         return err;
1359 }
1360 module_init(macvtap_init);
1361
1362 static void macvtap_exit(void)
1363 {
1364         rtnl_link_unregister(&macvtap_link_ops);
1365         unregister_netdevice_notifier(&macvtap_notifier_block);
1366         class_unregister(&macvtap_class);
1367         cdev_del(&macvtap_cdev);
1368         unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
1369         idr_destroy(&minor_idr);
1370 }
1371 module_exit(macvtap_exit);
1372
1373 MODULE_ALIAS_RTNL_LINK("macvtap");
1374 MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>");
1375 MODULE_LICENSE("GPL");