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