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