]> Pileus Git - ~andy/linux/blob - drivers/net/tun.c
tuntap: move socket to tun_file
[~andy/linux] / drivers / net / tun.c
1 /*
2  *  TUN - Universal TUN/TAP device driver.
3  *  Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
16  */
17
18 /*
19  *  Changes:
20  *
21  *  Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
22  *    Add TUNSETLINK ioctl to set the link encapsulation
23  *
24  *  Mark Smith <markzzzsmith@yahoo.com.au>
25  *    Use eth_random_addr() for tap MAC address.
26  *
27  *  Harald Roelle <harald.roelle@ifi.lmu.de>  2004/04/20
28  *    Fixes in packet dropping, queue length setting and queue wakeup.
29  *    Increased default tx queue length.
30  *    Added ethtool API.
31  *    Minor cleanups
32  *
33  *  Daniel Podlejski <underley@underley.eu.org>
34  *    Modifications for 2.3.99-pre5 kernel.
35  */
36
37 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
38
39 #define DRV_NAME        "tun"
40 #define DRV_VERSION     "1.6"
41 #define DRV_DESCRIPTION "Universal TUN/TAP device driver"
42 #define DRV_COPYRIGHT   "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
43
44 #include <linux/module.h>
45 #include <linux/errno.h>
46 #include <linux/kernel.h>
47 #include <linux/major.h>
48 #include <linux/slab.h>
49 #include <linux/poll.h>
50 #include <linux/fcntl.h>
51 #include <linux/init.h>
52 #include <linux/skbuff.h>
53 #include <linux/netdevice.h>
54 #include <linux/etherdevice.h>
55 #include <linux/miscdevice.h>
56 #include <linux/ethtool.h>
57 #include <linux/rtnetlink.h>
58 #include <linux/compat.h>
59 #include <linux/if.h>
60 #include <linux/if_arp.h>
61 #include <linux/if_ether.h>
62 #include <linux/if_tun.h>
63 #include <linux/crc32.h>
64 #include <linux/nsproxy.h>
65 #include <linux/virtio_net.h>
66 #include <linux/rcupdate.h>
67 #include <net/net_namespace.h>
68 #include <net/netns/generic.h>
69 #include <net/rtnetlink.h>
70 #include <net/sock.h>
71
72 #include <asm/uaccess.h>
73
74 /* Uncomment to enable debugging */
75 /* #define TUN_DEBUG 1 */
76
77 #ifdef TUN_DEBUG
78 static int debug;
79
80 #define tun_debug(level, tun, fmt, args...)                     \
81 do {                                                            \
82         if (tun->debug)                                         \
83                 netdev_printk(level, tun->dev, fmt, ##args);    \
84 } while (0)
85 #define DBG1(level, fmt, args...)                               \
86 do {                                                            \
87         if (debug == 2)                                         \
88                 printk(level fmt, ##args);                      \
89 } while (0)
90 #else
91 #define tun_debug(level, tun, fmt, args...)                     \
92 do {                                                            \
93         if (0)                                                  \
94                 netdev_printk(level, tun->dev, fmt, ##args);    \
95 } while (0)
96 #define DBG1(level, fmt, args...)                               \
97 do {                                                            \
98         if (0)                                                  \
99                 printk(level fmt, ##args);                      \
100 } while (0)
101 #endif
102
103 #define GOODCOPY_LEN 128
104
105 #define FLT_EXACT_COUNT 8
106 struct tap_filter {
107         unsigned int    count;    /* Number of addrs. Zero means disabled */
108         u32             mask[2];  /* Mask of the hashed addrs */
109         unsigned char   addr[FLT_EXACT_COUNT][ETH_ALEN];
110 };
111
112 /* A tun_file connects an open character device to a tuntap netdevice. It
113  * also contains all socket related strctures (except sock_fprog and tap_filter)
114  * to serve as one transmit queue for tuntap device. The sock_fprog and
115  * tap_filter were kept in tun_struct since they were used for filtering for the
116  * netdevice not for a specific queue (at least I didn't see the reqirement for
117  * this).
118  */
119 struct tun_file {
120         struct sock sk;
121         struct socket socket;
122         struct socket_wq wq;
123         atomic_t count;
124         struct tun_struct *tun;
125         struct net *net;
126         struct fasync_struct *fasync;
127         /* only used for fasnyc */
128         unsigned int flags;
129 };
130
131 /* Since the socket were moved to tun_file, to preserve the behavior of persist
132  * device, socket fileter, sndbuf and vnet header size were restore when the
133  * file were attached to a persist device.
134  */
135 struct tun_struct {
136         struct tun_file         *tfile;
137         unsigned int            flags;
138         kuid_t                  owner;
139         kgid_t                  group;
140
141         struct net_device       *dev;
142         netdev_features_t       set_features;
143 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
144                           NETIF_F_TSO6|NETIF_F_UFO)
145
146         int                     vnet_hdr_sz;
147         int                     sndbuf;
148         struct tap_filter       txflt;
149         struct sock_fprog       fprog;
150         /* protected by rtnl lock */
151         bool                    filter_attached;
152 #ifdef TUN_DEBUG
153         int debug;
154 #endif
155 };
156
157 static int tun_attach(struct tun_struct *tun, struct file *file)
158 {
159         struct tun_file *tfile = file->private_data;
160         int err;
161
162         ASSERT_RTNL();
163
164         netif_tx_lock_bh(tun->dev);
165
166         err = -EINVAL;
167         if (tfile->tun)
168                 goto out;
169
170         err = -EBUSY;
171         if (tun->tfile)
172                 goto out;
173
174         err = 0;
175
176         /* Re-attach filter when attaching to a persist device */
177         if (tun->filter_attached == true) {
178                 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
179                 if (!err)
180                         goto out;
181         }
182         tfile->tun = tun;
183         tfile->socket.sk->sk_sndbuf = tun->sndbuf;
184         tun->tfile = tfile;
185         netif_carrier_on(tun->dev);
186         dev_hold(tun->dev);
187         sock_hold(&tfile->sk);
188         atomic_inc(&tfile->count);
189
190 out:
191         netif_tx_unlock_bh(tun->dev);
192         return err;
193 }
194
195 static void __tun_detach(struct tun_struct *tun)
196 {
197         struct tun_file *tfile = tun->tfile;
198         /* Detach from net device */
199         netif_tx_lock_bh(tun->dev);
200         netif_carrier_off(tun->dev);
201         tun->tfile = NULL;
202         tfile->tun = NULL;
203         netif_tx_unlock_bh(tun->dev);
204
205         /* Drop read queue */
206         skb_queue_purge(&tfile->socket.sk->sk_receive_queue);
207
208         /* Drop the extra count on the net device */
209         dev_put(tun->dev);
210 }
211
212 static void tun_detach(struct tun_struct *tun)
213 {
214         rtnl_lock();
215         __tun_detach(tun);
216         rtnl_unlock();
217 }
218
219 static struct tun_struct *__tun_get(struct tun_file *tfile)
220 {
221         struct tun_struct *tun = NULL;
222
223         if (atomic_inc_not_zero(&tfile->count))
224                 tun = tfile->tun;
225
226         return tun;
227 }
228
229 static struct tun_struct *tun_get(struct file *file)
230 {
231         return __tun_get(file->private_data);
232 }
233
234 static void tun_put(struct tun_struct *tun)
235 {
236         struct tun_file *tfile = tun->tfile;
237
238         if (atomic_dec_and_test(&tfile->count))
239                 tun_detach(tfile->tun);
240 }
241
242 /* TAP filtering */
243 static void addr_hash_set(u32 *mask, const u8 *addr)
244 {
245         int n = ether_crc(ETH_ALEN, addr) >> 26;
246         mask[n >> 5] |= (1 << (n & 31));
247 }
248
249 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
250 {
251         int n = ether_crc(ETH_ALEN, addr) >> 26;
252         return mask[n >> 5] & (1 << (n & 31));
253 }
254
255 static int update_filter(struct tap_filter *filter, void __user *arg)
256 {
257         struct { u8 u[ETH_ALEN]; } *addr;
258         struct tun_filter uf;
259         int err, alen, n, nexact;
260
261         if (copy_from_user(&uf, arg, sizeof(uf)))
262                 return -EFAULT;
263
264         if (!uf.count) {
265                 /* Disabled */
266                 filter->count = 0;
267                 return 0;
268         }
269
270         alen = ETH_ALEN * uf.count;
271         addr = kmalloc(alen, GFP_KERNEL);
272         if (!addr)
273                 return -ENOMEM;
274
275         if (copy_from_user(addr, arg + sizeof(uf), alen)) {
276                 err = -EFAULT;
277                 goto done;
278         }
279
280         /* The filter is updated without holding any locks. Which is
281          * perfectly safe. We disable it first and in the worst
282          * case we'll accept a few undesired packets. */
283         filter->count = 0;
284         wmb();
285
286         /* Use first set of addresses as an exact filter */
287         for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
288                 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
289
290         nexact = n;
291
292         /* Remaining multicast addresses are hashed,
293          * unicast will leave the filter disabled. */
294         memset(filter->mask, 0, sizeof(filter->mask));
295         for (; n < uf.count; n++) {
296                 if (!is_multicast_ether_addr(addr[n].u)) {
297                         err = 0; /* no filter */
298                         goto done;
299                 }
300                 addr_hash_set(filter->mask, addr[n].u);
301         }
302
303         /* For ALLMULTI just set the mask to all ones.
304          * This overrides the mask populated above. */
305         if ((uf.flags & TUN_FLT_ALLMULTI))
306                 memset(filter->mask, ~0, sizeof(filter->mask));
307
308         /* Now enable the filter */
309         wmb();
310         filter->count = nexact;
311
312         /* Return the number of exact filters */
313         err = nexact;
314
315 done:
316         kfree(addr);
317         return err;
318 }
319
320 /* Returns: 0 - drop, !=0 - accept */
321 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
322 {
323         /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
324          * at this point. */
325         struct ethhdr *eh = (struct ethhdr *) skb->data;
326         int i;
327
328         /* Exact match */
329         for (i = 0; i < filter->count; i++)
330                 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
331                         return 1;
332
333         /* Inexact match (multicast only) */
334         if (is_multicast_ether_addr(eh->h_dest))
335                 return addr_hash_test(filter->mask, eh->h_dest);
336
337         return 0;
338 }
339
340 /*
341  * Checks whether the packet is accepted or not.
342  * Returns: 0 - drop, !=0 - accept
343  */
344 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
345 {
346         if (!filter->count)
347                 return 1;
348
349         return run_filter(filter, skb);
350 }
351
352 /* Network device part of the driver */
353
354 static const struct ethtool_ops tun_ethtool_ops;
355
356 /* Net device detach from fd. */
357 static void tun_net_uninit(struct net_device *dev)
358 {
359         struct tun_struct *tun = netdev_priv(dev);
360         struct tun_file *tfile = tun->tfile;
361
362         /* Inform the methods they need to stop using the dev.
363          */
364         if (tfile) {
365                 wake_up_all(&tfile->wq.wait);
366                 if (atomic_dec_and_test(&tfile->count))
367                         __tun_detach(tun);
368         }
369 }
370
371 /* Net device open. */
372 static int tun_net_open(struct net_device *dev)
373 {
374         netif_start_queue(dev);
375         return 0;
376 }
377
378 /* Net device close. */
379 static int tun_net_close(struct net_device *dev)
380 {
381         netif_stop_queue(dev);
382         return 0;
383 }
384
385 /* Net device start xmit */
386 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
387 {
388         struct tun_struct *tun = netdev_priv(dev);
389         struct tun_file *tfile = tun->tfile;
390
391         tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
392
393         /* Drop packet if interface is not attached */
394         if (!tfile)
395                 goto drop;
396
397         /* Drop if the filter does not like it.
398          * This is a noop if the filter is disabled.
399          * Filter can be enabled only for the TAP devices. */
400         if (!check_filter(&tun->txflt, skb))
401                 goto drop;
402
403         if (tfile->socket.sk->sk_filter &&
404             sk_filter(tfile->socket.sk, skb))
405                 goto drop;
406
407         if (skb_queue_len(&tfile->socket.sk->sk_receive_queue)
408             >= dev->tx_queue_len) {
409                 if (!(tun->flags & TUN_ONE_QUEUE)) {
410                         /* Normal queueing mode. */
411                         /* Packet scheduler handles dropping of further packets. */
412                         netif_stop_queue(dev);
413
414                         /* We won't see all dropped packets individually, so overrun
415                          * error is more appropriate. */
416                         dev->stats.tx_fifo_errors++;
417                 } else {
418                         /* Single queue mode.
419                          * Driver handles dropping of all packets itself. */
420                         goto drop;
421                 }
422         }
423
424         /* Orphan the skb - required as we might hang on to it
425          * for indefinite time. */
426         if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
427                 goto drop;
428         skb_orphan(skb);
429
430         /* Enqueue packet */
431         skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
432
433         /* Notify and wake up reader process */
434         if (tfile->flags & TUN_FASYNC)
435                 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
436         wake_up_interruptible_poll(&tfile->wq.wait, POLLIN |
437                                    POLLRDNORM | POLLRDBAND);
438         return NETDEV_TX_OK;
439
440 drop:
441         dev->stats.tx_dropped++;
442         kfree_skb(skb);
443         return NETDEV_TX_OK;
444 }
445
446 static void tun_net_mclist(struct net_device *dev)
447 {
448         /*
449          * This callback is supposed to deal with mc filter in
450          * _rx_ path and has nothing to do with the _tx_ path.
451          * In rx path we always accept everything userspace gives us.
452          */
453 }
454
455 #define MIN_MTU 68
456 #define MAX_MTU 65535
457
458 static int
459 tun_net_change_mtu(struct net_device *dev, int new_mtu)
460 {
461         if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
462                 return -EINVAL;
463         dev->mtu = new_mtu;
464         return 0;
465 }
466
467 static netdev_features_t tun_net_fix_features(struct net_device *dev,
468         netdev_features_t features)
469 {
470         struct tun_struct *tun = netdev_priv(dev);
471
472         return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
473 }
474 #ifdef CONFIG_NET_POLL_CONTROLLER
475 static void tun_poll_controller(struct net_device *dev)
476 {
477         /*
478          * Tun only receives frames when:
479          * 1) the char device endpoint gets data from user space
480          * 2) the tun socket gets a sendmsg call from user space
481          * Since both of those are syncronous operations, we are guaranteed
482          * never to have pending data when we poll for it
483          * so theres nothing to do here but return.
484          * We need this though so netpoll recognizes us as an interface that
485          * supports polling, which enables bridge devices in virt setups to
486          * still use netconsole
487          */
488         return;
489 }
490 #endif
491 static const struct net_device_ops tun_netdev_ops = {
492         .ndo_uninit             = tun_net_uninit,
493         .ndo_open               = tun_net_open,
494         .ndo_stop               = tun_net_close,
495         .ndo_start_xmit         = tun_net_xmit,
496         .ndo_change_mtu         = tun_net_change_mtu,
497         .ndo_fix_features       = tun_net_fix_features,
498 #ifdef CONFIG_NET_POLL_CONTROLLER
499         .ndo_poll_controller    = tun_poll_controller,
500 #endif
501 };
502
503 static const struct net_device_ops tap_netdev_ops = {
504         .ndo_uninit             = tun_net_uninit,
505         .ndo_open               = tun_net_open,
506         .ndo_stop               = tun_net_close,
507         .ndo_start_xmit         = tun_net_xmit,
508         .ndo_change_mtu         = tun_net_change_mtu,
509         .ndo_fix_features       = tun_net_fix_features,
510         .ndo_set_rx_mode        = tun_net_mclist,
511         .ndo_set_mac_address    = eth_mac_addr,
512         .ndo_validate_addr      = eth_validate_addr,
513 #ifdef CONFIG_NET_POLL_CONTROLLER
514         .ndo_poll_controller    = tun_poll_controller,
515 #endif
516 };
517
518 /* Initialize net device. */
519 static void tun_net_init(struct net_device *dev)
520 {
521         struct tun_struct *tun = netdev_priv(dev);
522
523         switch (tun->flags & TUN_TYPE_MASK) {
524         case TUN_TUN_DEV:
525                 dev->netdev_ops = &tun_netdev_ops;
526
527                 /* Point-to-Point TUN Device */
528                 dev->hard_header_len = 0;
529                 dev->addr_len = 0;
530                 dev->mtu = 1500;
531
532                 /* Zero header length */
533                 dev->type = ARPHRD_NONE;
534                 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
535                 dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
536                 break;
537
538         case TUN_TAP_DEV:
539                 dev->netdev_ops = &tap_netdev_ops;
540                 /* Ethernet TAP Device */
541                 ether_setup(dev);
542                 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
543
544                 eth_hw_addr_random(dev);
545
546                 dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
547                 break;
548         }
549 }
550
551 /* Character device part */
552
553 /* Poll */
554 static unsigned int tun_chr_poll(struct file *file, poll_table * wait)
555 {
556         struct tun_file *tfile = file->private_data;
557         struct tun_struct *tun = __tun_get(tfile);
558         struct sock *sk;
559         unsigned int mask = 0;
560
561         if (!tun)
562                 return POLLERR;
563
564         sk = tfile->socket.sk;
565
566         tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
567
568         poll_wait(file, &tfile->wq.wait, wait);
569
570         if (!skb_queue_empty(&sk->sk_receive_queue))
571                 mask |= POLLIN | POLLRDNORM;
572
573         if (sock_writeable(sk) ||
574             (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
575              sock_writeable(sk)))
576                 mask |= POLLOUT | POLLWRNORM;
577
578         if (tun->dev->reg_state != NETREG_REGISTERED)
579                 mask = POLLERR;
580
581         tun_put(tun);
582         return mask;
583 }
584
585 /* prepad is the amount to reserve at front.  len is length after that.
586  * linear is a hint as to how much to copy (usually headers). */
587 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
588                                      size_t prepad, size_t len,
589                                      size_t linear, int noblock)
590 {
591         struct sock *sk = tfile->socket.sk;
592         struct sk_buff *skb;
593         int err;
594
595         /* Under a page?  Don't bother with paged skb. */
596         if (prepad + len < PAGE_SIZE || !linear)
597                 linear = len;
598
599         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
600                                    &err);
601         if (!skb)
602                 return ERR_PTR(err);
603
604         skb_reserve(skb, prepad);
605         skb_put(skb, linear);
606         skb->data_len = len - linear;
607         skb->len += len - linear;
608
609         return skb;
610 }
611
612 /* set skb frags from iovec, this can move to core network code for reuse */
613 static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
614                                   int offset, size_t count)
615 {
616         int len = iov_length(from, count) - offset;
617         int copy = skb_headlen(skb);
618         int size, offset1 = 0;
619         int i = 0;
620
621         /* Skip over from offset */
622         while (count && (offset >= from->iov_len)) {
623                 offset -= from->iov_len;
624                 ++from;
625                 --count;
626         }
627
628         /* copy up to skb headlen */
629         while (count && (copy > 0)) {
630                 size = min_t(unsigned int, copy, from->iov_len - offset);
631                 if (copy_from_user(skb->data + offset1, from->iov_base + offset,
632                                    size))
633                         return -EFAULT;
634                 if (copy > size) {
635                         ++from;
636                         --count;
637                         offset = 0;
638                 } else
639                         offset += size;
640                 copy -= size;
641                 offset1 += size;
642         }
643
644         if (len == offset1)
645                 return 0;
646
647         while (count--) {
648                 struct page *page[MAX_SKB_FRAGS];
649                 int num_pages;
650                 unsigned long base;
651                 unsigned long truesize;
652
653                 len = from->iov_len - offset;
654                 if (!len) {
655                         offset = 0;
656                         ++from;
657                         continue;
658                 }
659                 base = (unsigned long)from->iov_base + offset;
660                 size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
661                 if (i + size > MAX_SKB_FRAGS)
662                         return -EMSGSIZE;
663                 num_pages = get_user_pages_fast(base, size, 0, &page[i]);
664                 if (num_pages != size) {
665                         for (i = 0; i < num_pages; i++)
666                                 put_page(page[i]);
667                         return -EFAULT;
668                 }
669                 truesize = size * PAGE_SIZE;
670                 skb->data_len += len;
671                 skb->len += len;
672                 skb->truesize += truesize;
673                 atomic_add(truesize, &skb->sk->sk_wmem_alloc);
674                 while (len) {
675                         int off = base & ~PAGE_MASK;
676                         int size = min_t(int, len, PAGE_SIZE - off);
677                         __skb_fill_page_desc(skb, i, page[i], off, size);
678                         skb_shinfo(skb)->nr_frags++;
679                         /* increase sk_wmem_alloc */
680                         base += size;
681                         len -= size;
682                         i++;
683                 }
684                 offset = 0;
685                 ++from;
686         }
687         return 0;
688 }
689
690 /* Get packet from user space buffer */
691 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
692                             void *msg_control, const struct iovec *iv,
693                             size_t total_len, size_t count, int noblock)
694 {
695         struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
696         struct sk_buff *skb;
697         size_t len = total_len, align = NET_SKB_PAD;
698         struct virtio_net_hdr gso = { 0 };
699         int offset = 0;
700         int copylen;
701         bool zerocopy = false;
702         int err;
703
704         if (!(tun->flags & TUN_NO_PI)) {
705                 if ((len -= sizeof(pi)) > total_len)
706                         return -EINVAL;
707
708                 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
709                         return -EFAULT;
710                 offset += sizeof(pi);
711         }
712
713         if (tun->flags & TUN_VNET_HDR) {
714                 if ((len -= tun->vnet_hdr_sz) > total_len)
715                         return -EINVAL;
716
717                 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
718                         return -EFAULT;
719
720                 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
721                     gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
722                         gso.hdr_len = gso.csum_start + gso.csum_offset + 2;
723
724                 if (gso.hdr_len > len)
725                         return -EINVAL;
726                 offset += tun->vnet_hdr_sz;
727         }
728
729         if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
730                 align += NET_IP_ALIGN;
731                 if (unlikely(len < ETH_HLEN ||
732                              (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
733                         return -EINVAL;
734         }
735
736         if (msg_control)
737                 zerocopy = true;
738
739         if (zerocopy) {
740                 /* Userspace may produce vectors with count greater than
741                  * MAX_SKB_FRAGS, so we need to linearize parts of the skb
742                  * to let the rest of data to be fit in the frags.
743                  */
744                 if (count > MAX_SKB_FRAGS) {
745                         copylen = iov_length(iv, count - MAX_SKB_FRAGS);
746                         if (copylen < offset)
747                                 copylen = 0;
748                         else
749                                 copylen -= offset;
750                 } else
751                                 copylen = 0;
752                 /* There are 256 bytes to be copied in skb, so there is enough
753                  * room for skb expand head in case it is used.
754                  * The rest of the buffer is mapped from userspace.
755                  */
756                 if (copylen < gso.hdr_len)
757                         copylen = gso.hdr_len;
758                 if (!copylen)
759                         copylen = GOODCOPY_LEN;
760         } else
761                 copylen = len;
762
763         skb = tun_alloc_skb(tfile, align, copylen, gso.hdr_len, noblock);
764         if (IS_ERR(skb)) {
765                 if (PTR_ERR(skb) != -EAGAIN)
766                         tun->dev->stats.rx_dropped++;
767                 return PTR_ERR(skb);
768         }
769
770         if (zerocopy)
771                 err = zerocopy_sg_from_iovec(skb, iv, offset, count);
772         else
773                 err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
774
775         if (err) {
776                 tun->dev->stats.rx_dropped++;
777                 kfree_skb(skb);
778                 return -EFAULT;
779         }
780
781         if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
782                 if (!skb_partial_csum_set(skb, gso.csum_start,
783                                           gso.csum_offset)) {
784                         tun->dev->stats.rx_frame_errors++;
785                         kfree_skb(skb);
786                         return -EINVAL;
787                 }
788         }
789
790         switch (tun->flags & TUN_TYPE_MASK) {
791         case TUN_TUN_DEV:
792                 if (tun->flags & TUN_NO_PI) {
793                         switch (skb->data[0] & 0xf0) {
794                         case 0x40:
795                                 pi.proto = htons(ETH_P_IP);
796                                 break;
797                         case 0x60:
798                                 pi.proto = htons(ETH_P_IPV6);
799                                 break;
800                         default:
801                                 tun->dev->stats.rx_dropped++;
802                                 kfree_skb(skb);
803                                 return -EINVAL;
804                         }
805                 }
806
807                 skb_reset_mac_header(skb);
808                 skb->protocol = pi.proto;
809                 skb->dev = tun->dev;
810                 break;
811         case TUN_TAP_DEV:
812                 skb->protocol = eth_type_trans(skb, tun->dev);
813                 break;
814         }
815
816         if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
817                 pr_debug("GSO!\n");
818                 switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
819                 case VIRTIO_NET_HDR_GSO_TCPV4:
820                         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
821                         break;
822                 case VIRTIO_NET_HDR_GSO_TCPV6:
823                         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
824                         break;
825                 case VIRTIO_NET_HDR_GSO_UDP:
826                         skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
827                         break;
828                 default:
829                         tun->dev->stats.rx_frame_errors++;
830                         kfree_skb(skb);
831                         return -EINVAL;
832                 }
833
834                 if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
835                         skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
836
837                 skb_shinfo(skb)->gso_size = gso.gso_size;
838                 if (skb_shinfo(skb)->gso_size == 0) {
839                         tun->dev->stats.rx_frame_errors++;
840                         kfree_skb(skb);
841                         return -EINVAL;
842                 }
843
844                 /* Header must be checked, and gso_segs computed. */
845                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
846                 skb_shinfo(skb)->gso_segs = 0;
847         }
848
849         /* copy skb_ubuf_info for callback when skb has no error */
850         if (zerocopy) {
851                 skb_shinfo(skb)->destructor_arg = msg_control;
852                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
853         }
854
855         netif_rx_ni(skb);
856
857         tun->dev->stats.rx_packets++;
858         tun->dev->stats.rx_bytes += len;
859
860         return total_len;
861 }
862
863 static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
864                               unsigned long count, loff_t pos)
865 {
866         struct file *file = iocb->ki_filp;
867         struct tun_struct *tun = tun_get(file);
868         struct tun_file *tfile = file->private_data;
869         ssize_t result;
870
871         if (!tun)
872                 return -EBADFD;
873
874         tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
875
876         result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
877                               count, file->f_flags & O_NONBLOCK);
878
879         tun_put(tun);
880         return result;
881 }
882
883 /* Put packet to the user space buffer */
884 static ssize_t tun_put_user(struct tun_struct *tun,
885                             struct tun_file *tfile,
886                             struct sk_buff *skb,
887                             const struct iovec *iv, int len)
888 {
889         struct tun_pi pi = { 0, skb->protocol };
890         ssize_t total = 0;
891
892         if (!(tun->flags & TUN_NO_PI)) {
893                 if ((len -= sizeof(pi)) < 0)
894                         return -EINVAL;
895
896                 if (len < skb->len) {
897                         /* Packet will be striped */
898                         pi.flags |= TUN_PKT_STRIP;
899                 }
900
901                 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
902                         return -EFAULT;
903                 total += sizeof(pi);
904         }
905
906         if (tun->flags & TUN_VNET_HDR) {
907                 struct virtio_net_hdr gso = { 0 }; /* no info leak */
908                 if ((len -= tun->vnet_hdr_sz) < 0)
909                         return -EINVAL;
910
911                 if (skb_is_gso(skb)) {
912                         struct skb_shared_info *sinfo = skb_shinfo(skb);
913
914                         /* This is a hint as to how much should be linear. */
915                         gso.hdr_len = skb_headlen(skb);
916                         gso.gso_size = sinfo->gso_size;
917                         if (sinfo->gso_type & SKB_GSO_TCPV4)
918                                 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
919                         else if (sinfo->gso_type & SKB_GSO_TCPV6)
920                                 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
921                         else if (sinfo->gso_type & SKB_GSO_UDP)
922                                 gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
923                         else {
924                                 pr_err("unexpected GSO type: "
925                                        "0x%x, gso_size %d, hdr_len %d\n",
926                                        sinfo->gso_type, gso.gso_size,
927                                        gso.hdr_len);
928                                 print_hex_dump(KERN_ERR, "tun: ",
929                                                DUMP_PREFIX_NONE,
930                                                16, 1, skb->head,
931                                                min((int)gso.hdr_len, 64), true);
932                                 WARN_ON_ONCE(1);
933                                 return -EINVAL;
934                         }
935                         if (sinfo->gso_type & SKB_GSO_TCP_ECN)
936                                 gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
937                 } else
938                         gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
939
940                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
941                         gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
942                         gso.csum_start = skb_checksum_start_offset(skb);
943                         gso.csum_offset = skb->csum_offset;
944                 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
945                         gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
946                 } /* else everything is zero */
947
948                 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
949                                                sizeof(gso))))
950                         return -EFAULT;
951                 total += tun->vnet_hdr_sz;
952         }
953
954         len = min_t(int, skb->len, len);
955
956         skb_copy_datagram_const_iovec(skb, 0, iv, total, len);
957         total += skb->len;
958
959         tun->dev->stats.tx_packets++;
960         tun->dev->stats.tx_bytes += len;
961
962         return total;
963 }
964
965 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
966                            struct kiocb *iocb, const struct iovec *iv,
967                            ssize_t len, int noblock)
968 {
969         DECLARE_WAITQUEUE(wait, current);
970         struct sk_buff *skb;
971         ssize_t ret = 0;
972
973         tun_debug(KERN_INFO, tun, "tun_chr_read\n");
974
975         if (unlikely(!noblock))
976                 add_wait_queue(&tfile->wq.wait, &wait);
977         while (len) {
978                 current->state = TASK_INTERRUPTIBLE;
979
980                 /* Read frames from the queue */
981                 if (!(skb = skb_dequeue(&tfile->socket.sk->sk_receive_queue))) {
982                         if (noblock) {
983                                 ret = -EAGAIN;
984                                 break;
985                         }
986                         if (signal_pending(current)) {
987                                 ret = -ERESTARTSYS;
988                                 break;
989                         }
990                         if (tun->dev->reg_state != NETREG_REGISTERED) {
991                                 ret = -EIO;
992                                 break;
993                         }
994
995                         /* Nothing to read, let's sleep */
996                         schedule();
997                         continue;
998                 }
999                 netif_wake_queue(tun->dev);
1000
1001                 ret = tun_put_user(tun, tfile, skb, iv, len);
1002                 kfree_skb(skb);
1003                 break;
1004         }
1005
1006         current->state = TASK_RUNNING;
1007         if (unlikely(!noblock))
1008                 remove_wait_queue(&tfile->wq.wait, &wait);
1009
1010         return ret;
1011 }
1012
1013 static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
1014                             unsigned long count, loff_t pos)
1015 {
1016         struct file *file = iocb->ki_filp;
1017         struct tun_file *tfile = file->private_data;
1018         struct tun_struct *tun = __tun_get(tfile);
1019         ssize_t len, ret;
1020
1021         if (!tun)
1022                 return -EBADFD;
1023         len = iov_length(iv, count);
1024         if (len < 0) {
1025                 ret = -EINVAL;
1026                 goto out;
1027         }
1028
1029         ret = tun_do_read(tun, tfile, iocb, iv, len,
1030                           file->f_flags & O_NONBLOCK);
1031         ret = min_t(ssize_t, ret, len);
1032 out:
1033         tun_put(tun);
1034         return ret;
1035 }
1036
1037 static void tun_setup(struct net_device *dev)
1038 {
1039         struct tun_struct *tun = netdev_priv(dev);
1040
1041         tun->owner = INVALID_UID;
1042         tun->group = INVALID_GID;
1043
1044         dev->ethtool_ops = &tun_ethtool_ops;
1045         dev->destructor = free_netdev;
1046 }
1047
1048 /* Trivial set of netlink ops to allow deleting tun or tap
1049  * device with netlink.
1050  */
1051 static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1052 {
1053         return -EINVAL;
1054 }
1055
1056 static struct rtnl_link_ops tun_link_ops __read_mostly = {
1057         .kind           = DRV_NAME,
1058         .priv_size      = sizeof(struct tun_struct),
1059         .setup          = tun_setup,
1060         .validate       = tun_validate,
1061 };
1062
1063 static void tun_sock_write_space(struct sock *sk)
1064 {
1065         struct tun_file *tfile;
1066         wait_queue_head_t *wqueue;
1067
1068         if (!sock_writeable(sk))
1069                 return;
1070
1071         if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1072                 return;
1073
1074         wqueue = sk_sleep(sk);
1075         if (wqueue && waitqueue_active(wqueue))
1076                 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1077                                                 POLLWRNORM | POLLWRBAND);
1078
1079         tfile = container_of(sk, struct tun_file, sk);
1080         kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1081 }
1082
1083 static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1084                        struct msghdr *m, size_t total_len)
1085 {
1086         int ret;
1087         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1088         struct tun_struct *tun = __tun_get(tfile);
1089
1090         if (!tun)
1091                 return -EBADFD;
1092
1093         ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
1094                            m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
1095         tun_put(tun);
1096         return ret;
1097 }
1098
1099
1100 static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1101                        struct msghdr *m, size_t total_len,
1102                        int flags)
1103 {
1104         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1105         struct tun_struct *tun = __tun_get(tfile);
1106         int ret;
1107
1108         if (!tun)
1109                 return -EBADFD;
1110
1111         if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
1112                 return -EINVAL;
1113         ret = tun_do_read(tun, tfile, iocb, m->msg_iov, total_len,
1114                           flags & MSG_DONTWAIT);
1115         if (ret > total_len) {
1116                 m->msg_flags |= MSG_TRUNC;
1117                 ret = flags & MSG_TRUNC ? ret : total_len;
1118         }
1119         tun_put(tun);
1120         return ret;
1121 }
1122
1123 static int tun_release(struct socket *sock)
1124 {
1125         if (sock->sk)
1126                 sock_put(sock->sk);
1127         return 0;
1128 }
1129
1130 /* Ops structure to mimic raw sockets with tun */
1131 static const struct proto_ops tun_socket_ops = {
1132         .sendmsg = tun_sendmsg,
1133         .recvmsg = tun_recvmsg,
1134         .release = tun_release,
1135 };
1136
1137 static struct proto tun_proto = {
1138         .name           = "tun",
1139         .owner          = THIS_MODULE,
1140         .obj_size       = sizeof(struct tun_file),
1141 };
1142
1143 static int tun_flags(struct tun_struct *tun)
1144 {
1145         int flags = 0;
1146
1147         if (tun->flags & TUN_TUN_DEV)
1148                 flags |= IFF_TUN;
1149         else
1150                 flags |= IFF_TAP;
1151
1152         if (tun->flags & TUN_NO_PI)
1153                 flags |= IFF_NO_PI;
1154
1155         if (tun->flags & TUN_ONE_QUEUE)
1156                 flags |= IFF_ONE_QUEUE;
1157
1158         if (tun->flags & TUN_VNET_HDR)
1159                 flags |= IFF_VNET_HDR;
1160
1161         return flags;
1162 }
1163
1164 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1165                               char *buf)
1166 {
1167         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1168         return sprintf(buf, "0x%x\n", tun_flags(tun));
1169 }
1170
1171 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1172                               char *buf)
1173 {
1174         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1175         return uid_valid(tun->owner)?
1176                 sprintf(buf, "%u\n",
1177                         from_kuid_munged(current_user_ns(), tun->owner)):
1178                 sprintf(buf, "-1\n");
1179 }
1180
1181 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1182                               char *buf)
1183 {
1184         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1185         return gid_valid(tun->group) ?
1186                 sprintf(buf, "%u\n",
1187                         from_kgid_munged(current_user_ns(), tun->group)):
1188                 sprintf(buf, "-1\n");
1189 }
1190
1191 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1192 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1193 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1194
1195 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1196 {
1197         struct tun_struct *tun;
1198         struct tun_file *tfile = file->private_data;
1199         struct net_device *dev;
1200         int err;
1201
1202         dev = __dev_get_by_name(net, ifr->ifr_name);
1203         if (dev) {
1204                 const struct cred *cred = current_cred();
1205
1206                 if (ifr->ifr_flags & IFF_TUN_EXCL)
1207                         return -EBUSY;
1208                 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
1209                         tun = netdev_priv(dev);
1210                 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
1211                         tun = netdev_priv(dev);
1212                 else
1213                         return -EINVAL;
1214
1215                 if (((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
1216                      (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
1217                     !capable(CAP_NET_ADMIN))
1218                         return -EPERM;
1219                 err = security_tun_dev_attach(tfile->socket.sk);
1220                 if (err < 0)
1221                         return err;
1222
1223                 err = tun_attach(tun, file);
1224                 if (err < 0)
1225                         return err;
1226         }
1227         else {
1228                 char *name;
1229                 unsigned long flags = 0;
1230
1231                 if (!capable(CAP_NET_ADMIN))
1232                         return -EPERM;
1233                 err = security_tun_dev_create();
1234                 if (err < 0)
1235                         return err;
1236
1237                 /* Set dev type */
1238                 if (ifr->ifr_flags & IFF_TUN) {
1239                         /* TUN device */
1240                         flags |= TUN_TUN_DEV;
1241                         name = "tun%d";
1242                 } else if (ifr->ifr_flags & IFF_TAP) {
1243                         /* TAP device */
1244                         flags |= TUN_TAP_DEV;
1245                         name = "tap%d";
1246                 } else
1247                         return -EINVAL;
1248
1249                 if (*ifr->ifr_name)
1250                         name = ifr->ifr_name;
1251
1252                 dev = alloc_netdev(sizeof(struct tun_struct), name,
1253                                    tun_setup);
1254                 if (!dev)
1255                         return -ENOMEM;
1256
1257                 dev_net_set(dev, net);
1258                 dev->rtnl_link_ops = &tun_link_ops;
1259
1260                 tun = netdev_priv(dev);
1261                 tun->dev = dev;
1262                 tun->flags = flags;
1263                 tun->txflt.count = 0;
1264                 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
1265
1266                 tun->filter_attached = false;
1267                 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
1268
1269                 security_tun_dev_post_create(&tfile->sk);
1270
1271                 tun_net_init(dev);
1272
1273                 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1274                         TUN_USER_FEATURES;
1275                 dev->features = dev->hw_features;
1276
1277                 err = register_netdevice(tun->dev);
1278                 if (err < 0)
1279                         goto err_free_dev;
1280
1281                 if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1282                     device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1283                     device_create_file(&tun->dev->dev, &dev_attr_group))
1284                         pr_err("Failed to create tun sysfs files\n");
1285
1286                 err = tun_attach(tun, file);
1287                 if (err < 0)
1288                         goto failed;
1289         }
1290
1291         tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1292
1293         if (ifr->ifr_flags & IFF_NO_PI)
1294                 tun->flags |= TUN_NO_PI;
1295         else
1296                 tun->flags &= ~TUN_NO_PI;
1297
1298         if (ifr->ifr_flags & IFF_ONE_QUEUE)
1299                 tun->flags |= TUN_ONE_QUEUE;
1300         else
1301                 tun->flags &= ~TUN_ONE_QUEUE;
1302
1303         if (ifr->ifr_flags & IFF_VNET_HDR)
1304                 tun->flags |= TUN_VNET_HDR;
1305         else
1306                 tun->flags &= ~TUN_VNET_HDR;
1307
1308         /* Make sure persistent devices do not get stuck in
1309          * xoff state.
1310          */
1311         if (netif_running(tun->dev))
1312                 netif_wake_queue(tun->dev);
1313
1314         strcpy(ifr->ifr_name, tun->dev->name);
1315         return 0;
1316
1317  err_free_dev:
1318         free_netdev(dev);
1319  failed:
1320         return err;
1321 }
1322
1323 static int tun_get_iff(struct net *net, struct tun_struct *tun,
1324                        struct ifreq *ifr)
1325 {
1326         tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1327
1328         strcpy(ifr->ifr_name, tun->dev->name);
1329
1330         ifr->ifr_flags = tun_flags(tun);
1331
1332         return 0;
1333 }
1334
1335 /* This is like a cut-down ethtool ops, except done via tun fd so no
1336  * privs required. */
1337 static int set_offload(struct tun_struct *tun, unsigned long arg)
1338 {
1339         netdev_features_t features = 0;
1340
1341         if (arg & TUN_F_CSUM) {
1342                 features |= NETIF_F_HW_CSUM;
1343                 arg &= ~TUN_F_CSUM;
1344
1345                 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
1346                         if (arg & TUN_F_TSO_ECN) {
1347                                 features |= NETIF_F_TSO_ECN;
1348                                 arg &= ~TUN_F_TSO_ECN;
1349                         }
1350                         if (arg & TUN_F_TSO4)
1351                                 features |= NETIF_F_TSO;
1352                         if (arg & TUN_F_TSO6)
1353                                 features |= NETIF_F_TSO6;
1354                         arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
1355                 }
1356
1357                 if (arg & TUN_F_UFO) {
1358                         features |= NETIF_F_UFO;
1359                         arg &= ~TUN_F_UFO;
1360                 }
1361         }
1362
1363         /* This gives the user a way to test for new features in future by
1364          * trying to set them. */
1365         if (arg)
1366                 return -EINVAL;
1367
1368         tun->set_features = features;
1369         netdev_update_features(tun->dev);
1370
1371         return 0;
1372 }
1373
1374 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
1375                             unsigned long arg, int ifreq_len)
1376 {
1377         struct tun_file *tfile = file->private_data;
1378         struct tun_struct *tun;
1379         void __user* argp = (void __user*)arg;
1380         struct ifreq ifr;
1381         kuid_t owner;
1382         kgid_t group;
1383         int sndbuf;
1384         int vnet_hdr_sz;
1385         int ret;
1386
1387         if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89) {
1388                 if (copy_from_user(&ifr, argp, ifreq_len))
1389                         return -EFAULT;
1390         } else {
1391                 memset(&ifr, 0, sizeof(ifr));
1392         }
1393         if (cmd == TUNGETFEATURES) {
1394                 /* Currently this just means: "what IFF flags are valid?".
1395                  * This is needed because we never checked for invalid flags on
1396                  * TUNSETIFF. */
1397                 return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
1398                                 IFF_VNET_HDR,
1399                                 (unsigned int __user*)argp);
1400         }
1401
1402         rtnl_lock();
1403
1404         tun = __tun_get(tfile);
1405         if (cmd == TUNSETIFF && !tun) {
1406                 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1407
1408                 ret = tun_set_iff(tfile->net, file, &ifr);
1409
1410                 if (ret)
1411                         goto unlock;
1412
1413                 if (copy_to_user(argp, &ifr, ifreq_len))
1414                         ret = -EFAULT;
1415                 goto unlock;
1416         }
1417
1418         ret = -EBADFD;
1419         if (!tun)
1420                 goto unlock;
1421
1422         tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1423
1424         ret = 0;
1425         switch (cmd) {
1426         case TUNGETIFF:
1427                 ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1428                 if (ret)
1429                         break;
1430
1431                 if (copy_to_user(argp, &ifr, ifreq_len))
1432                         ret = -EFAULT;
1433                 break;
1434
1435         case TUNSETNOCSUM:
1436                 /* Disable/Enable checksum */
1437
1438                 /* [unimplemented] */
1439                 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
1440                           arg ? "disabled" : "enabled");
1441                 break;
1442
1443         case TUNSETPERSIST:
1444                 /* Disable/Enable persist mode. Keep an extra reference to the
1445                  * module to prevent the module being unprobed.
1446                  */
1447                 if (arg) {
1448                         tun->flags |= TUN_PERSIST;
1449                         __module_get(THIS_MODULE);
1450                 } else {
1451                         tun->flags &= ~TUN_PERSIST;
1452                         module_put(THIS_MODULE);
1453                 }
1454
1455                 tun_debug(KERN_INFO, tun, "persist %s\n",
1456                           arg ? "enabled" : "disabled");
1457                 break;
1458
1459         case TUNSETOWNER:
1460                 /* Set owner of the device */
1461                 owner = make_kuid(current_user_ns(), arg);
1462                 if (!uid_valid(owner)) {
1463                         ret = -EINVAL;
1464                         break;
1465                 }
1466                 tun->owner = owner;
1467                 tun_debug(KERN_INFO, tun, "owner set to %u\n",
1468                           from_kuid(&init_user_ns, tun->owner));
1469                 break;
1470
1471         case TUNSETGROUP:
1472                 /* Set group of the device */
1473                 group = make_kgid(current_user_ns(), arg);
1474                 if (!gid_valid(group)) {
1475                         ret = -EINVAL;
1476                         break;
1477                 }
1478                 tun->group = group;
1479                 tun_debug(KERN_INFO, tun, "group set to %u\n",
1480                           from_kgid(&init_user_ns, tun->group));
1481                 break;
1482
1483         case TUNSETLINK:
1484                 /* Only allow setting the type when the interface is down */
1485                 if (tun->dev->flags & IFF_UP) {
1486                         tun_debug(KERN_INFO, tun,
1487                                   "Linktype set failed because interface is up\n");
1488                         ret = -EBUSY;
1489                 } else {
1490                         tun->dev->type = (int) arg;
1491                         tun_debug(KERN_INFO, tun, "linktype set to %d\n",
1492                                   tun->dev->type);
1493                         ret = 0;
1494                 }
1495                 break;
1496
1497 #ifdef TUN_DEBUG
1498         case TUNSETDEBUG:
1499                 tun->debug = arg;
1500                 break;
1501 #endif
1502         case TUNSETOFFLOAD:
1503                 ret = set_offload(tun, arg);
1504                 break;
1505
1506         case TUNSETTXFILTER:
1507                 /* Can be set only for TAPs */
1508                 ret = -EINVAL;
1509                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
1510                         break;
1511                 ret = update_filter(&tun->txflt, (void __user *)arg);
1512                 break;
1513
1514         case SIOCGIFHWADDR:
1515                 /* Get hw address */
1516                 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
1517                 ifr.ifr_hwaddr.sa_family = tun->dev->type;
1518                 if (copy_to_user(argp, &ifr, ifreq_len))
1519                         ret = -EFAULT;
1520                 break;
1521
1522         case SIOCSIFHWADDR:
1523                 /* Set hw address */
1524                 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
1525                           ifr.ifr_hwaddr.sa_data);
1526
1527                 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
1528                 break;
1529
1530         case TUNGETSNDBUF:
1531                 sndbuf = tfile->socket.sk->sk_sndbuf;
1532                 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
1533                         ret = -EFAULT;
1534                 break;
1535
1536         case TUNSETSNDBUF:
1537                 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
1538                         ret = -EFAULT;
1539                         break;
1540                 }
1541
1542                 tun->sndbuf = tfile->socket.sk->sk_sndbuf = sndbuf;
1543                 break;
1544
1545         case TUNGETVNETHDRSZ:
1546                 vnet_hdr_sz = tun->vnet_hdr_sz;
1547                 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
1548                         ret = -EFAULT;
1549                 break;
1550
1551         case TUNSETVNETHDRSZ:
1552                 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
1553                         ret = -EFAULT;
1554                         break;
1555                 }
1556                 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
1557                         ret = -EINVAL;
1558                         break;
1559                 }
1560
1561                 tun->vnet_hdr_sz = vnet_hdr_sz;
1562                 break;
1563
1564         case TUNATTACHFILTER:
1565                 /* Can be set only for TAPs */
1566                 ret = -EINVAL;
1567                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
1568                         break;
1569                 ret = -EFAULT;
1570                 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
1571                         break;
1572
1573                 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1574                 if (!ret)
1575                         tun->filter_attached = true;
1576                 break;
1577
1578         case TUNDETACHFILTER:
1579                 /* Can be set only for TAPs */
1580                 ret = -EINVAL;
1581                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
1582                         break;
1583                 ret = sk_detach_filter(tfile->socket.sk);
1584                 if (!ret)
1585                         tun->filter_attached = false;
1586                 break;
1587
1588         default:
1589                 ret = -EINVAL;
1590                 break;
1591         }
1592
1593 unlock:
1594         rtnl_unlock();
1595         if (tun)
1596                 tun_put(tun);
1597         return ret;
1598 }
1599
1600 static long tun_chr_ioctl(struct file *file,
1601                           unsigned int cmd, unsigned long arg)
1602 {
1603         return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
1604 }
1605
1606 #ifdef CONFIG_COMPAT
1607 static long tun_chr_compat_ioctl(struct file *file,
1608                          unsigned int cmd, unsigned long arg)
1609 {
1610         switch (cmd) {
1611         case TUNSETIFF:
1612         case TUNGETIFF:
1613         case TUNSETTXFILTER:
1614         case TUNGETSNDBUF:
1615         case TUNSETSNDBUF:
1616         case SIOCGIFHWADDR:
1617         case SIOCSIFHWADDR:
1618                 arg = (unsigned long)compat_ptr(arg);
1619                 break;
1620         default:
1621                 arg = (compat_ulong_t)arg;
1622                 break;
1623         }
1624
1625         /*
1626          * compat_ifreq is shorter than ifreq, so we must not access beyond
1627          * the end of that structure. All fields that are used in this
1628          * driver are compatible though, we don't need to convert the
1629          * contents.
1630          */
1631         return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
1632 }
1633 #endif /* CONFIG_COMPAT */
1634
1635 static int tun_chr_fasync(int fd, struct file *file, int on)
1636 {
1637         struct tun_file *tfile = file->private_data;
1638         int ret;
1639
1640         if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
1641                 goto out;
1642
1643         if (on) {
1644                 ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
1645                 if (ret)
1646                         goto out;
1647                 tfile->flags |= TUN_FASYNC;
1648         } else
1649                 tfile->flags &= ~TUN_FASYNC;
1650         ret = 0;
1651 out:
1652         return ret;
1653 }
1654
1655 static int tun_chr_open(struct inode *inode, struct file * file)
1656 {
1657         struct tun_file *tfile;
1658
1659         DBG1(KERN_INFO, "tunX: tun_chr_open\n");
1660
1661         tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
1662                                             &tun_proto);
1663         if (!tfile)
1664                 return -ENOMEM;
1665         atomic_set(&tfile->count, 0);
1666         tfile->tun = NULL;
1667         tfile->net = get_net(current->nsproxy->net_ns);
1668         tfile->flags = 0;
1669
1670         rcu_assign_pointer(tfile->socket.wq, &tfile->wq);
1671         init_waitqueue_head(&tfile->wq.wait);
1672
1673         tfile->socket.file = file;
1674         tfile->socket.ops = &tun_socket_ops;
1675
1676         sock_init_data(&tfile->socket, &tfile->sk);
1677         sk_change_net(&tfile->sk, tfile->net);
1678
1679         tfile->sk.sk_write_space = tun_sock_write_space;
1680         tfile->sk.sk_sndbuf = INT_MAX;
1681
1682         file->private_data = tfile;
1683         set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
1684
1685         return 0;
1686 }
1687
1688 static int tun_chr_close(struct inode *inode, struct file *file)
1689 {
1690         struct tun_file *tfile = file->private_data;
1691         struct tun_struct *tun;
1692         struct net *net = tfile->net;
1693
1694         tun = __tun_get(tfile);
1695         if (tun) {
1696                 struct net_device *dev = tun->dev;
1697
1698                 tun_debug(KERN_INFO, tun, "tun_chr_close\n");
1699
1700                 __tun_detach(tun);
1701
1702                 /* If desirable, unregister the netdevice. */
1703                 if (!(tun->flags & TUN_PERSIST)) {
1704                         rtnl_lock();
1705                         if (dev->reg_state == NETREG_REGISTERED)
1706                                 unregister_netdevice(dev);
1707                         rtnl_unlock();
1708                 }
1709
1710                 /* drop the reference that netdevice holds */
1711                 sock_put(&tfile->sk);
1712         }
1713
1714         /* drop the reference that file holds */
1715         BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
1716                          &tfile->socket.flags));
1717         sk_release_kernel(&tfile->sk);
1718         put_net(net);
1719
1720         return 0;
1721 }
1722
1723 static const struct file_operations tun_fops = {
1724         .owner  = THIS_MODULE,
1725         .llseek = no_llseek,
1726         .read  = do_sync_read,
1727         .aio_read  = tun_chr_aio_read,
1728         .write = do_sync_write,
1729         .aio_write = tun_chr_aio_write,
1730         .poll   = tun_chr_poll,
1731         .unlocked_ioctl = tun_chr_ioctl,
1732 #ifdef CONFIG_COMPAT
1733         .compat_ioctl = tun_chr_compat_ioctl,
1734 #endif
1735         .open   = tun_chr_open,
1736         .release = tun_chr_close,
1737         .fasync = tun_chr_fasync
1738 };
1739
1740 static struct miscdevice tun_miscdev = {
1741         .minor = TUN_MINOR,
1742         .name = "tun",
1743         .nodename = "net/tun",
1744         .fops = &tun_fops,
1745 };
1746
1747 /* ethtool interface */
1748
1749 static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1750 {
1751         cmd->supported          = 0;
1752         cmd->advertising        = 0;
1753         ethtool_cmd_speed_set(cmd, SPEED_10);
1754         cmd->duplex             = DUPLEX_FULL;
1755         cmd->port               = PORT_TP;
1756         cmd->phy_address        = 0;
1757         cmd->transceiver        = XCVR_INTERNAL;
1758         cmd->autoneg            = AUTONEG_DISABLE;
1759         cmd->maxtxpkt           = 0;
1760         cmd->maxrxpkt           = 0;
1761         return 0;
1762 }
1763
1764 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
1765 {
1766         struct tun_struct *tun = netdev_priv(dev);
1767
1768         strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
1769         strlcpy(info->version, DRV_VERSION, sizeof(info->version));
1770
1771         switch (tun->flags & TUN_TYPE_MASK) {
1772         case TUN_TUN_DEV:
1773                 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
1774                 break;
1775         case TUN_TAP_DEV:
1776                 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
1777                 break;
1778         }
1779 }
1780
1781 static u32 tun_get_msglevel(struct net_device *dev)
1782 {
1783 #ifdef TUN_DEBUG
1784         struct tun_struct *tun = netdev_priv(dev);
1785         return tun->debug;
1786 #else
1787         return -EOPNOTSUPP;
1788 #endif
1789 }
1790
1791 static void tun_set_msglevel(struct net_device *dev, u32 value)
1792 {
1793 #ifdef TUN_DEBUG
1794         struct tun_struct *tun = netdev_priv(dev);
1795         tun->debug = value;
1796 #endif
1797 }
1798
1799 static const struct ethtool_ops tun_ethtool_ops = {
1800         .get_settings   = tun_get_settings,
1801         .get_drvinfo    = tun_get_drvinfo,
1802         .get_msglevel   = tun_get_msglevel,
1803         .set_msglevel   = tun_set_msglevel,
1804         .get_link       = ethtool_op_get_link,
1805 };
1806
1807
1808 static int __init tun_init(void)
1809 {
1810         int ret = 0;
1811
1812         pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
1813         pr_info("%s\n", DRV_COPYRIGHT);
1814
1815         ret = rtnl_link_register(&tun_link_ops);
1816         if (ret) {
1817                 pr_err("Can't register link_ops\n");
1818                 goto err_linkops;
1819         }
1820
1821         ret = misc_register(&tun_miscdev);
1822         if (ret) {
1823                 pr_err("Can't register misc device %d\n", TUN_MINOR);
1824                 goto err_misc;
1825         }
1826         return  0;
1827 err_misc:
1828         rtnl_link_unregister(&tun_link_ops);
1829 err_linkops:
1830         return ret;
1831 }
1832
1833 static void tun_cleanup(void)
1834 {
1835         misc_deregister(&tun_miscdev);
1836         rtnl_link_unregister(&tun_link_ops);
1837 }
1838
1839 /* Get an underlying socket object from tun file.  Returns error unless file is
1840  * attached to a device.  The returned object works like a packet socket, it
1841  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
1842  * holding a reference to the file for as long as the socket is in use. */
1843 struct socket *tun_get_socket(struct file *file)
1844 {
1845         struct tun_struct *tun;
1846         struct tun_file *tfile = file->private_data;
1847         if (file->f_op != &tun_fops)
1848                 return ERR_PTR(-EINVAL);
1849         tun = tun_get(file);
1850         if (!tun)
1851                 return ERR_PTR(-EBADFD);
1852         tun_put(tun);
1853         return &tfile->socket;
1854 }
1855 EXPORT_SYMBOL_GPL(tun_get_socket);
1856
1857 module_init(tun_init);
1858 module_exit(tun_cleanup);
1859 MODULE_DESCRIPTION(DRV_DESCRIPTION);
1860 MODULE_AUTHOR(DRV_COPYRIGHT);
1861 MODULE_LICENSE("GPL");
1862 MODULE_ALIAS_MISCDEV(TUN_MINOR);
1863 MODULE_ALIAS("devname:net/tun");