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