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