]> Pileus Git - ~andy/linux/blob - drivers/net/tun.c
tun: fix carrier on/off status
[~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 /* DEFAULT_MAX_NUM_RSS_QUEUES were choosed to let the rx/tx queues allocated for
113  * the netdevice to be fit in one page. So we can make sure the success of
114  * memory allocation. TODO: increase the limit. */
115 #define MAX_TAP_QUEUES DEFAULT_MAX_NUM_RSS_QUEUES
116 #define MAX_TAP_FLOWS  4096
117
118 #define TUN_FLOW_EXPIRE (3 * HZ)
119
120 /* A tun_file connects an open character device to a tuntap netdevice. It
121  * also contains all socket related strctures (except sock_fprog and tap_filter)
122  * to serve as one transmit queue for tuntap device. The sock_fprog and
123  * tap_filter were kept in tun_struct since they were used for filtering for the
124  * netdevice not for a specific queue (at least I didn't see the requirement for
125  * this).
126  *
127  * RCU usage:
128  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
129  * other can only be read while rcu_read_lock or rtnl_lock is held.
130  */
131 struct tun_file {
132         struct sock sk;
133         struct socket socket;
134         struct socket_wq wq;
135         struct tun_struct __rcu *tun;
136         struct net *net;
137         struct fasync_struct *fasync;
138         /* only used for fasnyc */
139         unsigned int flags;
140         u16 queue_index;
141         struct list_head next;
142         struct tun_struct *detached;
143 };
144
145 struct tun_flow_entry {
146         struct hlist_node hash_link;
147         struct rcu_head rcu;
148         struct tun_struct *tun;
149
150         u32 rxhash;
151         int queue_index;
152         unsigned long updated;
153 };
154
155 #define TUN_NUM_FLOW_ENTRIES 1024
156
157 /* Since the socket were moved to tun_file, to preserve the behavior of persist
158  * device, socket filter, sndbuf and vnet header size were restore when the
159  * file were attached to a persist device.
160  */
161 struct tun_struct {
162         struct tun_file __rcu   *tfiles[MAX_TAP_QUEUES];
163         unsigned int            numqueues;
164         unsigned int            flags;
165         kuid_t                  owner;
166         kgid_t                  group;
167
168         struct net_device       *dev;
169         netdev_features_t       set_features;
170 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
171                           NETIF_F_TSO6|NETIF_F_UFO)
172
173         int                     vnet_hdr_sz;
174         int                     sndbuf;
175         struct tap_filter       txflt;
176         struct sock_fprog       fprog;
177         /* protected by rtnl lock */
178         bool                    filter_attached;
179 #ifdef TUN_DEBUG
180         int debug;
181 #endif
182         spinlock_t lock;
183         struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
184         struct timer_list flow_gc_timer;
185         unsigned long ageing_time;
186         unsigned int numdisabled;
187         struct list_head disabled;
188         void *security;
189         u32 flow_count;
190 };
191
192 static inline u32 tun_hashfn(u32 rxhash)
193 {
194         return rxhash & 0x3ff;
195 }
196
197 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
198 {
199         struct tun_flow_entry *e;
200         struct hlist_node *n;
201
202         hlist_for_each_entry_rcu(e, n, head, hash_link) {
203                 if (e->rxhash == rxhash)
204                         return e;
205         }
206         return NULL;
207 }
208
209 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
210                                               struct hlist_head *head,
211                                               u32 rxhash, u16 queue_index)
212 {
213         struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
214
215         if (e) {
216                 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
217                           rxhash, queue_index);
218                 e->updated = jiffies;
219                 e->rxhash = rxhash;
220                 e->queue_index = queue_index;
221                 e->tun = tun;
222                 hlist_add_head_rcu(&e->hash_link, head);
223                 ++tun->flow_count;
224         }
225         return e;
226 }
227
228 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
229 {
230         tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
231                   e->rxhash, e->queue_index);
232         hlist_del_rcu(&e->hash_link);
233         kfree_rcu(e, rcu);
234         --tun->flow_count;
235 }
236
237 static void tun_flow_flush(struct tun_struct *tun)
238 {
239         int i;
240
241         spin_lock_bh(&tun->lock);
242         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
243                 struct tun_flow_entry *e;
244                 struct hlist_node *h, *n;
245
246                 hlist_for_each_entry_safe(e, h, n, &tun->flows[i], hash_link)
247                         tun_flow_delete(tun, e);
248         }
249         spin_unlock_bh(&tun->lock);
250 }
251
252 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
253 {
254         int i;
255
256         spin_lock_bh(&tun->lock);
257         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
258                 struct tun_flow_entry *e;
259                 struct hlist_node *h, *n;
260
261                 hlist_for_each_entry_safe(e, h, n, &tun->flows[i], hash_link) {
262                         if (e->queue_index == queue_index)
263                                 tun_flow_delete(tun, e);
264                 }
265         }
266         spin_unlock_bh(&tun->lock);
267 }
268
269 static void tun_flow_cleanup(unsigned long data)
270 {
271         struct tun_struct *tun = (struct tun_struct *)data;
272         unsigned long delay = tun->ageing_time;
273         unsigned long next_timer = jiffies + delay;
274         unsigned long count = 0;
275         int i;
276
277         tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
278
279         spin_lock_bh(&tun->lock);
280         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
281                 struct tun_flow_entry *e;
282                 struct hlist_node *h, *n;
283
284                 hlist_for_each_entry_safe(e, h, n, &tun->flows[i], hash_link) {
285                         unsigned long this_timer;
286                         count++;
287                         this_timer = e->updated + delay;
288                         if (time_before_eq(this_timer, jiffies))
289                                 tun_flow_delete(tun, e);
290                         else if (time_before(this_timer, next_timer))
291                                 next_timer = this_timer;
292                 }
293         }
294
295         if (count)
296                 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
297         spin_unlock_bh(&tun->lock);
298 }
299
300 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
301                             u16 queue_index)
302 {
303         struct hlist_head *head;
304         struct tun_flow_entry *e;
305         unsigned long delay = tun->ageing_time;
306
307         if (!rxhash)
308                 return;
309         else
310                 head = &tun->flows[tun_hashfn(rxhash)];
311
312         rcu_read_lock();
313
314         if (tun->numqueues == 1)
315                 goto unlock;
316
317         e = tun_flow_find(head, rxhash);
318         if (likely(e)) {
319                 /* TODO: keep queueing to old queue until it's empty? */
320                 e->queue_index = queue_index;
321                 e->updated = jiffies;
322         } else {
323                 spin_lock_bh(&tun->lock);
324                 if (!tun_flow_find(head, rxhash) &&
325                     tun->flow_count < MAX_TAP_FLOWS)
326                         tun_flow_create(tun, head, rxhash, queue_index);
327
328                 if (!timer_pending(&tun->flow_gc_timer))
329                         mod_timer(&tun->flow_gc_timer,
330                                   round_jiffies_up(jiffies + delay));
331                 spin_unlock_bh(&tun->lock);
332         }
333
334 unlock:
335         rcu_read_unlock();
336 }
337
338 /* We try to identify a flow through its rxhash first. The reason that
339  * we do not check rxq no. is becuase some cards(e.g 82599), chooses
340  * the rxq based on the txq where the last packet of the flow comes. As
341  * the userspace application move between processors, we may get a
342  * different rxq no. here. If we could not get rxhash, then we would
343  * hope the rxq no. may help here.
344  */
345 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb)
346 {
347         struct tun_struct *tun = netdev_priv(dev);
348         struct tun_flow_entry *e;
349         u32 txq = 0;
350         u32 numqueues = 0;
351
352         rcu_read_lock();
353         numqueues = tun->numqueues;
354
355         txq = skb_get_rxhash(skb);
356         if (txq) {
357                 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
358                 if (e)
359                         txq = e->queue_index;
360                 else
361                         /* use multiply and shift instead of expensive divide */
362                         txq = ((u64)txq * numqueues) >> 32;
363         } else if (likely(skb_rx_queue_recorded(skb))) {
364                 txq = skb_get_rx_queue(skb);
365                 while (unlikely(txq >= numqueues))
366                         txq -= numqueues;
367         }
368
369         rcu_read_unlock();
370         return txq;
371 }
372
373 static inline bool tun_not_capable(struct tun_struct *tun)
374 {
375         const struct cred *cred = current_cred();
376         struct net *net = dev_net(tun->dev);
377
378         return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
379                   (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
380                 !ns_capable(net->user_ns, CAP_NET_ADMIN);
381 }
382
383 static void tun_set_real_num_queues(struct tun_struct *tun)
384 {
385         netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
386         netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
387 }
388
389 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
390 {
391         tfile->detached = tun;
392         list_add_tail(&tfile->next, &tun->disabled);
393         ++tun->numdisabled;
394 }
395
396 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
397 {
398         struct tun_struct *tun = tfile->detached;
399
400         tfile->detached = NULL;
401         list_del_init(&tfile->next);
402         --tun->numdisabled;
403         return tun;
404 }
405
406 static void __tun_detach(struct tun_file *tfile, bool clean)
407 {
408         struct tun_file *ntfile;
409         struct tun_struct *tun;
410         struct net_device *dev;
411
412         tun = rtnl_dereference(tfile->tun);
413
414         if (tun) {
415                 u16 index = tfile->queue_index;
416                 BUG_ON(index >= tun->numqueues);
417                 dev = tun->dev;
418
419                 rcu_assign_pointer(tun->tfiles[index],
420                                    tun->tfiles[tun->numqueues - 1]);
421                 rcu_assign_pointer(tfile->tun, NULL);
422                 ntfile = rtnl_dereference(tun->tfiles[index]);
423                 ntfile->queue_index = index;
424
425                 --tun->numqueues;
426                 if (clean)
427                         sock_put(&tfile->sk);
428                 else
429                         tun_disable_queue(tun, tfile);
430
431                 synchronize_net();
432                 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
433                 /* Drop read queue */
434                 skb_queue_purge(&tfile->sk.sk_receive_queue);
435                 tun_set_real_num_queues(tun);
436         } else if (tfile->detached && clean) {
437                 tun = tun_enable_queue(tfile);
438                 sock_put(&tfile->sk);
439         }
440
441         if (clean) {
442                 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
443                         netif_carrier_off(tun->dev);
444
445                         if (!(tun->flags & TUN_PERSIST) &&
446                             tun->dev->reg_state == NETREG_REGISTERED)
447                                 unregister_netdevice(tun->dev);
448                 }
449
450                 BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
451                                  &tfile->socket.flags));
452                 sk_release_kernel(&tfile->sk);
453         }
454 }
455
456 static void tun_detach(struct tun_file *tfile, bool clean)
457 {
458         rtnl_lock();
459         __tun_detach(tfile, clean);
460         rtnl_unlock();
461 }
462
463 static void tun_detach_all(struct net_device *dev)
464 {
465         struct tun_struct *tun = netdev_priv(dev);
466         struct tun_file *tfile, *tmp;
467         int i, n = tun->numqueues;
468
469         for (i = 0; i < n; i++) {
470                 tfile = rtnl_dereference(tun->tfiles[i]);
471                 BUG_ON(!tfile);
472                 wake_up_all(&tfile->wq.wait);
473                 rcu_assign_pointer(tfile->tun, NULL);
474                 --tun->numqueues;
475         }
476         BUG_ON(tun->numqueues != 0);
477
478         synchronize_net();
479         for (i = 0; i < n; i++) {
480                 tfile = rtnl_dereference(tun->tfiles[i]);
481                 /* Drop read queue */
482                 skb_queue_purge(&tfile->sk.sk_receive_queue);
483                 sock_put(&tfile->sk);
484         }
485         list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
486                 tun_enable_queue(tfile);
487                 skb_queue_purge(&tfile->sk.sk_receive_queue);
488                 sock_put(&tfile->sk);
489         }
490         BUG_ON(tun->numdisabled != 0);
491
492         if (tun->flags & TUN_PERSIST)
493                 module_put(THIS_MODULE);
494 }
495
496 static int tun_attach(struct tun_struct *tun, struct file *file)
497 {
498         struct tun_file *tfile = file->private_data;
499         int err;
500
501         err = security_tun_dev_attach(tfile->socket.sk, tun->security);
502         if (err < 0)
503                 goto out;
504
505         err = -EINVAL;
506         if (rtnl_dereference(tfile->tun))
507                 goto out;
508
509         err = -EBUSY;
510         if (!(tun->flags & TUN_TAP_MQ) && tun->numqueues == 1)
511                 goto out;
512
513         err = -E2BIG;
514         if (!tfile->detached &&
515             tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
516                 goto out;
517
518         err = 0;
519
520         /* Re-attach the filter to presist device */
521         if (tun->filter_attached == true) {
522                 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
523                 if (!err)
524                         goto out;
525         }
526         tfile->queue_index = tun->numqueues;
527         rcu_assign_pointer(tfile->tun, tun);
528         rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
529         tun->numqueues++;
530
531         if (tfile->detached)
532                 tun_enable_queue(tfile);
533         else
534                 sock_hold(&tfile->sk);
535
536         tun_set_real_num_queues(tun);
537
538         /* device is allowed to go away first, so no need to hold extra
539          * refcnt.
540          */
541
542 out:
543         return err;
544 }
545
546 static struct tun_struct *__tun_get(struct tun_file *tfile)
547 {
548         struct tun_struct *tun;
549
550         rcu_read_lock();
551         tun = rcu_dereference(tfile->tun);
552         if (tun)
553                 dev_hold(tun->dev);
554         rcu_read_unlock();
555
556         return tun;
557 }
558
559 static struct tun_struct *tun_get(struct file *file)
560 {
561         return __tun_get(file->private_data);
562 }
563
564 static void tun_put(struct tun_struct *tun)
565 {
566         dev_put(tun->dev);
567 }
568
569 /* TAP filtering */
570 static void addr_hash_set(u32 *mask, const u8 *addr)
571 {
572         int n = ether_crc(ETH_ALEN, addr) >> 26;
573         mask[n >> 5] |= (1 << (n & 31));
574 }
575
576 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
577 {
578         int n = ether_crc(ETH_ALEN, addr) >> 26;
579         return mask[n >> 5] & (1 << (n & 31));
580 }
581
582 static int update_filter(struct tap_filter *filter, void __user *arg)
583 {
584         struct { u8 u[ETH_ALEN]; } *addr;
585         struct tun_filter uf;
586         int err, alen, n, nexact;
587
588         if (copy_from_user(&uf, arg, sizeof(uf)))
589                 return -EFAULT;
590
591         if (!uf.count) {
592                 /* Disabled */
593                 filter->count = 0;
594                 return 0;
595         }
596
597         alen = ETH_ALEN * uf.count;
598         addr = kmalloc(alen, GFP_KERNEL);
599         if (!addr)
600                 return -ENOMEM;
601
602         if (copy_from_user(addr, arg + sizeof(uf), alen)) {
603                 err = -EFAULT;
604                 goto done;
605         }
606
607         /* The filter is updated without holding any locks. Which is
608          * perfectly safe. We disable it first and in the worst
609          * case we'll accept a few undesired packets. */
610         filter->count = 0;
611         wmb();
612
613         /* Use first set of addresses as an exact filter */
614         for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
615                 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
616
617         nexact = n;
618
619         /* Remaining multicast addresses are hashed,
620          * unicast will leave the filter disabled. */
621         memset(filter->mask, 0, sizeof(filter->mask));
622         for (; n < uf.count; n++) {
623                 if (!is_multicast_ether_addr(addr[n].u)) {
624                         err = 0; /* no filter */
625                         goto done;
626                 }
627                 addr_hash_set(filter->mask, addr[n].u);
628         }
629
630         /* For ALLMULTI just set the mask to all ones.
631          * This overrides the mask populated above. */
632         if ((uf.flags & TUN_FLT_ALLMULTI))
633                 memset(filter->mask, ~0, sizeof(filter->mask));
634
635         /* Now enable the filter */
636         wmb();
637         filter->count = nexact;
638
639         /* Return the number of exact filters */
640         err = nexact;
641
642 done:
643         kfree(addr);
644         return err;
645 }
646
647 /* Returns: 0 - drop, !=0 - accept */
648 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
649 {
650         /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
651          * at this point. */
652         struct ethhdr *eh = (struct ethhdr *) skb->data;
653         int i;
654
655         /* Exact match */
656         for (i = 0; i < filter->count; i++)
657                 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
658                         return 1;
659
660         /* Inexact match (multicast only) */
661         if (is_multicast_ether_addr(eh->h_dest))
662                 return addr_hash_test(filter->mask, eh->h_dest);
663
664         return 0;
665 }
666
667 /*
668  * Checks whether the packet is accepted or not.
669  * Returns: 0 - drop, !=0 - accept
670  */
671 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
672 {
673         if (!filter->count)
674                 return 1;
675
676         return run_filter(filter, skb);
677 }
678
679 /* Network device part of the driver */
680
681 static const struct ethtool_ops tun_ethtool_ops;
682
683 /* Net device detach from fd. */
684 static void tun_net_uninit(struct net_device *dev)
685 {
686         tun_detach_all(dev);
687 }
688
689 /* Net device open. */
690 static int tun_net_open(struct net_device *dev)
691 {
692         netif_tx_start_all_queues(dev);
693         return 0;
694 }
695
696 /* Net device close. */
697 static int tun_net_close(struct net_device *dev)
698 {
699         netif_tx_stop_all_queues(dev);
700         return 0;
701 }
702
703 /* Net device start xmit */
704 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
705 {
706         struct tun_struct *tun = netdev_priv(dev);
707         int txq = skb->queue_mapping;
708         struct tun_file *tfile;
709
710         rcu_read_lock();
711         tfile = rcu_dereference(tun->tfiles[txq]);
712
713         /* Drop packet if interface is not attached */
714         if (txq >= tun->numqueues)
715                 goto drop;
716
717         tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
718
719         BUG_ON(!tfile);
720
721         /* Drop if the filter does not like it.
722          * This is a noop if the filter is disabled.
723          * Filter can be enabled only for the TAP devices. */
724         if (!check_filter(&tun->txflt, skb))
725                 goto drop;
726
727         if (tfile->socket.sk->sk_filter &&
728             sk_filter(tfile->socket.sk, skb))
729                 goto drop;
730
731         /* Limit the number of packets queued by dividing txq length with the
732          * number of queues.
733          */
734         if (skb_queue_len(&tfile->socket.sk->sk_receive_queue)
735                           >= dev->tx_queue_len / tun->numqueues)
736                 goto drop;
737
738         /* Orphan the skb - required as we might hang on to it
739          * for indefinite time. */
740         if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
741                 goto drop;
742         skb_orphan(skb);
743
744         /* Enqueue packet */
745         skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
746
747         /* Notify and wake up reader process */
748         if (tfile->flags & TUN_FASYNC)
749                 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
750         wake_up_interruptible_poll(&tfile->wq.wait, POLLIN |
751                                    POLLRDNORM | POLLRDBAND);
752
753         rcu_read_unlock();
754         return NETDEV_TX_OK;
755
756 drop:
757         dev->stats.tx_dropped++;
758         skb_tx_error(skb);
759         kfree_skb(skb);
760         rcu_read_unlock();
761         return NETDEV_TX_OK;
762 }
763
764 static void tun_net_mclist(struct net_device *dev)
765 {
766         /*
767          * This callback is supposed to deal with mc filter in
768          * _rx_ path and has nothing to do with the _tx_ path.
769          * In rx path we always accept everything userspace gives us.
770          */
771 }
772
773 #define MIN_MTU 68
774 #define MAX_MTU 65535
775
776 static int
777 tun_net_change_mtu(struct net_device *dev, int new_mtu)
778 {
779         if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
780                 return -EINVAL;
781         dev->mtu = new_mtu;
782         return 0;
783 }
784
785 static netdev_features_t tun_net_fix_features(struct net_device *dev,
786         netdev_features_t features)
787 {
788         struct tun_struct *tun = netdev_priv(dev);
789
790         return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
791 }
792 #ifdef CONFIG_NET_POLL_CONTROLLER
793 static void tun_poll_controller(struct net_device *dev)
794 {
795         /*
796          * Tun only receives frames when:
797          * 1) the char device endpoint gets data from user space
798          * 2) the tun socket gets a sendmsg call from user space
799          * Since both of those are syncronous operations, we are guaranteed
800          * never to have pending data when we poll for it
801          * so theres nothing to do here but return.
802          * We need this though so netpoll recognizes us as an interface that
803          * supports polling, which enables bridge devices in virt setups to
804          * still use netconsole
805          */
806         return;
807 }
808 #endif
809 static const struct net_device_ops tun_netdev_ops = {
810         .ndo_uninit             = tun_net_uninit,
811         .ndo_open               = tun_net_open,
812         .ndo_stop               = tun_net_close,
813         .ndo_start_xmit         = tun_net_xmit,
814         .ndo_change_mtu         = tun_net_change_mtu,
815         .ndo_fix_features       = tun_net_fix_features,
816         .ndo_select_queue       = tun_select_queue,
817 #ifdef CONFIG_NET_POLL_CONTROLLER
818         .ndo_poll_controller    = tun_poll_controller,
819 #endif
820 };
821
822 static const struct net_device_ops tap_netdev_ops = {
823         .ndo_uninit             = tun_net_uninit,
824         .ndo_open               = tun_net_open,
825         .ndo_stop               = tun_net_close,
826         .ndo_start_xmit         = tun_net_xmit,
827         .ndo_change_mtu         = tun_net_change_mtu,
828         .ndo_fix_features       = tun_net_fix_features,
829         .ndo_set_rx_mode        = tun_net_mclist,
830         .ndo_set_mac_address    = eth_mac_addr,
831         .ndo_validate_addr      = eth_validate_addr,
832         .ndo_select_queue       = tun_select_queue,
833 #ifdef CONFIG_NET_POLL_CONTROLLER
834         .ndo_poll_controller    = tun_poll_controller,
835 #endif
836 };
837
838 static int tun_flow_init(struct tun_struct *tun)
839 {
840         int i;
841
842         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
843                 INIT_HLIST_HEAD(&tun->flows[i]);
844
845         tun->ageing_time = TUN_FLOW_EXPIRE;
846         setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
847         mod_timer(&tun->flow_gc_timer,
848                   round_jiffies_up(jiffies + tun->ageing_time));
849
850         return 0;
851 }
852
853 static void tun_flow_uninit(struct tun_struct *tun)
854 {
855         del_timer_sync(&tun->flow_gc_timer);
856         tun_flow_flush(tun);
857 }
858
859 /* Initialize net device. */
860 static void tun_net_init(struct net_device *dev)
861 {
862         struct tun_struct *tun = netdev_priv(dev);
863
864         switch (tun->flags & TUN_TYPE_MASK) {
865         case TUN_TUN_DEV:
866                 dev->netdev_ops = &tun_netdev_ops;
867
868                 /* Point-to-Point TUN Device */
869                 dev->hard_header_len = 0;
870                 dev->addr_len = 0;
871                 dev->mtu = 1500;
872
873                 /* Zero header length */
874                 dev->type = ARPHRD_NONE;
875                 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
876                 dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
877                 break;
878
879         case TUN_TAP_DEV:
880                 dev->netdev_ops = &tap_netdev_ops;
881                 /* Ethernet TAP Device */
882                 ether_setup(dev);
883                 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
884                 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
885
886                 eth_hw_addr_random(dev);
887
888                 dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
889                 break;
890         }
891 }
892
893 /* Character device part */
894
895 /* Poll */
896 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
897 {
898         struct tun_file *tfile = file->private_data;
899         struct tun_struct *tun = __tun_get(tfile);
900         struct sock *sk;
901         unsigned int mask = 0;
902
903         if (!tun)
904                 return POLLERR;
905
906         sk = tfile->socket.sk;
907
908         tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
909
910         poll_wait(file, &tfile->wq.wait, wait);
911
912         if (!skb_queue_empty(&sk->sk_receive_queue))
913                 mask |= POLLIN | POLLRDNORM;
914
915         if (sock_writeable(sk) ||
916             (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
917              sock_writeable(sk)))
918                 mask |= POLLOUT | POLLWRNORM;
919
920         if (tun->dev->reg_state != NETREG_REGISTERED)
921                 mask = POLLERR;
922
923         tun_put(tun);
924         return mask;
925 }
926
927 /* prepad is the amount to reserve at front.  len is length after that.
928  * linear is a hint as to how much to copy (usually headers). */
929 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
930                                      size_t prepad, size_t len,
931                                      size_t linear, int noblock)
932 {
933         struct sock *sk = tfile->socket.sk;
934         struct sk_buff *skb;
935         int err;
936
937         /* Under a page?  Don't bother with paged skb. */
938         if (prepad + len < PAGE_SIZE || !linear)
939                 linear = len;
940
941         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
942                                    &err);
943         if (!skb)
944                 return ERR_PTR(err);
945
946         skb_reserve(skb, prepad);
947         skb_put(skb, linear);
948         skb->data_len = len - linear;
949         skb->len += len - linear;
950
951         return skb;
952 }
953
954 /* set skb frags from iovec, this can move to core network code for reuse */
955 static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
956                                   int offset, size_t count)
957 {
958         int len = iov_length(from, count) - offset;
959         int copy = skb_headlen(skb);
960         int size, offset1 = 0;
961         int i = 0;
962
963         /* Skip over from offset */
964         while (count && (offset >= from->iov_len)) {
965                 offset -= from->iov_len;
966                 ++from;
967                 --count;
968         }
969
970         /* copy up to skb headlen */
971         while (count && (copy > 0)) {
972                 size = min_t(unsigned int, copy, from->iov_len - offset);
973                 if (copy_from_user(skb->data + offset1, from->iov_base + offset,
974                                    size))
975                         return -EFAULT;
976                 if (copy > size) {
977                         ++from;
978                         --count;
979                         offset = 0;
980                 } else
981                         offset += size;
982                 copy -= size;
983                 offset1 += size;
984         }
985
986         if (len == offset1)
987                 return 0;
988
989         while (count--) {
990                 struct page *page[MAX_SKB_FRAGS];
991                 int num_pages;
992                 unsigned long base;
993                 unsigned long truesize;
994
995                 len = from->iov_len - offset;
996                 if (!len) {
997                         offset = 0;
998                         ++from;
999                         continue;
1000                 }
1001                 base = (unsigned long)from->iov_base + offset;
1002                 size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
1003                 if (i + size > MAX_SKB_FRAGS)
1004                         return -EMSGSIZE;
1005                 num_pages = get_user_pages_fast(base, size, 0, &page[i]);
1006                 if (num_pages != size) {
1007                         for (i = 0; i < num_pages; i++)
1008                                 put_page(page[i]);
1009                         return -EFAULT;
1010                 }
1011                 truesize = size * PAGE_SIZE;
1012                 skb->data_len += len;
1013                 skb->len += len;
1014                 skb->truesize += truesize;
1015                 atomic_add(truesize, &skb->sk->sk_wmem_alloc);
1016                 while (len) {
1017                         int off = base & ~PAGE_MASK;
1018                         int size = min_t(int, len, PAGE_SIZE - off);
1019                         __skb_fill_page_desc(skb, i, page[i], off, size);
1020                         skb_shinfo(skb)->nr_frags++;
1021                         /* increase sk_wmem_alloc */
1022                         base += size;
1023                         len -= size;
1024                         i++;
1025                 }
1026                 offset = 0;
1027                 ++from;
1028         }
1029         return 0;
1030 }
1031
1032 /* Get packet from user space buffer */
1033 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1034                             void *msg_control, const struct iovec *iv,
1035                             size_t total_len, size_t count, int noblock)
1036 {
1037         struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1038         struct sk_buff *skb;
1039         size_t len = total_len, align = NET_SKB_PAD;
1040         struct virtio_net_hdr gso = { 0 };
1041         int offset = 0;
1042         int copylen;
1043         bool zerocopy = false;
1044         int err;
1045         u32 rxhash;
1046
1047         if (!(tun->flags & TUN_NO_PI)) {
1048                 if ((len -= sizeof(pi)) > total_len)
1049                         return -EINVAL;
1050
1051                 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
1052                         return -EFAULT;
1053                 offset += sizeof(pi);
1054         }
1055
1056         if (tun->flags & TUN_VNET_HDR) {
1057                 if ((len -= tun->vnet_hdr_sz) > total_len)
1058                         return -EINVAL;
1059
1060                 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
1061                         return -EFAULT;
1062
1063                 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1064                     gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
1065                         gso.hdr_len = gso.csum_start + gso.csum_offset + 2;
1066
1067                 if (gso.hdr_len > len)
1068                         return -EINVAL;
1069                 offset += tun->vnet_hdr_sz;
1070         }
1071
1072         if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
1073                 align += NET_IP_ALIGN;
1074                 if (unlikely(len < ETH_HLEN ||
1075                              (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
1076                         return -EINVAL;
1077         }
1078
1079         if (msg_control)
1080                 zerocopy = true;
1081
1082         if (zerocopy) {
1083                 /* Userspace may produce vectors with count greater than
1084                  * MAX_SKB_FRAGS, so we need to linearize parts of the skb
1085                  * to let the rest of data to be fit in the frags.
1086                  */
1087                 if (count > MAX_SKB_FRAGS) {
1088                         copylen = iov_length(iv, count - MAX_SKB_FRAGS);
1089                         if (copylen < offset)
1090                                 copylen = 0;
1091                         else
1092                                 copylen -= offset;
1093                 } else
1094                                 copylen = 0;
1095                 /* There are 256 bytes to be copied in skb, so there is enough
1096                  * room for skb expand head in case it is used.
1097                  * The rest of the buffer is mapped from userspace.
1098                  */
1099                 if (copylen < gso.hdr_len)
1100                         copylen = gso.hdr_len;
1101                 if (!copylen)
1102                         copylen = GOODCOPY_LEN;
1103         } else
1104                 copylen = len;
1105
1106         skb = tun_alloc_skb(tfile, align, copylen, gso.hdr_len, noblock);
1107         if (IS_ERR(skb)) {
1108                 if (PTR_ERR(skb) != -EAGAIN)
1109                         tun->dev->stats.rx_dropped++;
1110                 return PTR_ERR(skb);
1111         }
1112
1113         if (zerocopy)
1114                 err = zerocopy_sg_from_iovec(skb, iv, offset, count);
1115         else
1116                 err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
1117
1118         if (err) {
1119                 tun->dev->stats.rx_dropped++;
1120                 kfree_skb(skb);
1121                 return -EFAULT;
1122         }
1123
1124         if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1125                 if (!skb_partial_csum_set(skb, gso.csum_start,
1126                                           gso.csum_offset)) {
1127                         tun->dev->stats.rx_frame_errors++;
1128                         kfree_skb(skb);
1129                         return -EINVAL;
1130                 }
1131         }
1132
1133         switch (tun->flags & TUN_TYPE_MASK) {
1134         case TUN_TUN_DEV:
1135                 if (tun->flags & TUN_NO_PI) {
1136                         switch (skb->data[0] & 0xf0) {
1137                         case 0x40:
1138                                 pi.proto = htons(ETH_P_IP);
1139                                 break;
1140                         case 0x60:
1141                                 pi.proto = htons(ETH_P_IPV6);
1142                                 break;
1143                         default:
1144                                 tun->dev->stats.rx_dropped++;
1145                                 kfree_skb(skb);
1146                                 return -EINVAL;
1147                         }
1148                 }
1149
1150                 skb_reset_mac_header(skb);
1151                 skb->protocol = pi.proto;
1152                 skb->dev = tun->dev;
1153                 break;
1154         case TUN_TAP_DEV:
1155                 skb->protocol = eth_type_trans(skb, tun->dev);
1156                 break;
1157         }
1158
1159         if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1160                 pr_debug("GSO!\n");
1161                 switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1162                 case VIRTIO_NET_HDR_GSO_TCPV4:
1163                         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1164                         break;
1165                 case VIRTIO_NET_HDR_GSO_TCPV6:
1166                         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1167                         break;
1168                 case VIRTIO_NET_HDR_GSO_UDP:
1169                         skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
1170                         break;
1171                 default:
1172                         tun->dev->stats.rx_frame_errors++;
1173                         kfree_skb(skb);
1174                         return -EINVAL;
1175                 }
1176
1177                 if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1178                         skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
1179
1180                 skb_shinfo(skb)->gso_size = gso.gso_size;
1181                 if (skb_shinfo(skb)->gso_size == 0) {
1182                         tun->dev->stats.rx_frame_errors++;
1183                         kfree_skb(skb);
1184                         return -EINVAL;
1185                 }
1186
1187                 /* Header must be checked, and gso_segs computed. */
1188                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1189                 skb_shinfo(skb)->gso_segs = 0;
1190         }
1191
1192         /* copy skb_ubuf_info for callback when skb has no error */
1193         if (zerocopy) {
1194                 skb_shinfo(skb)->destructor_arg = msg_control;
1195                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1196         }
1197
1198         skb_reset_network_header(skb);
1199         rxhash = skb_get_rxhash(skb);
1200         netif_rx_ni(skb);
1201
1202         tun->dev->stats.rx_packets++;
1203         tun->dev->stats.rx_bytes += len;
1204
1205         tun_flow_update(tun, rxhash, tfile->queue_index);
1206         return total_len;
1207 }
1208
1209 static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
1210                               unsigned long count, loff_t pos)
1211 {
1212         struct file *file = iocb->ki_filp;
1213         struct tun_struct *tun = tun_get(file);
1214         struct tun_file *tfile = file->private_data;
1215         ssize_t result;
1216
1217         if (!tun)
1218                 return -EBADFD;
1219
1220         tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
1221
1222         result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
1223                               count, file->f_flags & O_NONBLOCK);
1224
1225         tun_put(tun);
1226         return result;
1227 }
1228
1229 /* Put packet to the user space buffer */
1230 static ssize_t tun_put_user(struct tun_struct *tun,
1231                             struct tun_file *tfile,
1232                             struct sk_buff *skb,
1233                             const struct iovec *iv, int len)
1234 {
1235         struct tun_pi pi = { 0, skb->protocol };
1236         ssize_t total = 0;
1237
1238         if (!(tun->flags & TUN_NO_PI)) {
1239                 if ((len -= sizeof(pi)) < 0)
1240                         return -EINVAL;
1241
1242                 if (len < skb->len) {
1243                         /* Packet will be striped */
1244                         pi.flags |= TUN_PKT_STRIP;
1245                 }
1246
1247                 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
1248                         return -EFAULT;
1249                 total += sizeof(pi);
1250         }
1251
1252         if (tun->flags & TUN_VNET_HDR) {
1253                 struct virtio_net_hdr gso = { 0 }; /* no info leak */
1254                 if ((len -= tun->vnet_hdr_sz) < 0)
1255                         return -EINVAL;
1256
1257                 if (skb_is_gso(skb)) {
1258                         struct skb_shared_info *sinfo = skb_shinfo(skb);
1259
1260                         /* This is a hint as to how much should be linear. */
1261                         gso.hdr_len = skb_headlen(skb);
1262                         gso.gso_size = sinfo->gso_size;
1263                         if (sinfo->gso_type & SKB_GSO_TCPV4)
1264                                 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1265                         else if (sinfo->gso_type & SKB_GSO_TCPV6)
1266                                 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1267                         else if (sinfo->gso_type & SKB_GSO_UDP)
1268                                 gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1269                         else {
1270                                 pr_err("unexpected GSO type: "
1271                                        "0x%x, gso_size %d, hdr_len %d\n",
1272                                        sinfo->gso_type, gso.gso_size,
1273                                        gso.hdr_len);
1274                                 print_hex_dump(KERN_ERR, "tun: ",
1275                                                DUMP_PREFIX_NONE,
1276                                                16, 1, skb->head,
1277                                                min((int)gso.hdr_len, 64), true);
1278                                 WARN_ON_ONCE(1);
1279                                 return -EINVAL;
1280                         }
1281                         if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1282                                 gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1283                 } else
1284                         gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1285
1286                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1287                         gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
1288                         gso.csum_start = skb_checksum_start_offset(skb);
1289                         gso.csum_offset = skb->csum_offset;
1290                 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
1291                         gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1292                 } /* else everything is zero */
1293
1294                 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
1295                                                sizeof(gso))))
1296                         return -EFAULT;
1297                 total += tun->vnet_hdr_sz;
1298         }
1299
1300         len = min_t(int, skb->len, len);
1301
1302         skb_copy_datagram_const_iovec(skb, 0, iv, total, len);
1303         total += skb->len;
1304
1305         tun->dev->stats.tx_packets++;
1306         tun->dev->stats.tx_bytes += len;
1307
1308         return total;
1309 }
1310
1311 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1312                            struct kiocb *iocb, const struct iovec *iv,
1313                            ssize_t len, int noblock)
1314 {
1315         DECLARE_WAITQUEUE(wait, current);
1316         struct sk_buff *skb;
1317         ssize_t ret = 0;
1318
1319         tun_debug(KERN_INFO, tun, "tun_do_read\n");
1320
1321         if (unlikely(!noblock))
1322                 add_wait_queue(&tfile->wq.wait, &wait);
1323         while (len) {
1324                 current->state = TASK_INTERRUPTIBLE;
1325
1326                 /* Read frames from the queue */
1327                 if (!(skb = skb_dequeue(&tfile->socket.sk->sk_receive_queue))) {
1328                         if (noblock) {
1329                                 ret = -EAGAIN;
1330                                 break;
1331                         }
1332                         if (signal_pending(current)) {
1333                                 ret = -ERESTARTSYS;
1334                                 break;
1335                         }
1336                         if (tun->dev->reg_state != NETREG_REGISTERED) {
1337                                 ret = -EIO;
1338                                 break;
1339                         }
1340
1341                         /* Nothing to read, let's sleep */
1342                         schedule();
1343                         continue;
1344                 }
1345
1346                 ret = tun_put_user(tun, tfile, skb, iv, len);
1347                 kfree_skb(skb);
1348                 break;
1349         }
1350
1351         current->state = TASK_RUNNING;
1352         if (unlikely(!noblock))
1353                 remove_wait_queue(&tfile->wq.wait, &wait);
1354
1355         return ret;
1356 }
1357
1358 static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
1359                             unsigned long count, loff_t pos)
1360 {
1361         struct file *file = iocb->ki_filp;
1362         struct tun_file *tfile = file->private_data;
1363         struct tun_struct *tun = __tun_get(tfile);
1364         ssize_t len, ret;
1365
1366         if (!tun)
1367                 return -EBADFD;
1368         len = iov_length(iv, count);
1369         if (len < 0) {
1370                 ret = -EINVAL;
1371                 goto out;
1372         }
1373
1374         ret = tun_do_read(tun, tfile, iocb, iv, len,
1375                           file->f_flags & O_NONBLOCK);
1376         ret = min_t(ssize_t, ret, len);
1377 out:
1378         tun_put(tun);
1379         return ret;
1380 }
1381
1382 static void tun_free_netdev(struct net_device *dev)
1383 {
1384         struct tun_struct *tun = netdev_priv(dev);
1385
1386         BUG_ON(!(list_empty(&tun->disabled)));
1387         tun_flow_uninit(tun);
1388         security_tun_dev_free_security(tun->security);
1389         free_netdev(dev);
1390 }
1391
1392 static void tun_setup(struct net_device *dev)
1393 {
1394         struct tun_struct *tun = netdev_priv(dev);
1395
1396         tun->owner = INVALID_UID;
1397         tun->group = INVALID_GID;
1398
1399         dev->ethtool_ops = &tun_ethtool_ops;
1400         dev->destructor = tun_free_netdev;
1401 }
1402
1403 /* Trivial set of netlink ops to allow deleting tun or tap
1404  * device with netlink.
1405  */
1406 static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1407 {
1408         return -EINVAL;
1409 }
1410
1411 static struct rtnl_link_ops tun_link_ops __read_mostly = {
1412         .kind           = DRV_NAME,
1413         .priv_size      = sizeof(struct tun_struct),
1414         .setup          = tun_setup,
1415         .validate       = tun_validate,
1416 };
1417
1418 static void tun_sock_write_space(struct sock *sk)
1419 {
1420         struct tun_file *tfile;
1421         wait_queue_head_t *wqueue;
1422
1423         if (!sock_writeable(sk))
1424                 return;
1425
1426         if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1427                 return;
1428
1429         wqueue = sk_sleep(sk);
1430         if (wqueue && waitqueue_active(wqueue))
1431                 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1432                                                 POLLWRNORM | POLLWRBAND);
1433
1434         tfile = container_of(sk, struct tun_file, sk);
1435         kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1436 }
1437
1438 static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1439                        struct msghdr *m, size_t total_len)
1440 {
1441         int ret;
1442         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1443         struct tun_struct *tun = __tun_get(tfile);
1444
1445         if (!tun)
1446                 return -EBADFD;
1447         ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
1448                            m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
1449         tun_put(tun);
1450         return ret;
1451 }
1452
1453
1454 static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1455                        struct msghdr *m, size_t total_len,
1456                        int flags)
1457 {
1458         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1459         struct tun_struct *tun = __tun_get(tfile);
1460         int ret;
1461
1462         if (!tun)
1463                 return -EBADFD;
1464
1465         if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
1466                 return -EINVAL;
1467         ret = tun_do_read(tun, tfile, iocb, m->msg_iov, total_len,
1468                           flags & MSG_DONTWAIT);
1469         if (ret > total_len) {
1470                 m->msg_flags |= MSG_TRUNC;
1471                 ret = flags & MSG_TRUNC ? ret : total_len;
1472         }
1473         tun_put(tun);
1474         return ret;
1475 }
1476
1477 static int tun_release(struct socket *sock)
1478 {
1479         if (sock->sk)
1480                 sock_put(sock->sk);
1481         return 0;
1482 }
1483
1484 /* Ops structure to mimic raw sockets with tun */
1485 static const struct proto_ops tun_socket_ops = {
1486         .sendmsg = tun_sendmsg,
1487         .recvmsg = tun_recvmsg,
1488         .release = tun_release,
1489 };
1490
1491 static struct proto tun_proto = {
1492         .name           = "tun",
1493         .owner          = THIS_MODULE,
1494         .obj_size       = sizeof(struct tun_file),
1495 };
1496
1497 static int tun_flags(struct tun_struct *tun)
1498 {
1499         int flags = 0;
1500
1501         if (tun->flags & TUN_TUN_DEV)
1502                 flags |= IFF_TUN;
1503         else
1504                 flags |= IFF_TAP;
1505
1506         if (tun->flags & TUN_NO_PI)
1507                 flags |= IFF_NO_PI;
1508
1509         /* This flag has no real effect.  We track the value for backwards
1510          * compatibility.
1511          */
1512         if (tun->flags & TUN_ONE_QUEUE)
1513                 flags |= IFF_ONE_QUEUE;
1514
1515         if (tun->flags & TUN_VNET_HDR)
1516                 flags |= IFF_VNET_HDR;
1517
1518         if (tun->flags & TUN_TAP_MQ)
1519                 flags |= IFF_MULTI_QUEUE;
1520
1521         return flags;
1522 }
1523
1524 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1525                               char *buf)
1526 {
1527         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1528         return sprintf(buf, "0x%x\n", tun_flags(tun));
1529 }
1530
1531 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1532                               char *buf)
1533 {
1534         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1535         return uid_valid(tun->owner)?
1536                 sprintf(buf, "%u\n",
1537                         from_kuid_munged(current_user_ns(), tun->owner)):
1538                 sprintf(buf, "-1\n");
1539 }
1540
1541 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1542                               char *buf)
1543 {
1544         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1545         return gid_valid(tun->group) ?
1546                 sprintf(buf, "%u\n",
1547                         from_kgid_munged(current_user_ns(), tun->group)):
1548                 sprintf(buf, "-1\n");
1549 }
1550
1551 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1552 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1553 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1554
1555 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1556 {
1557         struct tun_struct *tun;
1558         struct tun_file *tfile = file->private_data;
1559         struct net_device *dev;
1560         int err;
1561
1562         if (tfile->detached)
1563                 return -EINVAL;
1564
1565         dev = __dev_get_by_name(net, ifr->ifr_name);
1566         if (dev) {
1567                 if (ifr->ifr_flags & IFF_TUN_EXCL)
1568                         return -EBUSY;
1569                 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
1570                         tun = netdev_priv(dev);
1571                 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
1572                         tun = netdev_priv(dev);
1573                 else
1574                         return -EINVAL;
1575
1576                 if (tun_not_capable(tun))
1577                         return -EPERM;
1578                 err = security_tun_dev_open(tun->security);
1579                 if (err < 0)
1580                         return err;
1581
1582                 err = tun_attach(tun, file);
1583                 if (err < 0)
1584                         return err;
1585
1586                 if (tun->flags & TUN_TAP_MQ &&
1587                     (tun->numqueues + tun->numdisabled > 1))
1588                         return err;
1589         }
1590         else {
1591                 char *name;
1592                 unsigned long flags = 0;
1593                 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1594                              MAX_TAP_QUEUES : 1;
1595
1596                 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1597                         return -EPERM;
1598                 err = security_tun_dev_create();
1599                 if (err < 0)
1600                         return err;
1601
1602                 /* Set dev type */
1603                 if (ifr->ifr_flags & IFF_TUN) {
1604                         /* TUN device */
1605                         flags |= TUN_TUN_DEV;
1606                         name = "tun%d";
1607                 } else if (ifr->ifr_flags & IFF_TAP) {
1608                         /* TAP device */
1609                         flags |= TUN_TAP_DEV;
1610                         name = "tap%d";
1611                 } else
1612                         return -EINVAL;
1613
1614                 if (*ifr->ifr_name)
1615                         name = ifr->ifr_name;
1616
1617                 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1618                                        tun_setup, queues, queues);
1619
1620                 if (!dev)
1621                         return -ENOMEM;
1622
1623                 dev_net_set(dev, net);
1624                 dev->rtnl_link_ops = &tun_link_ops;
1625
1626                 tun = netdev_priv(dev);
1627                 tun->dev = dev;
1628                 tun->flags = flags;
1629                 tun->txflt.count = 0;
1630                 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
1631
1632                 tun->filter_attached = false;
1633                 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
1634
1635                 spin_lock_init(&tun->lock);
1636
1637                 err = security_tun_dev_alloc_security(&tun->security);
1638                 if (err < 0)
1639                         goto err_free_dev;
1640
1641                 tun_net_init(dev);
1642
1643                 err = tun_flow_init(tun);
1644                 if (err < 0)
1645                         goto err_free_dev;
1646
1647                 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1648                         TUN_USER_FEATURES;
1649                 dev->features = dev->hw_features;
1650
1651                 INIT_LIST_HEAD(&tun->disabled);
1652                 err = tun_attach(tun, file);
1653                 if (err < 0)
1654                         goto err_free_dev;
1655
1656                 err = register_netdevice(tun->dev);
1657                 if (err < 0)
1658                         goto err_free_dev;
1659
1660                 if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1661                     device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1662                     device_create_file(&tun->dev->dev, &dev_attr_group))
1663                         pr_err("Failed to create tun sysfs files\n");
1664         }
1665
1666         netif_carrier_on(tun->dev);
1667
1668         tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1669
1670         if (ifr->ifr_flags & IFF_NO_PI)
1671                 tun->flags |= TUN_NO_PI;
1672         else
1673                 tun->flags &= ~TUN_NO_PI;
1674
1675         /* This flag has no real effect.  We track the value for backwards
1676          * compatibility.
1677          */
1678         if (ifr->ifr_flags & IFF_ONE_QUEUE)
1679                 tun->flags |= TUN_ONE_QUEUE;
1680         else
1681                 tun->flags &= ~TUN_ONE_QUEUE;
1682
1683         if (ifr->ifr_flags & IFF_VNET_HDR)
1684                 tun->flags |= TUN_VNET_HDR;
1685         else
1686                 tun->flags &= ~TUN_VNET_HDR;
1687
1688         if (ifr->ifr_flags & IFF_MULTI_QUEUE)
1689                 tun->flags |= TUN_TAP_MQ;
1690         else
1691                 tun->flags &= ~TUN_TAP_MQ;
1692
1693         /* Make sure persistent devices do not get stuck in
1694          * xoff state.
1695          */
1696         if (netif_running(tun->dev))
1697                 netif_tx_wake_all_queues(tun->dev);
1698
1699         strcpy(ifr->ifr_name, tun->dev->name);
1700         return 0;
1701
1702  err_free_dev:
1703         free_netdev(dev);
1704         return err;
1705 }
1706
1707 static void tun_get_iff(struct net *net, struct tun_struct *tun,
1708                        struct ifreq *ifr)
1709 {
1710         tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1711
1712         strcpy(ifr->ifr_name, tun->dev->name);
1713
1714         ifr->ifr_flags = tun_flags(tun);
1715
1716 }
1717
1718 /* This is like a cut-down ethtool ops, except done via tun fd so no
1719  * privs required. */
1720 static int set_offload(struct tun_struct *tun, unsigned long arg)
1721 {
1722         netdev_features_t features = 0;
1723
1724         if (arg & TUN_F_CSUM) {
1725                 features |= NETIF_F_HW_CSUM;
1726                 arg &= ~TUN_F_CSUM;
1727
1728                 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
1729                         if (arg & TUN_F_TSO_ECN) {
1730                                 features |= NETIF_F_TSO_ECN;
1731                                 arg &= ~TUN_F_TSO_ECN;
1732                         }
1733                         if (arg & TUN_F_TSO4)
1734                                 features |= NETIF_F_TSO;
1735                         if (arg & TUN_F_TSO6)
1736                                 features |= NETIF_F_TSO6;
1737                         arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
1738                 }
1739
1740                 if (arg & TUN_F_UFO) {
1741                         features |= NETIF_F_UFO;
1742                         arg &= ~TUN_F_UFO;
1743                 }
1744         }
1745
1746         /* This gives the user a way to test for new features in future by
1747          * trying to set them. */
1748         if (arg)
1749                 return -EINVAL;
1750
1751         tun->set_features = features;
1752         netdev_update_features(tun->dev);
1753
1754         return 0;
1755 }
1756
1757 static void tun_detach_filter(struct tun_struct *tun, int n)
1758 {
1759         int i;
1760         struct tun_file *tfile;
1761
1762         for (i = 0; i < n; i++) {
1763                 tfile = rtnl_dereference(tun->tfiles[i]);
1764                 sk_detach_filter(tfile->socket.sk);
1765         }
1766
1767         tun->filter_attached = false;
1768 }
1769
1770 static int tun_attach_filter(struct tun_struct *tun)
1771 {
1772         int i, ret = 0;
1773         struct tun_file *tfile;
1774
1775         for (i = 0; i < tun->numqueues; i++) {
1776                 tfile = rtnl_dereference(tun->tfiles[i]);
1777                 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1778                 if (ret) {
1779                         tun_detach_filter(tun, i);
1780                         return ret;
1781                 }
1782         }
1783
1784         tun->filter_attached = true;
1785         return ret;
1786 }
1787
1788 static void tun_set_sndbuf(struct tun_struct *tun)
1789 {
1790         struct tun_file *tfile;
1791         int i;
1792
1793         for (i = 0; i < tun->numqueues; i++) {
1794                 tfile = rtnl_dereference(tun->tfiles[i]);
1795                 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1796         }
1797 }
1798
1799 static int tun_set_queue(struct file *file, struct ifreq *ifr)
1800 {
1801         struct tun_file *tfile = file->private_data;
1802         struct tun_struct *tun;
1803         int ret = 0;
1804
1805         rtnl_lock();
1806
1807         if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
1808                 tun = tfile->detached;
1809                 if (!tun) {
1810                         ret = -EINVAL;
1811                         goto unlock;
1812                 }
1813                 ret = security_tun_dev_attach_queue(tun->security);
1814                 if (ret < 0)
1815                         goto unlock;
1816                 ret = tun_attach(tun, file);
1817         } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
1818                 tun = rtnl_dereference(tfile->tun);
1819                 if (!tun || !(tun->flags & TUN_TAP_MQ))
1820                         ret = -EINVAL;
1821                 else
1822                         __tun_detach(tfile, false);
1823         } else
1824                 ret = -EINVAL;
1825
1826 unlock:
1827         rtnl_unlock();
1828         return ret;
1829 }
1830
1831 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
1832                             unsigned long arg, int ifreq_len)
1833 {
1834         struct tun_file *tfile = file->private_data;
1835         struct tun_struct *tun;
1836         void __user* argp = (void __user*)arg;
1837         struct ifreq ifr;
1838         kuid_t owner;
1839         kgid_t group;
1840         int sndbuf;
1841         int vnet_hdr_sz;
1842         int ret;
1843
1844         if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
1845                 if (copy_from_user(&ifr, argp, ifreq_len))
1846                         return -EFAULT;
1847         } else {
1848                 memset(&ifr, 0, sizeof(ifr));
1849         }
1850         if (cmd == TUNGETFEATURES) {
1851                 /* Currently this just means: "what IFF flags are valid?".
1852                  * This is needed because we never checked for invalid flags on
1853                  * TUNSETIFF. */
1854                 return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
1855                                 IFF_VNET_HDR | IFF_MULTI_QUEUE,
1856                                 (unsigned int __user*)argp);
1857         } else if (cmd == TUNSETQUEUE)
1858                 return tun_set_queue(file, &ifr);
1859
1860         ret = 0;
1861         rtnl_lock();
1862
1863         tun = __tun_get(tfile);
1864         if (cmd == TUNSETIFF && !tun) {
1865                 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1866
1867                 ret = tun_set_iff(tfile->net, file, &ifr);
1868
1869                 if (ret)
1870                         goto unlock;
1871
1872                 if (copy_to_user(argp, &ifr, ifreq_len))
1873                         ret = -EFAULT;
1874                 goto unlock;
1875         }
1876
1877         ret = -EBADFD;
1878         if (!tun)
1879                 goto unlock;
1880
1881         tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1882
1883         ret = 0;
1884         switch (cmd) {
1885         case TUNGETIFF:
1886                 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1887
1888                 if (copy_to_user(argp, &ifr, ifreq_len))
1889                         ret = -EFAULT;
1890                 break;
1891
1892         case TUNSETNOCSUM:
1893                 /* Disable/Enable checksum */
1894
1895                 /* [unimplemented] */
1896                 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
1897                           arg ? "disabled" : "enabled");
1898                 break;
1899
1900         case TUNSETPERSIST:
1901                 /* Disable/Enable persist mode. Keep an extra reference to the
1902                  * module to prevent the module being unprobed.
1903                  */
1904                 if (arg && !(tun->flags & TUN_PERSIST)) {
1905                         tun->flags |= TUN_PERSIST;
1906                         __module_get(THIS_MODULE);
1907                 }
1908                 if (!arg && (tun->flags & TUN_PERSIST)) {
1909                         tun->flags &= ~TUN_PERSIST;
1910                         module_put(THIS_MODULE);
1911                 }
1912
1913                 tun_debug(KERN_INFO, tun, "persist %s\n",
1914                           arg ? "enabled" : "disabled");
1915                 break;
1916
1917         case TUNSETOWNER:
1918                 /* Set owner of the device */
1919                 owner = make_kuid(current_user_ns(), arg);
1920                 if (!uid_valid(owner)) {
1921                         ret = -EINVAL;
1922                         break;
1923                 }
1924                 tun->owner = owner;
1925                 tun_debug(KERN_INFO, tun, "owner set to %u\n",
1926                           from_kuid(&init_user_ns, tun->owner));
1927                 break;
1928
1929         case TUNSETGROUP:
1930                 /* Set group of the device */
1931                 group = make_kgid(current_user_ns(), arg);
1932                 if (!gid_valid(group)) {
1933                         ret = -EINVAL;
1934                         break;
1935                 }
1936                 tun->group = group;
1937                 tun_debug(KERN_INFO, tun, "group set to %u\n",
1938                           from_kgid(&init_user_ns, tun->group));
1939                 break;
1940
1941         case TUNSETLINK:
1942                 /* Only allow setting the type when the interface is down */
1943                 if (tun->dev->flags & IFF_UP) {
1944                         tun_debug(KERN_INFO, tun,
1945                                   "Linktype set failed because interface is up\n");
1946                         ret = -EBUSY;
1947                 } else {
1948                         tun->dev->type = (int) arg;
1949                         tun_debug(KERN_INFO, tun, "linktype set to %d\n",
1950                                   tun->dev->type);
1951                         ret = 0;
1952                 }
1953                 break;
1954
1955 #ifdef TUN_DEBUG
1956         case TUNSETDEBUG:
1957                 tun->debug = arg;
1958                 break;
1959 #endif
1960         case TUNSETOFFLOAD:
1961                 ret = set_offload(tun, arg);
1962                 break;
1963
1964         case TUNSETTXFILTER:
1965                 /* Can be set only for TAPs */
1966                 ret = -EINVAL;
1967                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
1968                         break;
1969                 ret = update_filter(&tun->txflt, (void __user *)arg);
1970                 break;
1971
1972         case SIOCGIFHWADDR:
1973                 /* Get hw address */
1974                 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
1975                 ifr.ifr_hwaddr.sa_family = tun->dev->type;
1976                 if (copy_to_user(argp, &ifr, ifreq_len))
1977                         ret = -EFAULT;
1978                 break;
1979
1980         case SIOCSIFHWADDR:
1981                 /* Set hw address */
1982                 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
1983                           ifr.ifr_hwaddr.sa_data);
1984
1985                 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
1986                 break;
1987
1988         case TUNGETSNDBUF:
1989                 sndbuf = tfile->socket.sk->sk_sndbuf;
1990                 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
1991                         ret = -EFAULT;
1992                 break;
1993
1994         case TUNSETSNDBUF:
1995                 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
1996                         ret = -EFAULT;
1997                         break;
1998                 }
1999
2000                 tun->sndbuf = sndbuf;
2001                 tun_set_sndbuf(tun);
2002                 break;
2003
2004         case TUNGETVNETHDRSZ:
2005                 vnet_hdr_sz = tun->vnet_hdr_sz;
2006                 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2007                         ret = -EFAULT;
2008                 break;
2009
2010         case TUNSETVNETHDRSZ:
2011                 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2012                         ret = -EFAULT;
2013                         break;
2014                 }
2015                 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2016                         ret = -EINVAL;
2017                         break;
2018                 }
2019
2020                 tun->vnet_hdr_sz = vnet_hdr_sz;
2021                 break;
2022
2023         case TUNATTACHFILTER:
2024                 /* Can be set only for TAPs */
2025                 ret = -EINVAL;
2026                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2027                         break;
2028                 ret = -EFAULT;
2029                 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
2030                         break;
2031
2032                 ret = tun_attach_filter(tun);
2033                 break;
2034
2035         case TUNDETACHFILTER:
2036                 /* Can be set only for TAPs */
2037                 ret = -EINVAL;
2038                 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2039                         break;
2040                 ret = 0;
2041                 tun_detach_filter(tun, tun->numqueues);
2042                 break;
2043
2044         default:
2045                 ret = -EINVAL;
2046                 break;
2047         }
2048
2049 unlock:
2050         rtnl_unlock();
2051         if (tun)
2052                 tun_put(tun);
2053         return ret;
2054 }
2055
2056 static long tun_chr_ioctl(struct file *file,
2057                           unsigned int cmd, unsigned long arg)
2058 {
2059         return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2060 }
2061
2062 #ifdef CONFIG_COMPAT
2063 static long tun_chr_compat_ioctl(struct file *file,
2064                          unsigned int cmd, unsigned long arg)
2065 {
2066         switch (cmd) {
2067         case TUNSETIFF:
2068         case TUNGETIFF:
2069         case TUNSETTXFILTER:
2070         case TUNGETSNDBUF:
2071         case TUNSETSNDBUF:
2072         case SIOCGIFHWADDR:
2073         case SIOCSIFHWADDR:
2074                 arg = (unsigned long)compat_ptr(arg);
2075                 break;
2076         default:
2077                 arg = (compat_ulong_t)arg;
2078                 break;
2079         }
2080
2081         /*
2082          * compat_ifreq is shorter than ifreq, so we must not access beyond
2083          * the end of that structure. All fields that are used in this
2084          * driver are compatible though, we don't need to convert the
2085          * contents.
2086          */
2087         return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2088 }
2089 #endif /* CONFIG_COMPAT */
2090
2091 static int tun_chr_fasync(int fd, struct file *file, int on)
2092 {
2093         struct tun_file *tfile = file->private_data;
2094         int ret;
2095
2096         if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
2097                 goto out;
2098
2099         if (on) {
2100                 ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
2101                 if (ret)
2102                         goto out;
2103                 tfile->flags |= TUN_FASYNC;
2104         } else
2105                 tfile->flags &= ~TUN_FASYNC;
2106         ret = 0;
2107 out:
2108         return ret;
2109 }
2110
2111 static int tun_chr_open(struct inode *inode, struct file * file)
2112 {
2113         struct tun_file *tfile;
2114
2115         DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2116
2117         tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
2118                                             &tun_proto);
2119         if (!tfile)
2120                 return -ENOMEM;
2121         rcu_assign_pointer(tfile->tun, NULL);
2122         tfile->net = get_net(current->nsproxy->net_ns);
2123         tfile->flags = 0;
2124
2125         rcu_assign_pointer(tfile->socket.wq, &tfile->wq);
2126         init_waitqueue_head(&tfile->wq.wait);
2127
2128         tfile->socket.file = file;
2129         tfile->socket.ops = &tun_socket_ops;
2130
2131         sock_init_data(&tfile->socket, &tfile->sk);
2132         sk_change_net(&tfile->sk, tfile->net);
2133
2134         tfile->sk.sk_write_space = tun_sock_write_space;
2135         tfile->sk.sk_sndbuf = INT_MAX;
2136
2137         file->private_data = tfile;
2138         set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
2139         INIT_LIST_HEAD(&tfile->next);
2140
2141         return 0;
2142 }
2143
2144 static int tun_chr_close(struct inode *inode, struct file *file)
2145 {
2146         struct tun_file *tfile = file->private_data;
2147         struct net *net = tfile->net;
2148
2149         tun_detach(tfile, true);
2150         put_net(net);
2151
2152         return 0;
2153 }
2154
2155 static const struct file_operations tun_fops = {
2156         .owner  = THIS_MODULE,
2157         .llseek = no_llseek,
2158         .read  = do_sync_read,
2159         .aio_read  = tun_chr_aio_read,
2160         .write = do_sync_write,
2161         .aio_write = tun_chr_aio_write,
2162         .poll   = tun_chr_poll,
2163         .unlocked_ioctl = tun_chr_ioctl,
2164 #ifdef CONFIG_COMPAT
2165         .compat_ioctl = tun_chr_compat_ioctl,
2166 #endif
2167         .open   = tun_chr_open,
2168         .release = tun_chr_close,
2169         .fasync = tun_chr_fasync
2170 };
2171
2172 static struct miscdevice tun_miscdev = {
2173         .minor = TUN_MINOR,
2174         .name = "tun",
2175         .nodename = "net/tun",
2176         .fops = &tun_fops,
2177 };
2178
2179 /* ethtool interface */
2180
2181 static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2182 {
2183         cmd->supported          = 0;
2184         cmd->advertising        = 0;
2185         ethtool_cmd_speed_set(cmd, SPEED_10);
2186         cmd->duplex             = DUPLEX_FULL;
2187         cmd->port               = PORT_TP;
2188         cmd->phy_address        = 0;
2189         cmd->transceiver        = XCVR_INTERNAL;
2190         cmd->autoneg            = AUTONEG_DISABLE;
2191         cmd->maxtxpkt           = 0;
2192         cmd->maxrxpkt           = 0;
2193         return 0;
2194 }
2195
2196 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2197 {
2198         struct tun_struct *tun = netdev_priv(dev);
2199
2200         strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
2201         strlcpy(info->version, DRV_VERSION, sizeof(info->version));
2202
2203         switch (tun->flags & TUN_TYPE_MASK) {
2204         case TUN_TUN_DEV:
2205                 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
2206                 break;
2207         case TUN_TAP_DEV:
2208                 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
2209                 break;
2210         }
2211 }
2212
2213 static u32 tun_get_msglevel(struct net_device *dev)
2214 {
2215 #ifdef TUN_DEBUG
2216         struct tun_struct *tun = netdev_priv(dev);
2217         return tun->debug;
2218 #else
2219         return -EOPNOTSUPP;
2220 #endif
2221 }
2222
2223 static void tun_set_msglevel(struct net_device *dev, u32 value)
2224 {
2225 #ifdef TUN_DEBUG
2226         struct tun_struct *tun = netdev_priv(dev);
2227         tun->debug = value;
2228 #endif
2229 }
2230
2231 static const struct ethtool_ops tun_ethtool_ops = {
2232         .get_settings   = tun_get_settings,
2233         .get_drvinfo    = tun_get_drvinfo,
2234         .get_msglevel   = tun_get_msglevel,
2235         .set_msglevel   = tun_set_msglevel,
2236         .get_link       = ethtool_op_get_link,
2237 };
2238
2239
2240 static int __init tun_init(void)
2241 {
2242         int ret = 0;
2243
2244         pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
2245         pr_info("%s\n", DRV_COPYRIGHT);
2246
2247         ret = rtnl_link_register(&tun_link_ops);
2248         if (ret) {
2249                 pr_err("Can't register link_ops\n");
2250                 goto err_linkops;
2251         }
2252
2253         ret = misc_register(&tun_miscdev);
2254         if (ret) {
2255                 pr_err("Can't register misc device %d\n", TUN_MINOR);
2256                 goto err_misc;
2257         }
2258         return  0;
2259 err_misc:
2260         rtnl_link_unregister(&tun_link_ops);
2261 err_linkops:
2262         return ret;
2263 }
2264
2265 static void tun_cleanup(void)
2266 {
2267         misc_deregister(&tun_miscdev);
2268         rtnl_link_unregister(&tun_link_ops);
2269 }
2270
2271 /* Get an underlying socket object from tun file.  Returns error unless file is
2272  * attached to a device.  The returned object works like a packet socket, it
2273  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
2274  * holding a reference to the file for as long as the socket is in use. */
2275 struct socket *tun_get_socket(struct file *file)
2276 {
2277         struct tun_file *tfile;
2278         if (file->f_op != &tun_fops)
2279                 return ERR_PTR(-EINVAL);
2280         tfile = file->private_data;
2281         if (!tfile)
2282                 return ERR_PTR(-EBADFD);
2283         return &tfile->socket;
2284 }
2285 EXPORT_SYMBOL_GPL(tun_get_socket);
2286
2287 module_init(tun_init);
2288 module_exit(tun_cleanup);
2289 MODULE_DESCRIPTION(DRV_DESCRIPTION);
2290 MODULE_AUTHOR(DRV_COPYRIGHT);
2291 MODULE_LICENSE("GPL");
2292 MODULE_ALIAS_MISCDEV(TUN_MINOR);
2293 MODULE_ALIAS("devname:net/tun");