macvtap: Don't leak unreceived packets when we delete a macvtap device.
[pandora-kernel.git] / drivers / net / macvtap.c
1 #include <linux/etherdevice.h>
2 #include <linux/if_macvlan.h>
3 #include <linux/interrupt.h>
4 #include <linux/nsproxy.h>
5 #include <linux/compat.h>
6 #include <linux/if_tun.h>
7 #include <linux/module.h>
8 #include <linux/skbuff.h>
9 #include <linux/cache.h>
10 #include <linux/sched.h>
11 #include <linux/types.h>
12 #include <linux/slab.h>
13 #include <linux/init.h>
14 #include <linux/wait.h>
15 #include <linux/cdev.h>
16 #include <linux/fs.h>
17
18 #include <net/net_namespace.h>
19 #include <net/rtnetlink.h>
20 #include <net/sock.h>
21 #include <linux/virtio_net.h>
22
23 /*
24  * A macvtap queue is the central object of this driver, it connects
25  * an open character device to a macvlan interface. There can be
26  * multiple queues on one interface, which map back to queues
27  * implemented in hardware on the underlying device.
28  *
29  * macvtap_proto is used to allocate queues through the sock allocation
30  * mechanism.
31  *
32  * TODO: multiqueue support is currently not implemented, even though
33  * macvtap is basically prepared for that. We will need to add this
34  * here as well as in virtio-net and qemu to get line rate on 10gbit
35  * adapters from a guest.
36  */
37 struct macvtap_queue {
38         struct sock sk;
39         struct socket sock;
40         struct socket_wq wq;
41         int vnet_hdr_sz;
42         struct macvlan_dev __rcu *vlan;
43         struct file *file;
44         unsigned int flags;
45 };
46
47 static struct proto macvtap_proto = {
48         .name = "macvtap",
49         .owner = THIS_MODULE,
50         .obj_size = sizeof (struct macvtap_queue),
51 };
52
53 /*
54  * Minor number matches netdev->ifindex, so need a potentially
55  * large value. This also makes it possible to split the
56  * tap functionality out again in the future by offering it
57  * from other drivers besides macvtap. As long as every device
58  * only has one tap, the interface numbers assure that the
59  * device nodes are unique.
60  */
61 static dev_t macvtap_major;
62 #define MACVTAP_NUM_DEVS 65536
63 #define GOODCOPY_LEN 128
64 static struct class *macvtap_class;
65 static struct cdev macvtap_cdev;
66
67 static const struct proto_ops macvtap_socket_ops;
68
69 /*
70  * RCU usage:
71  * The macvtap_queue and the macvlan_dev are loosely coupled, the
72  * pointers from one to the other can only be read while rcu_read_lock
73  * or macvtap_lock is held.
74  *
75  * Both the file and the macvlan_dev hold a reference on the macvtap_queue
76  * through sock_hold(&q->sk). When the macvlan_dev goes away first,
77  * q->vlan becomes inaccessible. When the files gets closed,
78  * macvtap_get_queue() fails.
79  *
80  * There may still be references to the struct sock inside of the
81  * queue from outbound SKBs, but these never reference back to the
82  * file or the dev. The data structure is freed through __sk_free
83  * when both our references and any pending SKBs are gone.
84  */
85 static DEFINE_SPINLOCK(macvtap_lock);
86
87 /*
88  * get_slot: return a [unused/occupied] slot in vlan->taps[]:
89  *      - if 'q' is NULL, return the first empty slot;
90  *      - otherwise, return the slot this pointer occupies.
91  */
92 static int get_slot(struct macvlan_dev *vlan, struct macvtap_queue *q)
93 {
94         int i;
95
96         for (i = 0; i < MAX_MACVTAP_QUEUES; i++) {
97                 if (rcu_dereference(vlan->taps[i]) == q)
98                         return i;
99         }
100
101         /* Should never happen */
102         BUG_ON(1);
103 }
104
105 static int macvtap_set_queue(struct net_device *dev, struct file *file,
106                                 struct macvtap_queue *q)
107 {
108         struct macvlan_dev *vlan = netdev_priv(dev);
109         int index;
110         int err = -EBUSY;
111
112         spin_lock(&macvtap_lock);
113         if (vlan->numvtaps == MAX_MACVTAP_QUEUES)
114                 goto out;
115
116         err = 0;
117         index = get_slot(vlan, NULL);
118         rcu_assign_pointer(q->vlan, vlan);
119         rcu_assign_pointer(vlan->taps[index], q);
120         sock_hold(&q->sk);
121
122         q->file = file;
123         file->private_data = q;
124
125         vlan->numvtaps++;
126
127 out:
128         spin_unlock(&macvtap_lock);
129         return err;
130 }
131
132 /*
133  * The file owning the queue got closed, give up both
134  * the reference that the files holds as well as the
135  * one from the macvlan_dev if that still exists.
136  *
137  * Using the spinlock makes sure that we don't get
138  * to the queue again after destroying it.
139  */
140 static void macvtap_put_queue(struct macvtap_queue *q)
141 {
142         struct macvlan_dev *vlan;
143
144         spin_lock(&macvtap_lock);
145         vlan = rcu_dereference_protected(q->vlan,
146                                          lockdep_is_held(&macvtap_lock));
147         if (vlan) {
148                 int index = get_slot(vlan, q);
149
150                 rcu_assign_pointer(vlan->taps[index], NULL);
151                 rcu_assign_pointer(q->vlan, NULL);
152                 sock_put(&q->sk);
153                 --vlan->numvtaps;
154         }
155
156         spin_unlock(&macvtap_lock);
157
158         synchronize_rcu();
159         sock_put(&q->sk);
160 }
161
162 /*
163  * Select a queue based on the rxq of the device on which this packet
164  * arrived. If the incoming device is not mq, calculate a flow hash
165  * to select a queue. If all fails, find the first available queue.
166  * Cache vlan->numvtaps since it can become zero during the execution
167  * of this function.
168  */
169 static struct macvtap_queue *macvtap_get_queue(struct net_device *dev,
170                                                struct sk_buff *skb)
171 {
172         struct macvlan_dev *vlan = netdev_priv(dev);
173         struct macvtap_queue *tap = NULL;
174         int numvtaps = vlan->numvtaps;
175         __u32 rxq;
176
177         if (!numvtaps)
178                 goto out;
179
180         if (likely(skb_rx_queue_recorded(skb))) {
181                 rxq = skb_get_rx_queue(skb);
182
183                 while (unlikely(rxq >= numvtaps))
184                         rxq -= numvtaps;
185
186                 tap = rcu_dereference(vlan->taps[rxq]);
187                 if (tap)
188                         goto out;
189         }
190
191         /* Check if we can use flow to select a queue */
192         rxq = skb_get_rxhash(skb);
193         if (rxq) {
194                 tap = rcu_dereference(vlan->taps[rxq % numvtaps]);
195                 if (tap)
196                         goto out;
197         }
198
199         /* Everything failed - find first available queue */
200         for (rxq = 0; rxq < MAX_MACVTAP_QUEUES; rxq++) {
201                 tap = rcu_dereference(vlan->taps[rxq]);
202                 if (tap)
203                         break;
204         }
205
206 out:
207         return tap;
208 }
209
210 /*
211  * The net_device is going away, give up the reference
212  * that it holds on all queues and safely set the pointer
213  * from the queues to NULL.
214  */
215 static void macvtap_del_queues(struct net_device *dev)
216 {
217         struct macvlan_dev *vlan = netdev_priv(dev);
218         struct macvtap_queue *q, *qlist[MAX_MACVTAP_QUEUES];
219         int i, j = 0;
220
221         /* macvtap_put_queue can free some slots, so go through all slots */
222         spin_lock(&macvtap_lock);
223         for (i = 0; i < MAX_MACVTAP_QUEUES && vlan->numvtaps; i++) {
224                 q = rcu_dereference_protected(vlan->taps[i],
225                                               lockdep_is_held(&macvtap_lock));
226                 if (q) {
227                         qlist[j++] = q;
228                         rcu_assign_pointer(vlan->taps[i], NULL);
229                         rcu_assign_pointer(q->vlan, NULL);
230                         vlan->numvtaps--;
231                 }
232         }
233         BUG_ON(vlan->numvtaps != 0);
234         /* guarantee that any future macvtap_set_queue will fail */
235         vlan->numvtaps = MAX_MACVTAP_QUEUES;
236         spin_unlock(&macvtap_lock);
237
238         synchronize_rcu();
239
240         for (--j; j >= 0; j--)
241                 sock_put(&qlist[j]->sk);
242 }
243
244 /*
245  * Forward happens for data that gets sent from one macvlan
246  * endpoint to another one in bridge mode. We just take
247  * the skb and put it into the receive queue.
248  */
249 static int macvtap_forward(struct net_device *dev, struct sk_buff *skb)
250 {
251         struct macvtap_queue *q = macvtap_get_queue(dev, skb);
252         if (!q)
253                 goto drop;
254
255         if (skb_queue_len(&q->sk.sk_receive_queue) >= dev->tx_queue_len)
256                 goto drop;
257
258         skb_queue_tail(&q->sk.sk_receive_queue, skb);
259         wake_up_interruptible_poll(sk_sleep(&q->sk), POLLIN | POLLRDNORM | POLLRDBAND);
260         return NET_RX_SUCCESS;
261
262 drop:
263         kfree_skb(skb);
264         return NET_RX_DROP;
265 }
266
267 /*
268  * Receive is for data from the external interface (lowerdev),
269  * in case of macvtap, we can treat that the same way as
270  * forward, which macvlan cannot.
271  */
272 static int macvtap_receive(struct sk_buff *skb)
273 {
274         skb_push(skb, ETH_HLEN);
275         return macvtap_forward(skb->dev, skb);
276 }
277
278 static int macvtap_newlink(struct net *src_net,
279                            struct net_device *dev,
280                            struct nlattr *tb[],
281                            struct nlattr *data[])
282 {
283         struct device *classdev;
284         dev_t devt;
285         int err;
286
287         err = macvlan_common_newlink(src_net, dev, tb, data,
288                                      macvtap_receive, macvtap_forward);
289         if (err)
290                 goto out;
291
292         devt = MKDEV(MAJOR(macvtap_major), dev->ifindex);
293
294         classdev = device_create(macvtap_class, &dev->dev, devt,
295                                  dev, "tap%d", dev->ifindex);
296         if (IS_ERR(classdev)) {
297                 err = PTR_ERR(classdev);
298                 macvtap_del_queues(dev);
299         }
300
301 out:
302         return err;
303 }
304
305 static void macvtap_dellink(struct net_device *dev,
306                             struct list_head *head)
307 {
308         device_destroy(macvtap_class,
309                        MKDEV(MAJOR(macvtap_major), dev->ifindex));
310
311         macvtap_del_queues(dev);
312         macvlan_dellink(dev, head);
313 }
314
315 static void macvtap_setup(struct net_device *dev)
316 {
317         macvlan_common_setup(dev);
318         dev->tx_queue_len = TUN_READQ_SIZE;
319 }
320
321 static struct rtnl_link_ops macvtap_link_ops __read_mostly = {
322         .kind           = "macvtap",
323         .setup          = macvtap_setup,
324         .newlink        = macvtap_newlink,
325         .dellink        = macvtap_dellink,
326 };
327
328
329 static void macvtap_sock_write_space(struct sock *sk)
330 {
331         wait_queue_head_t *wqueue;
332
333         if (!sock_writeable(sk) ||
334             !test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
335                 return;
336
337         wqueue = sk_sleep(sk);
338         if (wqueue && waitqueue_active(wqueue))
339                 wake_up_interruptible_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND);
340 }
341
342 static void macvtap_sock_destruct(struct sock *sk)
343 {
344         skb_queue_purge(&sk->sk_receive_queue);
345 }
346
347 static int macvtap_open(struct inode *inode, struct file *file)
348 {
349         struct net *net = current->nsproxy->net_ns;
350         struct net_device *dev = dev_get_by_index(net, iminor(inode));
351         struct macvtap_queue *q;
352         int err;
353
354         err = -ENODEV;
355         if (!dev)
356                 goto out;
357
358         /* check if this is a macvtap device */
359         err = -EINVAL;
360         if (dev->rtnl_link_ops != &macvtap_link_ops)
361                 goto out;
362
363         err = -ENOMEM;
364         q = (struct macvtap_queue *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
365                                              &macvtap_proto);
366         if (!q)
367                 goto out;
368
369         q->sock.wq = &q->wq;
370         init_waitqueue_head(&q->wq.wait);
371         q->sock.type = SOCK_RAW;
372         q->sock.state = SS_CONNECTED;
373         q->sock.file = file;
374         q->sock.ops = &macvtap_socket_ops;
375         sock_init_data(&q->sock, &q->sk);
376         q->sk.sk_write_space = macvtap_sock_write_space;
377         q->sk.sk_destruct = macvtap_sock_destruct;
378         q->flags = IFF_VNET_HDR | IFF_NO_PI | IFF_TAP;
379         q->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
380
381         /*
382          * so far only KVM virtio_net uses macvtap, enable zero copy between
383          * guest kernel and host kernel when lower device supports zerocopy
384          *
385          * The macvlan supports zerocopy iff the lower device supports zero
386          * copy so we don't have to look at the lower device directly.
387          */
388         if ((dev->features & NETIF_F_HIGHDMA) && (dev->features & NETIF_F_SG))
389                 sock_set_flag(&q->sk, SOCK_ZEROCOPY);
390
391         err = macvtap_set_queue(dev, file, q);
392         if (err)
393                 sock_put(&q->sk);
394
395 out:
396         if (dev)
397                 dev_put(dev);
398
399         return err;
400 }
401
402 static int macvtap_release(struct inode *inode, struct file *file)
403 {
404         struct macvtap_queue *q = file->private_data;
405         macvtap_put_queue(q);
406         return 0;
407 }
408
409 static unsigned int macvtap_poll(struct file *file, poll_table * wait)
410 {
411         struct macvtap_queue *q = file->private_data;
412         unsigned int mask = POLLERR;
413
414         if (!q)
415                 goto out;
416
417         mask = 0;
418         poll_wait(file, &q->wq.wait, wait);
419
420         if (!skb_queue_empty(&q->sk.sk_receive_queue))
421                 mask |= POLLIN | POLLRDNORM;
422
423         if (sock_writeable(&q->sk) ||
424             (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &q->sock.flags) &&
425              sock_writeable(&q->sk)))
426                 mask |= POLLOUT | POLLWRNORM;
427
428 out:
429         return mask;
430 }
431
432 static inline struct sk_buff *macvtap_alloc_skb(struct sock *sk, size_t prepad,
433                                                 size_t len, size_t linear,
434                                                 int noblock, int *err)
435 {
436         struct sk_buff *skb;
437
438         /* Under a page?  Don't bother with paged skb. */
439         if (prepad + len < PAGE_SIZE || !linear)
440                 linear = len;
441
442         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
443                                    err);
444         if (!skb)
445                 return NULL;
446
447         skb_reserve(skb, prepad);
448         skb_put(skb, linear);
449         skb->data_len = len - linear;
450         skb->len += len - linear;
451
452         return skb;
453 }
454
455 /* set skb frags from iovec, this can move to core network code for reuse */
456 static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
457                                   int offset, size_t count)
458 {
459         int len = iov_length(from, count) - offset;
460         int copy = skb_headlen(skb);
461         int size, offset1 = 0;
462         int i = 0;
463
464         /* Skip over from offset */
465         while (count && (offset >= from->iov_len)) {
466                 offset -= from->iov_len;
467                 ++from;
468                 --count;
469         }
470
471         /* copy up to skb headlen */
472         while (count && (copy > 0)) {
473                 size = min_t(unsigned int, copy, from->iov_len - offset);
474                 if (copy_from_user(skb->data + offset1, from->iov_base + offset,
475                                    size))
476                         return -EFAULT;
477                 if (copy > size) {
478                         ++from;
479                         --count;
480                 }
481                 copy -= size;
482                 offset1 += size;
483                 offset = 0;
484         }
485
486         if (len == offset1)
487                 return 0;
488
489         while (count--) {
490                 struct page *page[MAX_SKB_FRAGS];
491                 int num_pages;
492                 unsigned long base;
493
494                 len = from->iov_len - offset1;
495                 if (!len) {
496                         offset1 = 0;
497                         ++from;
498                         continue;
499                 }
500                 base = (unsigned long)from->iov_base + offset1;
501                 size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
502                 num_pages = get_user_pages_fast(base, size, 0, &page[i]);
503                 if ((num_pages != size) ||
504                     (num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags))
505                         /* put_page is in skb free */
506                         return -EFAULT;
507                 skb->data_len += len;
508                 skb->len += len;
509                 skb->truesize += len;
510                 atomic_add(len, &skb->sk->sk_wmem_alloc);
511                 while (len) {
512                         int off = base & ~PAGE_MASK;
513                         int size = min_t(int, len, PAGE_SIZE - off);
514                         __skb_fill_page_desc(skb, i, page[i], off, size);
515                         skb_shinfo(skb)->nr_frags++;
516                         /* increase sk_wmem_alloc */
517                         base += size;
518                         len -= size;
519                         i++;
520                 }
521                 offset1 = 0;
522                 ++from;
523         }
524         return 0;
525 }
526
527 /*
528  * macvtap_skb_from_vnet_hdr and macvtap_skb_to_vnet_hdr should
529  * be shared with the tun/tap driver.
530  */
531 static int macvtap_skb_from_vnet_hdr(struct sk_buff *skb,
532                                      struct virtio_net_hdr *vnet_hdr)
533 {
534         unsigned short gso_type = 0;
535         if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
536                 switch (vnet_hdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
537                 case VIRTIO_NET_HDR_GSO_TCPV4:
538                         gso_type = SKB_GSO_TCPV4;
539                         break;
540                 case VIRTIO_NET_HDR_GSO_TCPV6:
541                         gso_type = SKB_GSO_TCPV6;
542                         break;
543                 case VIRTIO_NET_HDR_GSO_UDP:
544                         gso_type = SKB_GSO_UDP;
545                         break;
546                 default:
547                         return -EINVAL;
548                 }
549
550                 if (vnet_hdr->gso_type & VIRTIO_NET_HDR_GSO_ECN)
551                         gso_type |= SKB_GSO_TCP_ECN;
552
553                 if (vnet_hdr->gso_size == 0)
554                         return -EINVAL;
555         }
556
557         if (vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
558                 if (!skb_partial_csum_set(skb, vnet_hdr->csum_start,
559                                           vnet_hdr->csum_offset))
560                         return -EINVAL;
561         }
562
563         if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
564                 skb_shinfo(skb)->gso_size = vnet_hdr->gso_size;
565                 skb_shinfo(skb)->gso_type = gso_type;
566
567                 /* Header must be checked, and gso_segs computed. */
568                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
569                 skb_shinfo(skb)->gso_segs = 0;
570         }
571         return 0;
572 }
573
574 static int macvtap_skb_to_vnet_hdr(const struct sk_buff *skb,
575                                    struct virtio_net_hdr *vnet_hdr)
576 {
577         memset(vnet_hdr, 0, sizeof(*vnet_hdr));
578
579         if (skb_is_gso(skb)) {
580                 struct skb_shared_info *sinfo = skb_shinfo(skb);
581
582                 /* This is a hint as to how much should be linear. */
583                 vnet_hdr->hdr_len = skb_headlen(skb);
584                 vnet_hdr->gso_size = sinfo->gso_size;
585                 if (sinfo->gso_type & SKB_GSO_TCPV4)
586                         vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
587                 else if (sinfo->gso_type & SKB_GSO_TCPV6)
588                         vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
589                 else if (sinfo->gso_type & SKB_GSO_UDP)
590                         vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_UDP;
591                 else
592                         BUG();
593                 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
594                         vnet_hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
595         } else
596                 vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE;
597
598         if (skb->ip_summed == CHECKSUM_PARTIAL) {
599                 vnet_hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
600                 vnet_hdr->csum_start = skb_checksum_start_offset(skb);
601                 vnet_hdr->csum_offset = skb->csum_offset;
602         } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
603                 vnet_hdr->flags = VIRTIO_NET_HDR_F_DATA_VALID;
604         } /* else everything is zero */
605
606         return 0;
607 }
608
609
610 /* Get packet from user space buffer */
611 static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
612                                 const struct iovec *iv, unsigned long total_len,
613                                 size_t count, int noblock)
614 {
615         struct sk_buff *skb;
616         struct macvlan_dev *vlan;
617         unsigned long len = total_len;
618         int err;
619         struct virtio_net_hdr vnet_hdr = { 0 };
620         int vnet_hdr_len = 0;
621         int copylen;
622         bool zerocopy = false;
623
624         if (q->flags & IFF_VNET_HDR) {
625                 vnet_hdr_len = q->vnet_hdr_sz;
626
627                 err = -EINVAL;
628                 if (len < vnet_hdr_len)
629                         goto err;
630                 len -= vnet_hdr_len;
631
632                 err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,
633                                            sizeof(vnet_hdr));
634                 if (err < 0)
635                         goto err;
636                 if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
637                      vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
638                                                         vnet_hdr.hdr_len)
639                         vnet_hdr.hdr_len = vnet_hdr.csum_start +
640                                                 vnet_hdr.csum_offset + 2;
641                 err = -EINVAL;
642                 if (vnet_hdr.hdr_len > len)
643                         goto err;
644         }
645
646         err = -EINVAL;
647         if (unlikely(len < ETH_HLEN))
648                 goto err;
649
650         if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))
651                 zerocopy = true;
652
653         if (zerocopy) {
654                 /* There are 256 bytes to be copied in skb, so there is enough
655                  * room for skb expand head in case it is used.
656                  * The rest buffer is mapped from userspace.
657                  */
658                 copylen = vnet_hdr.hdr_len;
659                 if (!copylen)
660                         copylen = GOODCOPY_LEN;
661         } else
662                 copylen = len;
663
664         skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,
665                                 vnet_hdr.hdr_len, noblock, &err);
666         if (!skb)
667                 goto err;
668
669         if (zerocopy) {
670                 err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);
671                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
672         } else
673                 err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,
674                                                    len);
675         if (err)
676                 goto err_kfree;
677
678         skb_set_network_header(skb, ETH_HLEN);
679         skb_reset_mac_header(skb);
680         skb->protocol = eth_hdr(skb)->h_proto;
681
682         if (vnet_hdr_len) {
683                 err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);
684                 if (err)
685                         goto err_kfree;
686         }
687
688         rcu_read_lock_bh();
689         vlan = rcu_dereference_bh(q->vlan);
690         /* copy skb_ubuf_info for callback when skb has no error */
691         if (zerocopy)
692                 skb_shinfo(skb)->destructor_arg = m->msg_control;
693         if (vlan)
694                 macvlan_start_xmit(skb, vlan->dev);
695         else
696                 kfree_skb(skb);
697         rcu_read_unlock_bh();
698
699         return total_len;
700
701 err_kfree:
702         kfree_skb(skb);
703
704 err:
705         rcu_read_lock_bh();
706         vlan = rcu_dereference_bh(q->vlan);
707         if (vlan)
708                 vlan->dev->stats.tx_dropped++;
709         rcu_read_unlock_bh();
710
711         return err;
712 }
713
714 static ssize_t macvtap_aio_write(struct kiocb *iocb, const struct iovec *iv,
715                                  unsigned long count, loff_t pos)
716 {
717         struct file *file = iocb->ki_filp;
718         ssize_t result = -ENOLINK;
719         struct macvtap_queue *q = file->private_data;
720
721         result = macvtap_get_user(q, NULL, iv, iov_length(iv, count), count,
722                                   file->f_flags & O_NONBLOCK);
723         return result;
724 }
725
726 /* Put packet to the user space buffer */
727 static ssize_t macvtap_put_user(struct macvtap_queue *q,
728                                 const struct sk_buff *skb,
729                                 const struct iovec *iv, int len)
730 {
731         struct macvlan_dev *vlan;
732         int ret;
733         int vnet_hdr_len = 0;
734
735         if (q->flags & IFF_VNET_HDR) {
736                 struct virtio_net_hdr vnet_hdr;
737                 vnet_hdr_len = q->vnet_hdr_sz;
738                 if ((len -= vnet_hdr_len) < 0)
739                         return -EINVAL;
740
741                 ret = macvtap_skb_to_vnet_hdr(skb, &vnet_hdr);
742                 if (ret)
743                         return ret;
744
745                 if (memcpy_toiovecend(iv, (void *)&vnet_hdr, 0, sizeof(vnet_hdr)))
746                         return -EFAULT;
747         }
748
749         len = min_t(int, skb->len, len);
750
751         ret = skb_copy_datagram_const_iovec(skb, 0, iv, vnet_hdr_len, len);
752
753         rcu_read_lock_bh();
754         vlan = rcu_dereference_bh(q->vlan);
755         if (vlan)
756                 macvlan_count_rx(vlan, len, ret == 0, 0);
757         rcu_read_unlock_bh();
758
759         return ret ? ret : (len + vnet_hdr_len);
760 }
761
762 static ssize_t macvtap_do_read(struct macvtap_queue *q, struct kiocb *iocb,
763                                const struct iovec *iv, unsigned long len,
764                                int noblock)
765 {
766         DECLARE_WAITQUEUE(wait, current);
767         struct sk_buff *skb;
768         ssize_t ret = 0;
769
770         add_wait_queue(sk_sleep(&q->sk), &wait);
771         while (len) {
772                 current->state = TASK_INTERRUPTIBLE;
773
774                 /* Read frames from the queue */
775                 skb = skb_dequeue(&q->sk.sk_receive_queue);
776                 if (!skb) {
777                         if (noblock) {
778                                 ret = -EAGAIN;
779                                 break;
780                         }
781                         if (signal_pending(current)) {
782                                 ret = -ERESTARTSYS;
783                                 break;
784                         }
785                         /* Nothing to read, let's sleep */
786                         schedule();
787                         continue;
788                 }
789                 ret = macvtap_put_user(q, skb, iv, len);
790                 kfree_skb(skb);
791                 break;
792         }
793
794         current->state = TASK_RUNNING;
795         remove_wait_queue(sk_sleep(&q->sk), &wait);
796         return ret;
797 }
798
799 static ssize_t macvtap_aio_read(struct kiocb *iocb, const struct iovec *iv,
800                                 unsigned long count, loff_t pos)
801 {
802         struct file *file = iocb->ki_filp;
803         struct macvtap_queue *q = file->private_data;
804         ssize_t len, ret = 0;
805
806         len = iov_length(iv, count);
807         if (len < 0) {
808                 ret = -EINVAL;
809                 goto out;
810         }
811
812         ret = macvtap_do_read(q, iocb, iv, len, file->f_flags & O_NONBLOCK);
813         ret = min_t(ssize_t, ret, len); /* XXX copied from tun.c. Why? */
814 out:
815         return ret;
816 }
817
818 /*
819  * provide compatibility with generic tun/tap interface
820  */
821 static long macvtap_ioctl(struct file *file, unsigned int cmd,
822                           unsigned long arg)
823 {
824         struct macvtap_queue *q = file->private_data;
825         struct macvlan_dev *vlan;
826         void __user *argp = (void __user *)arg;
827         struct ifreq __user *ifr = argp;
828         unsigned int __user *up = argp;
829         unsigned int u;
830         int __user *sp = argp;
831         int s;
832         int ret;
833
834         switch (cmd) {
835         case TUNSETIFF:
836                 /* ignore the name, just look at flags */
837                 if (get_user(u, &ifr->ifr_flags))
838                         return -EFAULT;
839
840                 ret = 0;
841                 if ((u & ~IFF_VNET_HDR) != (IFF_NO_PI | IFF_TAP))
842                         ret = -EINVAL;
843                 else
844                         q->flags = u;
845
846                 return ret;
847
848         case TUNGETIFF:
849                 rcu_read_lock_bh();
850                 vlan = rcu_dereference_bh(q->vlan);
851                 if (vlan)
852                         dev_hold(vlan->dev);
853                 rcu_read_unlock_bh();
854
855                 if (!vlan)
856                         return -ENOLINK;
857
858                 ret = 0;
859                 if (copy_to_user(&ifr->ifr_name, vlan->dev->name, IFNAMSIZ) ||
860                     put_user(q->flags, &ifr->ifr_flags))
861                         ret = -EFAULT;
862                 dev_put(vlan->dev);
863                 return ret;
864
865         case TUNGETFEATURES:
866                 if (put_user(IFF_TAP | IFF_NO_PI | IFF_VNET_HDR, up))
867                         return -EFAULT;
868                 return 0;
869
870         case TUNSETSNDBUF:
871                 if (get_user(u, up))
872                         return -EFAULT;
873
874                 q->sk.sk_sndbuf = u;
875                 return 0;
876
877         case TUNGETVNETHDRSZ:
878                 s = q->vnet_hdr_sz;
879                 if (put_user(s, sp))
880                         return -EFAULT;
881                 return 0;
882
883         case TUNSETVNETHDRSZ:
884                 if (get_user(s, sp))
885                         return -EFAULT;
886                 if (s < (int)sizeof(struct virtio_net_hdr))
887                         return -EINVAL;
888
889                 q->vnet_hdr_sz = s;
890                 return 0;
891
892         case TUNSETOFFLOAD:
893                 /* let the user check for future flags */
894                 if (arg & ~(TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 |
895                             TUN_F_TSO_ECN | TUN_F_UFO))
896                         return -EINVAL;
897
898                 /* TODO: only accept frames with the features that
899                          got enabled for forwarded frames */
900                 if (!(q->flags & IFF_VNET_HDR))
901                         return  -EINVAL;
902                 return 0;
903
904         default:
905                 return -EINVAL;
906         }
907 }
908
909 #ifdef CONFIG_COMPAT
910 static long macvtap_compat_ioctl(struct file *file, unsigned int cmd,
911                                  unsigned long arg)
912 {
913         return macvtap_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
914 }
915 #endif
916
917 static const struct file_operations macvtap_fops = {
918         .owner          = THIS_MODULE,
919         .open           = macvtap_open,
920         .release        = macvtap_release,
921         .aio_read       = macvtap_aio_read,
922         .aio_write      = macvtap_aio_write,
923         .poll           = macvtap_poll,
924         .llseek         = no_llseek,
925         .unlocked_ioctl = macvtap_ioctl,
926 #ifdef CONFIG_COMPAT
927         .compat_ioctl   = macvtap_compat_ioctl,
928 #endif
929 };
930
931 static int macvtap_sendmsg(struct kiocb *iocb, struct socket *sock,
932                            struct msghdr *m, size_t total_len)
933 {
934         struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
935         return macvtap_get_user(q, m, m->msg_iov, total_len, m->msg_iovlen,
936                             m->msg_flags & MSG_DONTWAIT);
937 }
938
939 static int macvtap_recvmsg(struct kiocb *iocb, struct socket *sock,
940                            struct msghdr *m, size_t total_len,
941                            int flags)
942 {
943         struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
944         int ret;
945         if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
946                 return -EINVAL;
947         ret = macvtap_do_read(q, iocb, m->msg_iov, total_len,
948                           flags & MSG_DONTWAIT);
949         if (ret > total_len) {
950                 m->msg_flags |= MSG_TRUNC;
951                 ret = flags & MSG_TRUNC ? ret : total_len;
952         }
953         return ret;
954 }
955
956 /* Ops structure to mimic raw sockets with tun */
957 static const struct proto_ops macvtap_socket_ops = {
958         .sendmsg = macvtap_sendmsg,
959         .recvmsg = macvtap_recvmsg,
960 };
961
962 /* Get an underlying socket object from tun file.  Returns error unless file is
963  * attached to a device.  The returned object works like a packet socket, it
964  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
965  * holding a reference to the file for as long as the socket is in use. */
966 struct socket *macvtap_get_socket(struct file *file)
967 {
968         struct macvtap_queue *q;
969         if (file->f_op != &macvtap_fops)
970                 return ERR_PTR(-EINVAL);
971         q = file->private_data;
972         if (!q)
973                 return ERR_PTR(-EBADFD);
974         return &q->sock;
975 }
976 EXPORT_SYMBOL_GPL(macvtap_get_socket);
977
978 static int macvtap_init(void)
979 {
980         int err;
981
982         err = alloc_chrdev_region(&macvtap_major, 0,
983                                 MACVTAP_NUM_DEVS, "macvtap");
984         if (err)
985                 goto out1;
986
987         cdev_init(&macvtap_cdev, &macvtap_fops);
988         err = cdev_add(&macvtap_cdev, macvtap_major, MACVTAP_NUM_DEVS);
989         if (err)
990                 goto out2;
991
992         macvtap_class = class_create(THIS_MODULE, "macvtap");
993         if (IS_ERR(macvtap_class)) {
994                 err = PTR_ERR(macvtap_class);
995                 goto out3;
996         }
997
998         err = macvlan_link_register(&macvtap_link_ops);
999         if (err)
1000                 goto out4;
1001
1002         return 0;
1003
1004 out4:
1005         class_unregister(macvtap_class);
1006 out3:
1007         cdev_del(&macvtap_cdev);
1008 out2:
1009         unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
1010 out1:
1011         return err;
1012 }
1013 module_init(macvtap_init);
1014
1015 static void macvtap_exit(void)
1016 {
1017         rtnl_link_unregister(&macvtap_link_ops);
1018         class_unregister(macvtap_class);
1019         cdev_del(&macvtap_cdev);
1020         unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
1021 }
1022 module_exit(macvtap_exit);
1023
1024 MODULE_ALIAS_RTNL_LINK("macvtap");
1025 MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>");
1026 MODULE_LICENSE("GPL");