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