GNU Linux-libre 4.14.313-gnu1
[releases.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/sched/signal.h>
48 #include <linux/major.h>
49 #include <linux/slab.h>
50 #include <linux/poll.h>
51 #include <linux/fcntl.h>
52 #include <linux/init.h>
53 #include <linux/skbuff.h>
54 #include <linux/netdevice.h>
55 #include <linux/etherdevice.h>
56 #include <linux/miscdevice.h>
57 #include <linux/ethtool.h>
58 #include <linux/rtnetlink.h>
59 #include <linux/compat.h>
60 #include <linux/if.h>
61 #include <linux/if_arp.h>
62 #include <linux/if_ether.h>
63 #include <linux/if_tun.h>
64 #include <linux/if_vlan.h>
65 #include <linux/crc32.h>
66 #include <linux/nsproxy.h>
67 #include <linux/virtio_net.h>
68 #include <linux/rcupdate.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 #include <linux/uio.h>
75 #include <linux/skb_array.h>
76 #include <linux/bpf.h>
77 #include <linux/bpf_trace.h>
78 #include <linux/ieee802154.h>
79 #include <linux/if_ltalk.h>
80 #include <uapi/linux/if_fddi.h>
81 #include <uapi/linux/if_hippi.h>
82 #include <uapi/linux/if_fc.h>
83 #include <net/ax25.h>
84 #include <net/rose.h>
85 #include <net/6lowpan.h>
86
87 #include <linux/uaccess.h>
88
89 /* Uncomment to enable debugging */
90 /* #define TUN_DEBUG 1 */
91
92 #ifdef TUN_DEBUG
93 static int debug;
94
95 #define tun_debug(level, tun, fmt, args...)                     \
96 do {                                                            \
97         if (tun->debug)                                         \
98                 netdev_printk(level, tun->dev, fmt, ##args);    \
99 } while (0)
100 #define DBG1(level, fmt, args...)                               \
101 do {                                                            \
102         if (debug == 2)                                         \
103                 printk(level fmt, ##args);                      \
104 } while (0)
105 #else
106 #define tun_debug(level, tun, fmt, args...)                     \
107 do {                                                            \
108         if (0)                                                  \
109                 netdev_printk(level, tun->dev, fmt, ##args);    \
110 } while (0)
111 #define DBG1(level, fmt, args...)                               \
112 do {                                                            \
113         if (0)                                                  \
114                 printk(level fmt, ##args);                      \
115 } while (0)
116 #endif
117
118 #define TUN_HEADROOM 256
119 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
120
121 /* TUN device flags */
122
123 /* IFF_ATTACH_QUEUE is never stored in device flags,
124  * overload it to mean fasync when stored there.
125  */
126 #define TUN_FASYNC      IFF_ATTACH_QUEUE
127 /* High bits in flags field are unused. */
128 #define TUN_VNET_LE     0x80000000
129 #define TUN_VNET_BE     0x40000000
130
131 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
132                       IFF_MULTI_QUEUE)
133 #define GOODCOPY_LEN 128
134
135 #define FLT_EXACT_COUNT 8
136 struct tap_filter {
137         unsigned int    count;    /* Number of addrs. Zero means disabled */
138         u32             mask[2];  /* Mask of the hashed addrs */
139         unsigned char   addr[FLT_EXACT_COUNT][ETH_ALEN];
140 };
141
142 /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
143  * to max number of VCPUs in guest. */
144 #define MAX_TAP_QUEUES 256
145 #define MAX_TAP_FLOWS  4096
146
147 #define TUN_FLOW_EXPIRE (3 * HZ)
148
149 struct tun_pcpu_stats {
150         u64 rx_packets;
151         u64 rx_bytes;
152         u64 tx_packets;
153         u64 tx_bytes;
154         struct u64_stats_sync syncp;
155         u32 rx_dropped;
156         u32 tx_dropped;
157         u32 rx_frame_errors;
158 };
159
160 /* A tun_file connects an open character device to a tuntap netdevice. It
161  * also contains all socket related structures (except sock_fprog and tap_filter)
162  * to serve as one transmit queue for tuntap device. The sock_fprog and
163  * tap_filter were kept in tun_struct since they were used for filtering for the
164  * netdevice not for a specific queue (at least I didn't see the requirement for
165  * this).
166  *
167  * RCU usage:
168  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
169  * other can only be read while rcu_read_lock or rtnl_lock is held.
170  */
171 struct tun_file {
172         struct sock sk;
173         struct socket socket;
174         struct socket_wq wq;
175         struct tun_struct __rcu *tun;
176         struct fasync_struct *fasync;
177         /* only used for fasnyc */
178         unsigned int flags;
179         union {
180                 u16 queue_index;
181                 unsigned int ifindex;
182         };
183         struct list_head next;
184         struct tun_struct *detached;
185         struct skb_array tx_array;
186 };
187
188 struct tun_flow_entry {
189         struct hlist_node hash_link;
190         struct rcu_head rcu;
191         struct tun_struct *tun;
192
193         u32 rxhash;
194         u32 rps_rxhash;
195         int queue_index;
196         unsigned long updated;
197 };
198
199 #define TUN_NUM_FLOW_ENTRIES 1024
200
201 /* Since the socket were moved to tun_file, to preserve the behavior of persist
202  * device, socket filter, sndbuf and vnet header size were restore when the
203  * file were attached to a persist device.
204  */
205 struct tun_struct {
206         struct tun_file __rcu   *tfiles[MAX_TAP_QUEUES];
207         unsigned int            numqueues;
208         unsigned int            flags;
209         kuid_t                  owner;
210         kgid_t                  group;
211
212         struct net_device       *dev;
213         netdev_features_t       set_features;
214 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
215                           NETIF_F_TSO6)
216
217         int                     align;
218         int                     vnet_hdr_sz;
219         int                     sndbuf;
220         struct tap_filter       txflt;
221         struct sock_fprog       fprog;
222         /* protected by rtnl lock */
223         bool                    filter_attached;
224 #ifdef TUN_DEBUG
225         int debug;
226 #endif
227         spinlock_t lock;
228         struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
229         struct timer_list flow_gc_timer;
230         unsigned long ageing_time;
231         unsigned int numdisabled;
232         struct list_head disabled;
233         void *security;
234         u32 flow_count;
235         u32 rx_batched;
236         struct tun_pcpu_stats __percpu *pcpu_stats;
237         struct bpf_prog __rcu *xdp_prog;
238 };
239
240 #ifdef CONFIG_TUN_VNET_CROSS_LE
241 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
242 {
243         return tun->flags & TUN_VNET_BE ? false :
244                 virtio_legacy_is_little_endian();
245 }
246
247 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
248 {
249         int be = !!(tun->flags & TUN_VNET_BE);
250
251         if (put_user(be, argp))
252                 return -EFAULT;
253
254         return 0;
255 }
256
257 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
258 {
259         int be;
260
261         if (get_user(be, argp))
262                 return -EFAULT;
263
264         if (be)
265                 tun->flags |= TUN_VNET_BE;
266         else
267                 tun->flags &= ~TUN_VNET_BE;
268
269         return 0;
270 }
271 #else
272 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
273 {
274         return virtio_legacy_is_little_endian();
275 }
276
277 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
278 {
279         return -EINVAL;
280 }
281
282 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
283 {
284         return -EINVAL;
285 }
286 #endif /* CONFIG_TUN_VNET_CROSS_LE */
287
288 static inline bool tun_is_little_endian(struct tun_struct *tun)
289 {
290         return tun->flags & TUN_VNET_LE ||
291                 tun_legacy_is_little_endian(tun);
292 }
293
294 static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
295 {
296         return __virtio16_to_cpu(tun_is_little_endian(tun), val);
297 }
298
299 static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
300 {
301         return __cpu_to_virtio16(tun_is_little_endian(tun), val);
302 }
303
304 static inline u32 tun_hashfn(u32 rxhash)
305 {
306         return rxhash & 0x3ff;
307 }
308
309 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
310 {
311         struct tun_flow_entry *e;
312
313         hlist_for_each_entry_rcu(e, head, hash_link) {
314                 if (e->rxhash == rxhash)
315                         return e;
316         }
317         return NULL;
318 }
319
320 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
321                                               struct hlist_head *head,
322                                               u32 rxhash, u16 queue_index)
323 {
324         struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
325
326         if (e) {
327                 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
328                           rxhash, queue_index);
329                 e->updated = jiffies;
330                 e->rxhash = rxhash;
331                 e->rps_rxhash = 0;
332                 e->queue_index = queue_index;
333                 e->tun = tun;
334                 hlist_add_head_rcu(&e->hash_link, head);
335                 ++tun->flow_count;
336         }
337         return e;
338 }
339
340 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
341 {
342         tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
343                   e->rxhash, e->queue_index);
344         hlist_del_rcu(&e->hash_link);
345         kfree_rcu(e, rcu);
346         --tun->flow_count;
347 }
348
349 static void tun_flow_flush(struct tun_struct *tun)
350 {
351         int i;
352
353         spin_lock_bh(&tun->lock);
354         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
355                 struct tun_flow_entry *e;
356                 struct hlist_node *n;
357
358                 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
359                         tun_flow_delete(tun, e);
360         }
361         spin_unlock_bh(&tun->lock);
362 }
363
364 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
365 {
366         int i;
367
368         spin_lock_bh(&tun->lock);
369         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
370                 struct tun_flow_entry *e;
371                 struct hlist_node *n;
372
373                 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
374                         if (e->queue_index == queue_index)
375                                 tun_flow_delete(tun, e);
376                 }
377         }
378         spin_unlock_bh(&tun->lock);
379 }
380
381 static void tun_flow_cleanup(unsigned long data)
382 {
383         struct tun_struct *tun = (struct tun_struct *)data;
384         unsigned long delay = tun->ageing_time;
385         unsigned long next_timer = jiffies + delay;
386         unsigned long count = 0;
387         int i;
388
389         tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
390
391         spin_lock_bh(&tun->lock);
392         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
393                 struct tun_flow_entry *e;
394                 struct hlist_node *n;
395
396                 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
397                         unsigned long this_timer;
398                         count++;
399                         this_timer = e->updated + delay;
400                         if (time_before_eq(this_timer, jiffies))
401                                 tun_flow_delete(tun, e);
402                         else if (time_before(this_timer, next_timer))
403                                 next_timer = this_timer;
404                 }
405         }
406
407         if (count)
408                 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
409         spin_unlock_bh(&tun->lock);
410 }
411
412 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
413                             struct tun_file *tfile)
414 {
415         struct hlist_head *head;
416         struct tun_flow_entry *e;
417         unsigned long delay = tun->ageing_time;
418         u16 queue_index = tfile->queue_index;
419
420         if (!rxhash)
421                 return;
422         else
423                 head = &tun->flows[tun_hashfn(rxhash)];
424
425         rcu_read_lock();
426
427         /* We may get a very small possibility of OOO during switching, not
428          * worth to optimize.*/
429         if (tun->numqueues == 1 || tfile->detached)
430                 goto unlock;
431
432         e = tun_flow_find(head, rxhash);
433         if (likely(e)) {
434                 /* TODO: keep queueing to old queue until it's empty? */
435                 e->queue_index = queue_index;
436                 e->updated = jiffies;
437                 sock_rps_record_flow_hash(e->rps_rxhash);
438         } else {
439                 spin_lock_bh(&tun->lock);
440                 if (!tun_flow_find(head, rxhash) &&
441                     tun->flow_count < MAX_TAP_FLOWS)
442                         tun_flow_create(tun, head, rxhash, queue_index);
443
444                 if (!timer_pending(&tun->flow_gc_timer))
445                         mod_timer(&tun->flow_gc_timer,
446                                   round_jiffies_up(jiffies + delay));
447                 spin_unlock_bh(&tun->lock);
448         }
449
450 unlock:
451         rcu_read_unlock();
452 }
453
454 /**
455  * Save the hash received in the stack receive path and update the
456  * flow_hash table accordingly.
457  */
458 static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
459 {
460         if (unlikely(e->rps_rxhash != hash))
461                 e->rps_rxhash = hash;
462 }
463
464 /* We try to identify a flow through its rxhash first. The reason that
465  * we do not check rxq no. is because some cards(e.g 82599), chooses
466  * the rxq based on the txq where the last packet of the flow comes. As
467  * the userspace application move between processors, we may get a
468  * different rxq no. here. If we could not get rxhash, then we would
469  * hope the rxq no. may help here.
470  */
471 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
472                             void *accel_priv, select_queue_fallback_t fallback)
473 {
474         struct tun_struct *tun = netdev_priv(dev);
475         struct tun_flow_entry *e;
476         u32 txq = 0;
477         u32 numqueues = 0;
478
479         rcu_read_lock();
480         numqueues = ACCESS_ONCE(tun->numqueues);
481
482         txq = __skb_get_hash_symmetric(skb);
483         if (txq) {
484                 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
485                 if (e) {
486                         tun_flow_save_rps_rxhash(e, txq);
487                         txq = e->queue_index;
488                 } else
489                         /* use multiply and shift instead of expensive divide */
490                         txq = ((u64)txq * numqueues) >> 32;
491         } else if (likely(skb_rx_queue_recorded(skb))) {
492                 txq = skb_get_rx_queue(skb);
493                 while (unlikely(txq >= numqueues))
494                         txq -= numqueues;
495         }
496
497         rcu_read_unlock();
498         return txq;
499 }
500
501 static inline bool tun_not_capable(struct tun_struct *tun)
502 {
503         const struct cred *cred = current_cred();
504         struct net *net = dev_net(tun->dev);
505
506         return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
507                   (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
508                 !ns_capable(net->user_ns, CAP_NET_ADMIN);
509 }
510
511 static void tun_set_real_num_queues(struct tun_struct *tun)
512 {
513         netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
514         netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
515 }
516
517 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
518 {
519         tfile->detached = tun;
520         list_add_tail(&tfile->next, &tun->disabled);
521         ++tun->numdisabled;
522 }
523
524 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
525 {
526         struct tun_struct *tun = tfile->detached;
527
528         tfile->detached = NULL;
529         list_del_init(&tfile->next);
530         --tun->numdisabled;
531         return tun;
532 }
533
534 static void tun_queue_purge(struct tun_file *tfile)
535 {
536         struct sk_buff *skb;
537
538         while ((skb = skb_array_consume(&tfile->tx_array)) != NULL)
539                 kfree_skb(skb);
540
541         skb_queue_purge(&tfile->sk.sk_write_queue);
542         skb_queue_purge(&tfile->sk.sk_error_queue);
543 }
544
545 static void __tun_detach(struct tun_file *tfile, bool clean)
546 {
547         struct tun_file *ntfile;
548         struct tun_struct *tun;
549
550         tun = rtnl_dereference(tfile->tun);
551
552         if (tun && !tfile->detached) {
553                 u16 index = tfile->queue_index;
554                 BUG_ON(index >= tun->numqueues);
555
556                 rcu_assign_pointer(tun->tfiles[index],
557                                    tun->tfiles[tun->numqueues - 1]);
558                 ntfile = rtnl_dereference(tun->tfiles[index]);
559                 ntfile->queue_index = index;
560
561                 --tun->numqueues;
562                 if (clean) {
563                         RCU_INIT_POINTER(tfile->tun, NULL);
564                         sock_put(&tfile->sk);
565                 } else
566                         tun_disable_queue(tun, tfile);
567
568                 synchronize_net();
569                 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
570                 /* Drop read queue */
571                 tun_queue_purge(tfile);
572                 tun_set_real_num_queues(tun);
573         } else if (tfile->detached && clean) {
574                 tun = tun_enable_queue(tfile);
575                 sock_put(&tfile->sk);
576         }
577
578         if (clean) {
579                 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
580                         netif_carrier_off(tun->dev);
581
582                         if (!(tun->flags & IFF_PERSIST) &&
583                             tun->dev->reg_state == NETREG_REGISTERED)
584                                 unregister_netdevice(tun->dev);
585                 }
586                 skb_array_cleanup(&tfile->tx_array);
587                 sock_put(&tfile->sk);
588         }
589 }
590
591 static void tun_detach(struct tun_file *tfile, bool clean)
592 {
593         rtnl_lock();
594         __tun_detach(tfile, clean);
595         rtnl_unlock();
596 }
597
598 static void tun_detach_all(struct net_device *dev)
599 {
600         struct tun_struct *tun = netdev_priv(dev);
601         struct bpf_prog *xdp_prog = rtnl_dereference(tun->xdp_prog);
602         struct tun_file *tfile, *tmp;
603         int i, n = tun->numqueues;
604
605         for (i = 0; i < n; i++) {
606                 tfile = rtnl_dereference(tun->tfiles[i]);
607                 BUG_ON(!tfile);
608                 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
609                 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
610                 RCU_INIT_POINTER(tfile->tun, NULL);
611                 --tun->numqueues;
612         }
613         list_for_each_entry(tfile, &tun->disabled, next) {
614                 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
615                 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
616                 RCU_INIT_POINTER(tfile->tun, NULL);
617         }
618         BUG_ON(tun->numqueues != 0);
619
620         synchronize_net();
621         for (i = 0; i < n; i++) {
622                 tfile = rtnl_dereference(tun->tfiles[i]);
623                 /* Drop read queue */
624                 tun_queue_purge(tfile);
625                 sock_put(&tfile->sk);
626         }
627         list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
628                 tun_enable_queue(tfile);
629                 tun_queue_purge(tfile);
630                 sock_put(&tfile->sk);
631         }
632         BUG_ON(tun->numdisabled != 0);
633
634         if (xdp_prog)
635                 bpf_prog_put(xdp_prog);
636
637         if (tun->flags & IFF_PERSIST)
638                 module_put(THIS_MODULE);
639 }
640
641 static int tun_attach(struct tun_struct *tun, struct file *file,
642                       bool skip_filter, bool publish_tun)
643 {
644         struct tun_file *tfile = file->private_data;
645         struct net_device *dev = tun->dev;
646         int err;
647
648         err = security_tun_dev_attach(tfile->socket.sk, tun->security);
649         if (err < 0)
650                 goto out;
651
652         err = -EINVAL;
653         if (rtnl_dereference(tfile->tun) && !tfile->detached)
654                 goto out;
655
656         err = -EBUSY;
657         if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
658                 goto out;
659
660         err = -E2BIG;
661         if (!tfile->detached &&
662             tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
663                 goto out;
664
665         err = 0;
666
667         /* Re-attach the filter to persist device */
668         if (!skip_filter && (tun->filter_attached == true)) {
669                 lock_sock(tfile->socket.sk);
670                 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
671                 release_sock(tfile->socket.sk);
672                 if (!err)
673                         goto out;
674         }
675
676         if (!tfile->detached &&
677             skb_array_resize(&tfile->tx_array, dev->tx_queue_len, GFP_KERNEL)) {
678                 err = -ENOMEM;
679                 goto out;
680         }
681
682         tfile->queue_index = tun->numqueues;
683         tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
684         if (publish_tun)
685                 rcu_assign_pointer(tfile->tun, tun);
686         rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
687         tun->numqueues++;
688
689         if (tfile->detached)
690                 tun_enable_queue(tfile);
691         else
692                 sock_hold(&tfile->sk);
693
694         tun_set_real_num_queues(tun);
695
696         /* device is allowed to go away first, so no need to hold extra
697          * refcnt.
698          */
699
700 out:
701         return err;
702 }
703
704 static struct tun_struct *__tun_get(struct tun_file *tfile)
705 {
706         struct tun_struct *tun;
707
708         rcu_read_lock();
709         tun = rcu_dereference(tfile->tun);
710         if (tun)
711                 dev_hold(tun->dev);
712         rcu_read_unlock();
713
714         return tun;
715 }
716
717 static struct tun_struct *tun_get(struct file *file)
718 {
719         return __tun_get(file->private_data);
720 }
721
722 static void tun_put(struct tun_struct *tun)
723 {
724         dev_put(tun->dev);
725 }
726
727 /* TAP filtering */
728 static void addr_hash_set(u32 *mask, const u8 *addr)
729 {
730         int n = ether_crc(ETH_ALEN, addr) >> 26;
731         mask[n >> 5] |= (1 << (n & 31));
732 }
733
734 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
735 {
736         int n = ether_crc(ETH_ALEN, addr) >> 26;
737         return mask[n >> 5] & (1 << (n & 31));
738 }
739
740 static int update_filter(struct tap_filter *filter, void __user *arg)
741 {
742         struct { u8 u[ETH_ALEN]; } *addr;
743         struct tun_filter uf;
744         int err, alen, n, nexact;
745
746         if (copy_from_user(&uf, arg, sizeof(uf)))
747                 return -EFAULT;
748
749         if (!uf.count) {
750                 /* Disabled */
751                 filter->count = 0;
752                 return 0;
753         }
754
755         alen = ETH_ALEN * uf.count;
756         addr = memdup_user(arg + sizeof(uf), alen);
757         if (IS_ERR(addr))
758                 return PTR_ERR(addr);
759
760         /* The filter is updated without holding any locks. Which is
761          * perfectly safe. We disable it first and in the worst
762          * case we'll accept a few undesired packets. */
763         filter->count = 0;
764         wmb();
765
766         /* Use first set of addresses as an exact filter */
767         for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
768                 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
769
770         nexact = n;
771
772         /* Remaining multicast addresses are hashed,
773          * unicast will leave the filter disabled. */
774         memset(filter->mask, 0, sizeof(filter->mask));
775         for (; n < uf.count; n++) {
776                 if (!is_multicast_ether_addr(addr[n].u)) {
777                         err = 0; /* no filter */
778                         goto free_addr;
779                 }
780                 addr_hash_set(filter->mask, addr[n].u);
781         }
782
783         /* For ALLMULTI just set the mask to all ones.
784          * This overrides the mask populated above. */
785         if ((uf.flags & TUN_FLT_ALLMULTI))
786                 memset(filter->mask, ~0, sizeof(filter->mask));
787
788         /* Now enable the filter */
789         wmb();
790         filter->count = nexact;
791
792         /* Return the number of exact filters */
793         err = nexact;
794 free_addr:
795         kfree(addr);
796         return err;
797 }
798
799 /* Returns: 0 - drop, !=0 - accept */
800 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
801 {
802         /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
803          * at this point. */
804         struct ethhdr *eh = (struct ethhdr *) skb->data;
805         int i;
806
807         /* Exact match */
808         for (i = 0; i < filter->count; i++)
809                 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
810                         return 1;
811
812         /* Inexact match (multicast only) */
813         if (is_multicast_ether_addr(eh->h_dest))
814                 return addr_hash_test(filter->mask, eh->h_dest);
815
816         return 0;
817 }
818
819 /*
820  * Checks whether the packet is accepted or not.
821  * Returns: 0 - drop, !=0 - accept
822  */
823 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
824 {
825         if (!filter->count)
826                 return 1;
827
828         return run_filter(filter, skb);
829 }
830
831 /* Network device part of the driver */
832
833 static const struct ethtool_ops tun_ethtool_ops;
834
835 /* Net device detach from fd. */
836 static void tun_net_uninit(struct net_device *dev)
837 {
838         tun_detach_all(dev);
839 }
840
841 /* Net device open. */
842 static int tun_net_open(struct net_device *dev)
843 {
844         netif_tx_start_all_queues(dev);
845
846         return 0;
847 }
848
849 /* Net device close. */
850 static int tun_net_close(struct net_device *dev)
851 {
852         netif_tx_stop_all_queues(dev);
853         return 0;
854 }
855
856 /* Net device start xmit */
857 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
858 {
859         struct tun_struct *tun = netdev_priv(dev);
860         int txq = skb->queue_mapping;
861         struct netdev_queue *queue;
862         struct tun_file *tfile;
863         u32 numqueues = 0;
864
865         rcu_read_lock();
866         tfile = rcu_dereference(tun->tfiles[txq]);
867         numqueues = ACCESS_ONCE(tun->numqueues);
868
869         /* Drop packet if interface is not attached */
870         if (txq >= numqueues)
871                 goto drop;
872
873 #ifdef CONFIG_RPS
874         if (numqueues == 1 && static_key_false(&rps_needed)) {
875                 /* Select queue was not called for the skbuff, so we extract the
876                  * RPS hash and save it into the flow_table here.
877                  */
878                 __u32 rxhash;
879
880                 rxhash = __skb_get_hash_symmetric(skb);
881                 if (rxhash) {
882                         struct tun_flow_entry *e;
883                         e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
884                                         rxhash);
885                         if (e)
886                                 tun_flow_save_rps_rxhash(e, rxhash);
887                 }
888         }
889 #endif
890
891         tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
892
893         BUG_ON(!tfile);
894
895         /* Drop if the filter does not like it.
896          * This is a noop if the filter is disabled.
897          * Filter can be enabled only for the TAP devices. */
898         if (!check_filter(&tun->txflt, skb))
899                 goto drop;
900
901         if (tfile->socket.sk->sk_filter &&
902             sk_filter(tfile->socket.sk, skb))
903                 goto drop;
904
905         if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
906                 goto drop;
907
908         skb_tx_timestamp(skb);
909
910         /* Orphan the skb - required as we might hang on to it
911          * for indefinite time.
912          */
913         skb_orphan(skb);
914
915         nf_reset(skb);
916
917         if (skb_array_produce(&tfile->tx_array, skb))
918                 goto drop;
919
920         /* NETIF_F_LLTX requires to do our own update of trans_start */
921         queue = netdev_get_tx_queue(dev, txq);
922         queue->trans_start = jiffies;
923
924         /* Notify and wake up reader process */
925         if (tfile->flags & TUN_FASYNC)
926                 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
927         tfile->socket.sk->sk_data_ready(tfile->socket.sk);
928
929         rcu_read_unlock();
930         return NETDEV_TX_OK;
931
932 drop:
933         this_cpu_inc(tun->pcpu_stats->tx_dropped);
934         skb_tx_error(skb);
935         kfree_skb(skb);
936         rcu_read_unlock();
937         return NET_XMIT_DROP;
938 }
939
940 static void tun_net_mclist(struct net_device *dev)
941 {
942         /*
943          * This callback is supposed to deal with mc filter in
944          * _rx_ path and has nothing to do with the _tx_ path.
945          * In rx path we always accept everything userspace gives us.
946          */
947 }
948
949 static netdev_features_t tun_net_fix_features(struct net_device *dev,
950         netdev_features_t features)
951 {
952         struct tun_struct *tun = netdev_priv(dev);
953
954         return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
955 }
956 #ifdef CONFIG_NET_POLL_CONTROLLER
957 static void tun_poll_controller(struct net_device *dev)
958 {
959         /*
960          * Tun only receives frames when:
961          * 1) the char device endpoint gets data from user space
962          * 2) the tun socket gets a sendmsg call from user space
963          * Since both of those are synchronous operations, we are guaranteed
964          * never to have pending data when we poll for it
965          * so there is nothing to do here but return.
966          * We need this though so netpoll recognizes us as an interface that
967          * supports polling, which enables bridge devices in virt setups to
968          * still use netconsole
969          */
970         return;
971 }
972 #endif
973
974 static void tun_set_headroom(struct net_device *dev, int new_hr)
975 {
976         struct tun_struct *tun = netdev_priv(dev);
977
978         if (new_hr < NET_SKB_PAD)
979                 new_hr = NET_SKB_PAD;
980
981         tun->align = new_hr;
982 }
983
984 static void
985 tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
986 {
987         u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
988         struct tun_struct *tun = netdev_priv(dev);
989         struct tun_pcpu_stats *p;
990         int i;
991
992         for_each_possible_cpu(i) {
993                 u64 rxpackets, rxbytes, txpackets, txbytes;
994                 unsigned int start;
995
996                 p = per_cpu_ptr(tun->pcpu_stats, i);
997                 do {
998                         start = u64_stats_fetch_begin(&p->syncp);
999                         rxpackets       = p->rx_packets;
1000                         rxbytes         = p->rx_bytes;
1001                         txpackets       = p->tx_packets;
1002                         txbytes         = p->tx_bytes;
1003                 } while (u64_stats_fetch_retry(&p->syncp, start));
1004
1005                 stats->rx_packets       += rxpackets;
1006                 stats->rx_bytes         += rxbytes;
1007                 stats->tx_packets       += txpackets;
1008                 stats->tx_bytes         += txbytes;
1009
1010                 /* u32 counters */
1011                 rx_dropped      += p->rx_dropped;
1012                 rx_frame_errors += p->rx_frame_errors;
1013                 tx_dropped      += p->tx_dropped;
1014         }
1015         stats->rx_dropped  = rx_dropped;
1016         stats->rx_frame_errors = rx_frame_errors;
1017         stats->tx_dropped = tx_dropped;
1018 }
1019
1020 static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1021                        struct netlink_ext_ack *extack)
1022 {
1023         struct tun_struct *tun = netdev_priv(dev);
1024         struct bpf_prog *old_prog;
1025
1026         old_prog = rtnl_dereference(tun->xdp_prog);
1027         rcu_assign_pointer(tun->xdp_prog, prog);
1028         if (old_prog)
1029                 bpf_prog_put(old_prog);
1030
1031         return 0;
1032 }
1033
1034 static u32 tun_xdp_query(struct net_device *dev)
1035 {
1036         struct tun_struct *tun = netdev_priv(dev);
1037         const struct bpf_prog *xdp_prog;
1038
1039         xdp_prog = rtnl_dereference(tun->xdp_prog);
1040         if (xdp_prog)
1041                 return xdp_prog->aux->id;
1042
1043         return 0;
1044 }
1045
1046 static int tun_xdp(struct net_device *dev, struct netdev_xdp *xdp)
1047 {
1048         switch (xdp->command) {
1049         case XDP_SETUP_PROG:
1050                 return tun_xdp_set(dev, xdp->prog, xdp->extack);
1051         case XDP_QUERY_PROG:
1052                 xdp->prog_id = tun_xdp_query(dev);
1053                 xdp->prog_attached = !!xdp->prog_id;
1054                 return 0;
1055         default:
1056                 return -EINVAL;
1057         }
1058 }
1059
1060 static const struct net_device_ops tun_netdev_ops = {
1061         .ndo_uninit             = tun_net_uninit,
1062         .ndo_open               = tun_net_open,
1063         .ndo_stop               = tun_net_close,
1064         .ndo_start_xmit         = tun_net_xmit,
1065         .ndo_fix_features       = tun_net_fix_features,
1066         .ndo_select_queue       = tun_select_queue,
1067 #ifdef CONFIG_NET_POLL_CONTROLLER
1068         .ndo_poll_controller    = tun_poll_controller,
1069 #endif
1070         .ndo_set_rx_headroom    = tun_set_headroom,
1071         .ndo_get_stats64        = tun_net_get_stats64,
1072 };
1073
1074 static const struct net_device_ops tap_netdev_ops = {
1075         .ndo_uninit             = tun_net_uninit,
1076         .ndo_open               = tun_net_open,
1077         .ndo_stop               = tun_net_close,
1078         .ndo_start_xmit         = tun_net_xmit,
1079         .ndo_fix_features       = tun_net_fix_features,
1080         .ndo_set_rx_mode        = tun_net_mclist,
1081         .ndo_set_mac_address    = eth_mac_addr,
1082         .ndo_validate_addr      = eth_validate_addr,
1083         .ndo_select_queue       = tun_select_queue,
1084 #ifdef CONFIG_NET_POLL_CONTROLLER
1085         .ndo_poll_controller    = tun_poll_controller,
1086 #endif
1087         .ndo_features_check     = passthru_features_check,
1088         .ndo_set_rx_headroom    = tun_set_headroom,
1089         .ndo_get_stats64        = tun_net_get_stats64,
1090         .ndo_xdp                = tun_xdp,
1091 };
1092
1093 static void tun_flow_init(struct tun_struct *tun)
1094 {
1095         int i;
1096
1097         for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
1098                 INIT_HLIST_HEAD(&tun->flows[i]);
1099
1100         tun->ageing_time = TUN_FLOW_EXPIRE;
1101         setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
1102         mod_timer(&tun->flow_gc_timer,
1103                   round_jiffies_up(jiffies + tun->ageing_time));
1104 }
1105
1106 static void tun_flow_uninit(struct tun_struct *tun)
1107 {
1108         del_timer_sync(&tun->flow_gc_timer);
1109         tun_flow_flush(tun);
1110 }
1111
1112 #define MIN_MTU 68
1113 #define MAX_MTU 65535
1114
1115 /* Initialize net device. */
1116 static void tun_net_init(struct net_device *dev)
1117 {
1118         struct tun_struct *tun = netdev_priv(dev);
1119
1120         switch (tun->flags & TUN_TYPE_MASK) {
1121         case IFF_TUN:
1122                 dev->netdev_ops = &tun_netdev_ops;
1123
1124                 /* Point-to-Point TUN Device */
1125                 dev->hard_header_len = 0;
1126                 dev->addr_len = 0;
1127                 dev->mtu = 1500;
1128
1129                 /* Zero header length */
1130                 dev->type = ARPHRD_NONE;
1131                 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
1132                 break;
1133
1134         case IFF_TAP:
1135                 dev->netdev_ops = &tap_netdev_ops;
1136                 /* Ethernet TAP Device */
1137                 ether_setup(dev);
1138                 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1139                 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
1140
1141                 eth_hw_addr_random(dev);
1142
1143                 break;
1144         }
1145
1146         dev->min_mtu = MIN_MTU;
1147         dev->max_mtu = MAX_MTU - dev->hard_header_len;
1148 }
1149
1150 static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
1151 {
1152         struct sock *sk = tfile->socket.sk;
1153
1154         return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
1155 }
1156
1157 /* Character device part */
1158
1159 /* Poll */
1160 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
1161 {
1162         struct tun_file *tfile = file->private_data;
1163         struct tun_struct *tun = __tun_get(tfile);
1164         struct sock *sk;
1165         unsigned int mask = 0;
1166
1167         if (!tun)
1168                 return POLLERR;
1169
1170         sk = tfile->socket.sk;
1171
1172         tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
1173
1174         poll_wait(file, sk_sleep(sk), wait);
1175
1176         if (!skb_array_empty(&tfile->tx_array))
1177                 mask |= POLLIN | POLLRDNORM;
1178
1179         /* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
1180          * guarantee EPOLLOUT to be raised by either here or
1181          * tun_sock_write_space(). Then process could get notification
1182          * after it writes to a down device and meets -EIO.
1183          */
1184         if (tun_sock_writeable(tun, tfile) ||
1185             (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1186              tun_sock_writeable(tun, tfile)))
1187                 mask |= POLLOUT | POLLWRNORM;
1188
1189         if (tun->dev->reg_state != NETREG_REGISTERED)
1190                 mask = POLLERR;
1191
1192         tun_put(tun);
1193         return mask;
1194 }
1195
1196 /* prepad is the amount to reserve at front.  len is length after that.
1197  * linear is a hint as to how much to copy (usually headers). */
1198 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
1199                                      size_t prepad, size_t len,
1200                                      size_t linear, int noblock)
1201 {
1202         struct sock *sk = tfile->socket.sk;
1203         struct sk_buff *skb;
1204         int err;
1205
1206         /* Under a page?  Don't bother with paged skb. */
1207         if (prepad + len < PAGE_SIZE || !linear)
1208                 linear = len;
1209
1210         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
1211                                    &err, 0);
1212         if (!skb)
1213                 return ERR_PTR(err);
1214
1215         skb_reserve(skb, prepad);
1216         skb_put(skb, linear);
1217         skb->data_len = len - linear;
1218         skb->len += len - linear;
1219
1220         return skb;
1221 }
1222
1223 static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
1224                            struct sk_buff *skb, int more)
1225 {
1226         struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1227         struct sk_buff_head process_queue;
1228         u32 rx_batched = tun->rx_batched;
1229         bool rcv = false;
1230
1231         if (!rx_batched || (!more && skb_queue_empty(queue))) {
1232                 local_bh_disable();
1233                 skb_record_rx_queue(skb, tfile->queue_index);
1234                 netif_receive_skb(skb);
1235                 local_bh_enable();
1236                 return;
1237         }
1238
1239         spin_lock(&queue->lock);
1240         if (!more || skb_queue_len(queue) == rx_batched) {
1241                 __skb_queue_head_init(&process_queue);
1242                 skb_queue_splice_tail_init(queue, &process_queue);
1243                 rcv = true;
1244         } else {
1245                 __skb_queue_tail(queue, skb);
1246         }
1247         spin_unlock(&queue->lock);
1248
1249         if (rcv) {
1250                 struct sk_buff *nskb;
1251
1252                 local_bh_disable();
1253                 while ((nskb = __skb_dequeue(&process_queue))) {
1254                         skb_record_rx_queue(nskb, tfile->queue_index);
1255                         netif_receive_skb(nskb);
1256                 }
1257                 skb_record_rx_queue(skb, tfile->queue_index);
1258                 netif_receive_skb(skb);
1259                 local_bh_enable();
1260         }
1261 }
1262
1263 static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
1264                               int len, int noblock, bool zerocopy)
1265 {
1266         if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
1267                 return false;
1268
1269         if (tfile->socket.sk->sk_sndbuf != INT_MAX)
1270                 return false;
1271
1272         if (!noblock)
1273                 return false;
1274
1275         if (zerocopy)
1276                 return false;
1277
1278         if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
1279             SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
1280                 return false;
1281
1282         return true;
1283 }
1284
1285 static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1286                                      struct tun_file *tfile,
1287                                      struct iov_iter *from,
1288                                      struct virtio_net_hdr *hdr,
1289                                      int len, int *skb_xdp)
1290 {
1291         struct page_frag *alloc_frag = &current->task_frag;
1292         struct sk_buff *skb;
1293         struct bpf_prog *xdp_prog;
1294         int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1295         unsigned int delta = 0;
1296         char *buf;
1297         size_t copied;
1298         bool xdp_xmit = false;
1299         int err, pad = TUN_RX_PAD;
1300
1301         rcu_read_lock();
1302         xdp_prog = rcu_dereference(tun->xdp_prog);
1303         if (xdp_prog)
1304                 pad += TUN_HEADROOM;
1305         buflen += SKB_DATA_ALIGN(len + pad);
1306         rcu_read_unlock();
1307
1308         alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
1309         if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
1310                 return ERR_PTR(-ENOMEM);
1311
1312         buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1313         copied = copy_page_from_iter(alloc_frag->page,
1314                                      alloc_frag->offset + pad,
1315                                      len, from);
1316         if (copied != len)
1317                 return ERR_PTR(-EFAULT);
1318
1319         /* There's a small window that XDP may be set after the check
1320          * of xdp_prog above, this should be rare and for simplicity
1321          * we do XDP on skb in case the headroom is not enough.
1322          */
1323         if (hdr->gso_type || !xdp_prog)
1324                 *skb_xdp = 1;
1325         else
1326                 *skb_xdp = 0;
1327
1328         local_bh_disable();
1329         rcu_read_lock();
1330         xdp_prog = rcu_dereference(tun->xdp_prog);
1331         if (xdp_prog && !*skb_xdp) {
1332                 struct xdp_buff xdp;
1333                 void *orig_data;
1334                 u32 act;
1335
1336                 xdp.data_hard_start = buf;
1337                 xdp.data = buf + pad;
1338                 xdp.data_end = xdp.data + len;
1339                 orig_data = xdp.data;
1340                 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1341
1342                 switch (act) {
1343                 case XDP_REDIRECT:
1344                         get_page(alloc_frag->page);
1345                         alloc_frag->offset += buflen;
1346                         err = xdp_do_redirect(tun->dev, &xdp, xdp_prog);
1347                         xdp_do_flush_map();
1348                         if (err)
1349                                 goto err_redirect;
1350                         rcu_read_unlock();
1351                         local_bh_enable();
1352                         return NULL;
1353                 case XDP_TX:
1354                         xdp_xmit = true;
1355                         /* fall through */
1356                 case XDP_PASS:
1357                         delta = orig_data - xdp.data;
1358                         break;
1359                 default:
1360                         bpf_warn_invalid_xdp_action(act);
1361                         /* fall through */
1362                 case XDP_ABORTED:
1363                         trace_xdp_exception(tun->dev, xdp_prog, act);
1364                         /* fall through */
1365                 case XDP_DROP:
1366                         goto err_xdp;
1367                 }
1368         }
1369
1370         skb = build_skb(buf, buflen);
1371         if (!skb) {
1372                 rcu_read_unlock();
1373                 local_bh_enable();
1374                 return ERR_PTR(-ENOMEM);
1375         }
1376
1377         skb_reserve(skb, pad - delta);
1378         skb_put(skb, len + delta);
1379         skb_set_owner_w(skb, tfile->socket.sk);
1380         get_page(alloc_frag->page);
1381         alloc_frag->offset += buflen;
1382
1383         if (xdp_xmit) {
1384                 skb->dev = tun->dev;
1385                 generic_xdp_tx(skb, xdp_prog);
1386                 rcu_read_unlock();
1387                 local_bh_enable();
1388                 return NULL;
1389         }
1390
1391         rcu_read_unlock();
1392         local_bh_enable();
1393
1394         return skb;
1395
1396 err_redirect:
1397         put_page(alloc_frag->page);
1398 err_xdp:
1399         rcu_read_unlock();
1400         local_bh_enable();
1401         this_cpu_inc(tun->pcpu_stats->rx_dropped);
1402         return NULL;
1403 }
1404
1405 /* Get packet from user space buffer */
1406 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1407                             void *msg_control, struct iov_iter *from,
1408                             int noblock, bool more)
1409 {
1410         struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1411         struct sk_buff *skb;
1412         size_t total_len = iov_iter_count(from);
1413         size_t len = total_len, align = tun->align, linear;
1414         struct virtio_net_hdr gso = { 0 };
1415         struct tun_pcpu_stats *stats;
1416         int good_linear;
1417         int copylen;
1418         bool zerocopy = false;
1419         int err;
1420         u32 rxhash;
1421         int skb_xdp = 1;
1422
1423         if (!(tun->flags & IFF_NO_PI)) {
1424                 if (len < sizeof(pi))
1425                         return -EINVAL;
1426                 len -= sizeof(pi);
1427
1428                 if (!copy_from_iter_full(&pi, sizeof(pi), from))
1429                         return -EFAULT;
1430         }
1431
1432         if (tun->flags & IFF_VNET_HDR) {
1433                 int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1434
1435                 if (len < vnet_hdr_sz)
1436                         return -EINVAL;
1437                 len -= vnet_hdr_sz;
1438
1439                 if (!copy_from_iter_full(&gso, sizeof(gso), from))
1440                         return -EFAULT;
1441
1442                 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1443                     tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
1444                         gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
1445
1446                 if (tun16_to_cpu(tun, gso.hdr_len) > len)
1447                         return -EINVAL;
1448                 iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1449         }
1450
1451         if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1452                 align += NET_IP_ALIGN;
1453                 if (unlikely(len < ETH_HLEN ||
1454                              (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1455                         return -EINVAL;
1456         }
1457
1458         good_linear = SKB_MAX_HEAD(align);
1459
1460         if (msg_control) {
1461                 struct iov_iter i = *from;
1462
1463                 /* There are 256 bytes to be copied in skb, so there is
1464                  * enough room for skb expand head in case it is used.
1465                  * The rest of the buffer is mapped from userspace.
1466                  */
1467                 copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
1468                 if (copylen > good_linear)
1469                         copylen = good_linear;
1470                 linear = copylen;
1471                 iov_iter_advance(&i, copylen);
1472                 if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
1473                         zerocopy = true;
1474         }
1475
1476         if (tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
1477                 /* For the packet that is not easy to be processed
1478                  * (e.g gso or jumbo packet), we will do it at after
1479                  * skb was created with generic XDP routine.
1480                  */
1481                 skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
1482                 if (IS_ERR(skb)) {
1483                         this_cpu_inc(tun->pcpu_stats->rx_dropped);
1484                         return PTR_ERR(skb);
1485                 }
1486                 if (!skb)
1487                         return total_len;
1488         } else {
1489                 if (!zerocopy) {
1490                         copylen = len;
1491                         if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
1492                                 linear = good_linear;
1493                         else
1494                                 linear = tun16_to_cpu(tun, gso.hdr_len);
1495                 }
1496
1497                 skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
1498                 if (IS_ERR(skb)) {
1499                         if (PTR_ERR(skb) != -EAGAIN)
1500                                 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1501                         return PTR_ERR(skb);
1502                 }
1503
1504                 if (zerocopy)
1505                         err = zerocopy_sg_from_iter(skb, from);
1506                 else
1507                         err = skb_copy_datagram_from_iter(skb, 0, from, len);
1508
1509                 if (err) {
1510                         err = -EFAULT;
1511 drop:
1512                         this_cpu_inc(tun->pcpu_stats->rx_dropped);
1513                         kfree_skb(skb);
1514                         return err;
1515                 }
1516         }
1517
1518         if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1519                 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1520                 kfree_skb(skb);
1521                 return -EINVAL;
1522         }
1523
1524         switch (tun->flags & TUN_TYPE_MASK) {
1525         case IFF_TUN:
1526                 if (tun->flags & IFF_NO_PI) {
1527                         u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
1528
1529                         switch (ip_version) {
1530                         case 4:
1531                                 pi.proto = htons(ETH_P_IP);
1532                                 break;
1533                         case 6:
1534                                 pi.proto = htons(ETH_P_IPV6);
1535                                 break;
1536                         default:
1537                                 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1538                                 kfree_skb(skb);
1539                                 return -EINVAL;
1540                         }
1541                 }
1542
1543                 skb_reset_mac_header(skb);
1544                 skb->protocol = pi.proto;
1545                 skb->dev = tun->dev;
1546                 break;
1547         case IFF_TAP:
1548                 skb->protocol = eth_type_trans(skb, tun->dev);
1549                 break;
1550         }
1551
1552         /* copy skb_ubuf_info for callback when skb has no error */
1553         if (zerocopy) {
1554                 skb_shinfo(skb)->destructor_arg = msg_control;
1555                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1556                 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1557         } else if (msg_control) {
1558                 struct ubuf_info *uarg = msg_control;
1559                 uarg->callback(uarg, false);
1560         }
1561
1562         skb_reset_network_header(skb);
1563         skb_probe_transport_header(skb, 0);
1564
1565         if (skb_xdp) {
1566                 struct bpf_prog *xdp_prog;
1567                 int ret;
1568
1569                 local_bh_disable();
1570                 rcu_read_lock();
1571                 xdp_prog = rcu_dereference(tun->xdp_prog);
1572                 if (xdp_prog) {
1573                         ret = do_xdp_generic(xdp_prog, skb);
1574                         if (ret != XDP_PASS) {
1575                                 rcu_read_unlock();
1576                                 local_bh_enable();
1577                                 return total_len;
1578                         }
1579                 }
1580                 rcu_read_unlock();
1581                 local_bh_enable();
1582         }
1583
1584         rxhash = __skb_get_hash_symmetric(skb);
1585
1586         rcu_read_lock();
1587         if (unlikely(!(tun->dev->flags & IFF_UP))) {
1588                 err = -EIO;
1589                 rcu_read_unlock();
1590                 goto drop;
1591         }
1592
1593 #ifndef CONFIG_4KSTACKS
1594         tun_rx_batched(tun, tfile, skb, more);
1595 #else
1596         netif_rx_ni(skb);
1597 #endif
1598         rcu_read_unlock();
1599
1600         stats = get_cpu_ptr(tun->pcpu_stats);
1601         u64_stats_update_begin(&stats->syncp);
1602         stats->rx_packets++;
1603         stats->rx_bytes += len;
1604         u64_stats_update_end(&stats->syncp);
1605         put_cpu_ptr(stats);
1606
1607         tun_flow_update(tun, rxhash, tfile);
1608         return total_len;
1609 }
1610
1611 static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
1612 {
1613         struct file *file = iocb->ki_filp;
1614         struct tun_struct *tun = tun_get(file);
1615         struct tun_file *tfile = file->private_data;
1616         ssize_t result;
1617         int noblock = 0;
1618
1619         if (!tun)
1620                 return -EBADFD;
1621
1622         if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
1623                 noblock = 1;
1624
1625         result = tun_get_user(tun, tfile, NULL, from, noblock, false);
1626
1627         tun_put(tun);
1628         return result;
1629 }
1630
1631 /* Put packet to the user space buffer */
1632 static ssize_t tun_put_user(struct tun_struct *tun,
1633                             struct tun_file *tfile,
1634                             struct sk_buff *skb,
1635                             struct iov_iter *iter)
1636 {
1637         struct tun_pi pi = { 0, skb->protocol };
1638         struct tun_pcpu_stats *stats;
1639         ssize_t total;
1640         int vlan_offset = 0;
1641         int vlan_hlen = 0;
1642         int vnet_hdr_sz = 0;
1643
1644         if (skb_vlan_tag_present(skb))
1645                 vlan_hlen = VLAN_HLEN;
1646
1647         if (tun->flags & IFF_VNET_HDR)
1648                 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1649
1650         total = skb->len + vlan_hlen + vnet_hdr_sz;
1651
1652         if (!(tun->flags & IFF_NO_PI)) {
1653                 if (iov_iter_count(iter) < sizeof(pi))
1654                         return -EINVAL;
1655
1656                 total += sizeof(pi);
1657                 if (iov_iter_count(iter) < total) {
1658                         /* Packet will be striped */
1659                         pi.flags |= TUN_PKT_STRIP;
1660                 }
1661
1662                 if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
1663                         return -EFAULT;
1664         }
1665
1666         if (vnet_hdr_sz) {
1667                 struct virtio_net_hdr gso;
1668
1669                 if (iov_iter_count(iter) < vnet_hdr_sz)
1670                         return -EINVAL;
1671
1672                 if (virtio_net_hdr_from_skb(skb, &gso,
1673                                             tun_is_little_endian(tun), true,
1674                                             vlan_hlen)) {
1675                         struct skb_shared_info *sinfo = skb_shinfo(skb);
1676                         pr_err("unexpected GSO type: "
1677                                "0x%x, gso_size %d, hdr_len %d\n",
1678                                sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
1679                                tun16_to_cpu(tun, gso.hdr_len));
1680                         print_hex_dump(KERN_ERR, "tun: ",
1681                                        DUMP_PREFIX_NONE,
1682                                        16, 1, skb->head,
1683                                        min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
1684                         WARN_ON_ONCE(1);
1685                         return -EINVAL;
1686                 }
1687
1688                 if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
1689                         return -EFAULT;
1690
1691                 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
1692         }
1693
1694         if (vlan_hlen) {
1695                 int ret;
1696                 struct {
1697                         __be16 h_vlan_proto;
1698                         __be16 h_vlan_TCI;
1699                 } veth;
1700
1701                 veth.h_vlan_proto = skb->vlan_proto;
1702                 veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
1703
1704                 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
1705
1706                 ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
1707                 if (ret || !iov_iter_count(iter))
1708                         goto done;
1709
1710                 ret = copy_to_iter(&veth, sizeof(veth), iter);
1711                 if (ret != sizeof(veth) || !iov_iter_count(iter))
1712                         goto done;
1713         }
1714
1715         skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
1716
1717 done:
1718         /* caller is in process context, */
1719         stats = get_cpu_ptr(tun->pcpu_stats);
1720         u64_stats_update_begin(&stats->syncp);
1721         stats->tx_packets++;
1722         stats->tx_bytes += skb->len + vlan_hlen;
1723         u64_stats_update_end(&stats->syncp);
1724         put_cpu_ptr(tun->pcpu_stats);
1725
1726         return total;
1727 }
1728
1729 static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock,
1730                                      int *err)
1731 {
1732         DECLARE_WAITQUEUE(wait, current);
1733         struct sk_buff *skb = NULL;
1734         int error = 0;
1735
1736         skb = skb_array_consume(&tfile->tx_array);
1737         if (skb)
1738                 goto out;
1739         if (noblock) {
1740                 error = -EAGAIN;
1741                 goto out;
1742         }
1743
1744         add_wait_queue(&tfile->wq.wait, &wait);
1745
1746         while (1) {
1747                 set_current_state(TASK_INTERRUPTIBLE);
1748                 skb = skb_array_consume(&tfile->tx_array);
1749                 if (skb)
1750                         break;
1751                 if (signal_pending(current)) {
1752                         error = -ERESTARTSYS;
1753                         break;
1754                 }
1755                 if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
1756                         error = -EFAULT;
1757                         break;
1758                 }
1759
1760                 schedule();
1761         }
1762
1763         __set_current_state(TASK_RUNNING);
1764         remove_wait_queue(&tfile->wq.wait, &wait);
1765
1766 out:
1767         *err = error;
1768         return skb;
1769 }
1770
1771 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1772                            struct iov_iter *to,
1773                            int noblock, struct sk_buff *skb)
1774 {
1775         ssize_t ret;
1776         int err;
1777
1778         tun_debug(KERN_INFO, tun, "tun_do_read\n");
1779
1780         if (!iov_iter_count(to)) {
1781                 if (skb)
1782                         kfree_skb(skb);
1783                 return 0;
1784         }
1785
1786         if (!skb) {
1787                 /* Read frames from ring */
1788                 skb = tun_ring_recv(tfile, noblock, &err);
1789                 if (!skb)
1790                         return err;
1791         }
1792
1793         ret = tun_put_user(tun, tfile, skb, to);
1794         if (unlikely(ret < 0))
1795                 kfree_skb(skb);
1796         else
1797                 consume_skb(skb);
1798
1799         return ret;
1800 }
1801
1802 static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
1803 {
1804         struct file *file = iocb->ki_filp;
1805         struct tun_file *tfile = file->private_data;
1806         struct tun_struct *tun = __tun_get(tfile);
1807         ssize_t len = iov_iter_count(to), ret;
1808         int noblock = 0;
1809
1810         if (!tun)
1811                 return -EBADFD;
1812
1813         if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
1814                 noblock = 1;
1815
1816         ret = tun_do_read(tun, tfile, to, noblock, NULL);
1817         ret = min_t(ssize_t, ret, len);
1818         if (ret > 0)
1819                 iocb->ki_pos = ret;
1820         tun_put(tun);
1821         return ret;
1822 }
1823
1824 static void tun_free_netdev(struct net_device *dev)
1825 {
1826         struct tun_struct *tun = netdev_priv(dev);
1827
1828         BUG_ON(!(list_empty(&tun->disabled)));
1829         free_percpu(tun->pcpu_stats);
1830         tun_flow_uninit(tun);
1831         security_tun_dev_free_security(tun->security);
1832 }
1833
1834 static void tun_setup(struct net_device *dev)
1835 {
1836         struct tun_struct *tun = netdev_priv(dev);
1837
1838         tun->owner = INVALID_UID;
1839         tun->group = INVALID_GID;
1840
1841         dev->ethtool_ops = &tun_ethtool_ops;
1842         dev->needs_free_netdev = true;
1843         dev->priv_destructor = tun_free_netdev;
1844         /* We prefer our own queue length */
1845         dev->tx_queue_len = TUN_READQ_SIZE;
1846 }
1847
1848 /* Trivial set of netlink ops to allow deleting tun or tap
1849  * device with netlink.
1850  */
1851 static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
1852                         struct netlink_ext_ack *extack)
1853 {
1854         NL_SET_ERR_MSG(extack,
1855                        "tun/tap creation via rtnetlink is not supported.");
1856         return -EOPNOTSUPP;
1857 }
1858
1859 static struct rtnl_link_ops tun_link_ops __read_mostly = {
1860         .kind           = DRV_NAME,
1861         .priv_size      = sizeof(struct tun_struct),
1862         .setup          = tun_setup,
1863         .validate       = tun_validate,
1864 };
1865
1866 static void tun_sock_write_space(struct sock *sk)
1867 {
1868         struct tun_file *tfile;
1869         wait_queue_head_t *wqueue;
1870
1871         if (!sock_writeable(sk))
1872                 return;
1873
1874         if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
1875                 return;
1876
1877         wqueue = sk_sleep(sk);
1878         if (wqueue && waitqueue_active(wqueue))
1879                 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1880                                                 POLLWRNORM | POLLWRBAND);
1881
1882         tfile = container_of(sk, struct tun_file, sk);
1883         kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1884 }
1885
1886 static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
1887 {
1888         int ret;
1889         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1890         struct tun_struct *tun = __tun_get(tfile);
1891
1892         if (!tun)
1893                 return -EBADFD;
1894
1895         ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
1896                            m->msg_flags & MSG_DONTWAIT,
1897                            m->msg_flags & MSG_MORE);
1898         tun_put(tun);
1899         return ret;
1900 }
1901
1902 static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
1903                        int flags)
1904 {
1905         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1906         struct tun_struct *tun = __tun_get(tfile);
1907         struct sk_buff *skb = m->msg_control;
1908         int ret;
1909
1910         if (!tun) {
1911                 ret = -EBADFD;
1912                 goto out_free_skb;
1913         }
1914
1915         if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
1916                 ret = -EINVAL;
1917                 goto out_put_tun;
1918         }
1919         if (flags & MSG_ERRQUEUE) {
1920                 ret = sock_recv_errqueue(sock->sk, m, total_len,
1921                                          SOL_PACKET, TUN_TX_TIMESTAMP);
1922                 goto out;
1923         }
1924         ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, skb);
1925         if (ret > (ssize_t)total_len) {
1926                 m->msg_flags |= MSG_TRUNC;
1927                 ret = flags & MSG_TRUNC ? ret : total_len;
1928         }
1929 out:
1930         tun_put(tun);
1931         return ret;
1932
1933 out_put_tun:
1934         tun_put(tun);
1935 out_free_skb:
1936         if (skb)
1937                 kfree_skb(skb);
1938         return ret;
1939 }
1940
1941 static int tun_peek_len(struct socket *sock)
1942 {
1943         struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1944         struct tun_struct *tun;
1945         int ret = 0;
1946
1947         tun = __tun_get(tfile);
1948         if (!tun)
1949                 return 0;
1950
1951         ret = skb_array_peek_len(&tfile->tx_array);
1952         tun_put(tun);
1953
1954         return ret;
1955 }
1956
1957 /* Ops structure to mimic raw sockets with tun */
1958 static const struct proto_ops tun_socket_ops = {
1959         .peek_len = tun_peek_len,
1960         .sendmsg = tun_sendmsg,
1961         .recvmsg = tun_recvmsg,
1962 };
1963
1964 static struct proto tun_proto = {
1965         .name           = "tun",
1966         .owner          = THIS_MODULE,
1967         .obj_size       = sizeof(struct tun_file),
1968 };
1969
1970 static int tun_flags(struct tun_struct *tun)
1971 {
1972         return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
1973 }
1974
1975 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1976                               char *buf)
1977 {
1978         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1979         return sprintf(buf, "0x%x\n", tun_flags(tun));
1980 }
1981
1982 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1983                               char *buf)
1984 {
1985         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1986         return uid_valid(tun->owner)?
1987                 sprintf(buf, "%u\n",
1988                         from_kuid_munged(current_user_ns(), tun->owner)):
1989                 sprintf(buf, "-1\n");
1990 }
1991
1992 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1993                               char *buf)
1994 {
1995         struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1996         return gid_valid(tun->group) ?
1997                 sprintf(buf, "%u\n",
1998                         from_kgid_munged(current_user_ns(), tun->group)):
1999                 sprintf(buf, "-1\n");
2000 }
2001
2002 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2003 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2004 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2005
2006 static struct attribute *tun_dev_attrs[] = {
2007         &dev_attr_tun_flags.attr,
2008         &dev_attr_owner.attr,
2009         &dev_attr_group.attr,
2010         NULL
2011 };
2012
2013 static const struct attribute_group tun_attr_group = {
2014         .attrs = tun_dev_attrs
2015 };
2016
2017 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
2018 {
2019         struct tun_struct *tun;
2020         struct tun_file *tfile = file->private_data;
2021         struct net_device *dev;
2022         int err;
2023
2024         if (tfile->detached)
2025                 return -EINVAL;
2026
2027         dev = __dev_get_by_name(net, ifr->ifr_name);
2028         if (dev) {
2029                 if (ifr->ifr_flags & IFF_TUN_EXCL)
2030                         return -EBUSY;
2031                 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
2032                         tun = netdev_priv(dev);
2033                 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
2034                         tun = netdev_priv(dev);
2035                 else
2036                         return -EINVAL;
2037
2038                 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
2039                     !!(tun->flags & IFF_MULTI_QUEUE))
2040                         return -EINVAL;
2041
2042                 if (tun_not_capable(tun))
2043                         return -EPERM;
2044                 err = security_tun_dev_open(tun->security);
2045                 if (err < 0)
2046                         return err;
2047
2048                 err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER, true);
2049                 if (err < 0)
2050                         return err;
2051
2052                 if (tun->flags & IFF_MULTI_QUEUE &&
2053                     (tun->numqueues + tun->numdisabled > 1)) {
2054                         /* One or more queue has already been attached, no need
2055                          * to initialize the device again.
2056                          */
2057                         return 0;
2058                 }
2059         }
2060         else {
2061                 char *name;
2062                 unsigned long flags = 0;
2063                 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2064                              MAX_TAP_QUEUES : 1;
2065
2066                 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2067                         return -EPERM;
2068                 err = security_tun_dev_create();
2069                 if (err < 0)
2070                         return err;
2071
2072                 /* Set dev type */
2073                 if (ifr->ifr_flags & IFF_TUN) {
2074                         /* TUN device */
2075                         flags |= IFF_TUN;
2076                         name = "tun%d";
2077                 } else if (ifr->ifr_flags & IFF_TAP) {
2078                         /* TAP device */
2079                         flags |= IFF_TAP;
2080                         name = "tap%d";
2081                 } else
2082                         return -EINVAL;
2083
2084                 if (*ifr->ifr_name)
2085                         name = ifr->ifr_name;
2086
2087                 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2088                                        NET_NAME_UNKNOWN, tun_setup, queues,
2089                                        queues);
2090
2091                 if (!dev)
2092                         return -ENOMEM;
2093                 err = dev_get_valid_name(net, dev, name);
2094                 if (err < 0)
2095                         goto err_free_dev;
2096
2097                 dev_net_set(dev, net);
2098                 dev->rtnl_link_ops = &tun_link_ops;
2099                 dev->ifindex = tfile->ifindex;
2100                 dev->sysfs_groups[0] = &tun_attr_group;
2101
2102                 tun = netdev_priv(dev);
2103                 tun->dev = dev;
2104                 tun->flags = flags;
2105                 tun->txflt.count = 0;
2106                 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
2107
2108                 tun->align = NET_SKB_PAD;
2109                 tun->filter_attached = false;
2110                 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
2111                 tun->rx_batched = 0;
2112
2113                 tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2114                 if (!tun->pcpu_stats) {
2115                         err = -ENOMEM;
2116                         goto err_free_dev;
2117                 }
2118
2119                 spin_lock_init(&tun->lock);
2120
2121                 err = security_tun_dev_alloc_security(&tun->security);
2122                 if (err < 0)
2123                         goto err_free_stat;
2124
2125                 tun_net_init(dev);
2126                 tun_flow_init(tun);
2127
2128                 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
2129                                    TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
2130                                    NETIF_F_HW_VLAN_STAG_TX;
2131                 dev->features = dev->hw_features | NETIF_F_LLTX;
2132                 dev->vlan_features = dev->features &
2133                                      ~(NETIF_F_HW_VLAN_CTAG_TX |
2134                                        NETIF_F_HW_VLAN_STAG_TX);
2135
2136                 INIT_LIST_HEAD(&tun->disabled);
2137                 err = tun_attach(tun, file, false, false);
2138                 if (err < 0)
2139                         goto err_free_flow;
2140
2141                 err = register_netdevice(tun->dev);
2142                 if (err < 0)
2143                         goto err_detach;
2144                 /* free_netdev() won't check refcnt, to aovid race
2145                  * with dev_put() we need publish tun after registration.
2146                  */
2147                 rcu_assign_pointer(tfile->tun, tun);
2148         }
2149
2150         netif_carrier_on(tun->dev);
2151
2152         tun_debug(KERN_INFO, tun, "tun_set_iff\n");
2153
2154         tun->flags = (tun->flags & ~TUN_FEATURES) |
2155                 (ifr->ifr_flags & TUN_FEATURES);
2156
2157         /* Make sure persistent devices do not get stuck in
2158          * xoff state.
2159          */
2160         if (netif_running(tun->dev))
2161                 netif_tx_wake_all_queues(tun->dev);
2162
2163         strcpy(ifr->ifr_name, tun->dev->name);
2164         return 0;
2165
2166 err_detach:
2167         tun_detach_all(dev);
2168         /* register_netdevice() already called tun_free_netdev() */
2169         goto err_free_dev;
2170
2171 err_free_flow:
2172         tun_flow_uninit(tun);
2173         security_tun_dev_free_security(tun->security);
2174 err_free_stat:
2175         free_percpu(tun->pcpu_stats);
2176 err_free_dev:
2177         free_netdev(dev);
2178         return err;
2179 }
2180
2181 static void tun_get_iff(struct net *net, struct tun_struct *tun,
2182                        struct ifreq *ifr)
2183 {
2184         tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2185
2186         strcpy(ifr->ifr_name, tun->dev->name);
2187
2188         ifr->ifr_flags = tun_flags(tun);
2189
2190 }
2191
2192 /* This is like a cut-down ethtool ops, except done via tun fd so no
2193  * privs required. */
2194 static int set_offload(struct tun_struct *tun, unsigned long arg)
2195 {
2196         netdev_features_t features = 0;
2197
2198         if (arg & TUN_F_CSUM) {
2199                 features |= NETIF_F_HW_CSUM;
2200                 arg &= ~TUN_F_CSUM;
2201
2202                 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
2203                         if (arg & TUN_F_TSO_ECN) {
2204                                 features |= NETIF_F_TSO_ECN;
2205                                 arg &= ~TUN_F_TSO_ECN;
2206                         }
2207                         if (arg & TUN_F_TSO4)
2208                                 features |= NETIF_F_TSO;
2209                         if (arg & TUN_F_TSO6)
2210                                 features |= NETIF_F_TSO6;
2211                         arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
2212                 }
2213
2214                 arg &= ~TUN_F_UFO;
2215         }
2216
2217         /* This gives the user a way to test for new features in future by
2218          * trying to set them. */
2219         if (arg)
2220                 return -EINVAL;
2221
2222         tun->set_features = features;
2223         tun->dev->wanted_features &= ~TUN_USER_FEATURES;
2224         tun->dev->wanted_features |= features;
2225         netdev_update_features(tun->dev);
2226
2227         return 0;
2228 }
2229
2230 static void tun_detach_filter(struct tun_struct *tun, int n)
2231 {
2232         int i;
2233         struct tun_file *tfile;
2234
2235         for (i = 0; i < n; i++) {
2236                 tfile = rtnl_dereference(tun->tfiles[i]);
2237                 lock_sock(tfile->socket.sk);
2238                 sk_detach_filter(tfile->socket.sk);
2239                 release_sock(tfile->socket.sk);
2240         }
2241
2242         tun->filter_attached = false;
2243 }
2244
2245 static int tun_attach_filter(struct tun_struct *tun)
2246 {
2247         int i, ret = 0;
2248         struct tun_file *tfile;
2249
2250         for (i = 0; i < tun->numqueues; i++) {
2251                 tfile = rtnl_dereference(tun->tfiles[i]);
2252                 lock_sock(tfile->socket.sk);
2253                 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
2254                 release_sock(tfile->socket.sk);
2255                 if (ret) {
2256                         tun_detach_filter(tun, i);
2257                         return ret;
2258                 }
2259         }
2260
2261         tun->filter_attached = true;
2262         return ret;
2263 }
2264
2265 static void tun_set_sndbuf(struct tun_struct *tun)
2266 {
2267         struct tun_file *tfile;
2268         int i;
2269
2270         for (i = 0; i < tun->numqueues; i++) {
2271                 tfile = rtnl_dereference(tun->tfiles[i]);
2272                 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2273         }
2274 }
2275
2276 static int tun_set_queue(struct file *file, struct ifreq *ifr)
2277 {
2278         struct tun_file *tfile = file->private_data;
2279         struct tun_struct *tun;
2280         int ret = 0;
2281
2282         rtnl_lock();
2283
2284         if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
2285                 tun = tfile->detached;
2286                 if (!tun) {
2287                         ret = -EINVAL;
2288                         goto unlock;
2289                 }
2290                 ret = security_tun_dev_attach_queue(tun->security);
2291                 if (ret < 0)
2292                         goto unlock;
2293                 ret = tun_attach(tun, file, false, true);
2294         } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2295                 tun = rtnl_dereference(tfile->tun);
2296                 if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
2297                         ret = -EINVAL;
2298                 else
2299                         __tun_detach(tfile, false);
2300         } else
2301                 ret = -EINVAL;
2302
2303 unlock:
2304         rtnl_unlock();
2305         return ret;
2306 }
2307
2308 /* Return correct value for tun->dev->addr_len based on tun->dev->type. */
2309 static unsigned char tun_get_addr_len(unsigned short type)
2310 {
2311         switch (type) {
2312         case ARPHRD_IP6GRE:
2313         case ARPHRD_TUNNEL6:
2314                 return sizeof(struct in6_addr);
2315         case ARPHRD_IPGRE:
2316         case ARPHRD_TUNNEL:
2317         case ARPHRD_SIT:
2318                 return 4;
2319         case ARPHRD_ETHER:
2320                 return ETH_ALEN;
2321         case ARPHRD_IEEE802154:
2322         case ARPHRD_IEEE802154_MONITOR:
2323                 return IEEE802154_EXTENDED_ADDR_LEN;
2324         case ARPHRD_PHONET_PIPE:
2325         case ARPHRD_PPP:
2326         case ARPHRD_NONE:
2327                 return 0;
2328         case ARPHRD_6LOWPAN:
2329                 return EUI64_ADDR_LEN;
2330         case ARPHRD_FDDI:
2331                 return FDDI_K_ALEN;
2332         case ARPHRD_HIPPI:
2333                 return HIPPI_ALEN;
2334         case ARPHRD_IEEE802:
2335                 return FC_ALEN;
2336         case ARPHRD_ROSE:
2337                 return ROSE_ADDR_LEN;
2338         case ARPHRD_NETROM:
2339                 return AX25_ADDR_LEN;
2340         case ARPHRD_LOCALTLK:
2341                 return LTALK_ALEN;
2342         default:
2343                 return 0;
2344         }
2345 }
2346
2347 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
2348                             unsigned long arg, int ifreq_len)
2349 {
2350         struct tun_file *tfile = file->private_data;
2351         struct tun_struct *tun;
2352         void __user* argp = (void __user*)arg;
2353         struct ifreq ifr;
2354         kuid_t owner;
2355         kgid_t group;
2356         int sndbuf;
2357         int vnet_hdr_sz;
2358         unsigned int ifindex;
2359         int le;
2360         int ret;
2361
2362         if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) {
2363                 if (copy_from_user(&ifr, argp, ifreq_len))
2364                         return -EFAULT;
2365         } else {
2366                 memset(&ifr, 0, sizeof(ifr));
2367         }
2368         if (cmd == TUNGETFEATURES) {
2369                 /* Currently this just means: "what IFF flags are valid?".
2370                  * This is needed because we never checked for invalid flags on
2371                  * TUNSETIFF.
2372                  */
2373                 return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
2374                                 (unsigned int __user*)argp);
2375         } else if (cmd == TUNSETQUEUE)
2376                 return tun_set_queue(file, &ifr);
2377
2378         ret = 0;
2379         rtnl_lock();
2380
2381         tun = __tun_get(tfile);
2382         if (cmd == TUNSETIFF) {
2383                 ret = -EEXIST;
2384                 if (tun)
2385                         goto unlock;
2386
2387                 ifr.ifr_name[IFNAMSIZ-1] = '\0';
2388
2389                 ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr);
2390
2391                 if (ret)
2392                         goto unlock;
2393
2394                 if (copy_to_user(argp, &ifr, ifreq_len))
2395                         ret = -EFAULT;
2396                 goto unlock;
2397         }
2398         if (cmd == TUNSETIFINDEX) {
2399                 ret = -EPERM;
2400                 if (tun)
2401                         goto unlock;
2402
2403                 ret = -EFAULT;
2404                 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
2405                         goto unlock;
2406
2407                 ret = 0;
2408                 tfile->ifindex = ifindex;
2409                 goto unlock;
2410         }
2411
2412         ret = -EBADFD;
2413         if (!tun)
2414                 goto unlock;
2415
2416         tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
2417
2418         ret = 0;
2419         switch (cmd) {
2420         case TUNGETIFF:
2421                 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2422
2423                 if (tfile->detached)
2424                         ifr.ifr_flags |= IFF_DETACH_QUEUE;
2425                 if (!tfile->socket.sk->sk_filter)
2426                         ifr.ifr_flags |= IFF_NOFILTER;
2427
2428                 if (copy_to_user(argp, &ifr, ifreq_len))
2429                         ret = -EFAULT;
2430                 break;
2431
2432         case TUNSETNOCSUM:
2433                 /* Disable/Enable checksum */
2434
2435                 /* [unimplemented] */
2436                 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
2437                           arg ? "disabled" : "enabled");
2438                 break;
2439
2440         case TUNSETPERSIST:
2441                 /* Disable/Enable persist mode. Keep an extra reference to the
2442                  * module to prevent the module being unprobed.
2443                  */
2444                 if (arg && !(tun->flags & IFF_PERSIST)) {
2445                         tun->flags |= IFF_PERSIST;
2446                         __module_get(THIS_MODULE);
2447                 }
2448                 if (!arg && (tun->flags & IFF_PERSIST)) {
2449                         tun->flags &= ~IFF_PERSIST;
2450                         module_put(THIS_MODULE);
2451                 }
2452
2453                 tun_debug(KERN_INFO, tun, "persist %s\n",
2454                           arg ? "enabled" : "disabled");
2455                 break;
2456
2457         case TUNSETOWNER:
2458                 /* Set owner of the device */
2459                 owner = make_kuid(current_user_ns(), arg);
2460                 if (!uid_valid(owner)) {
2461                         ret = -EINVAL;
2462                         break;
2463                 }
2464                 tun->owner = owner;
2465                 tun_debug(KERN_INFO, tun, "owner set to %u\n",
2466                           from_kuid(&init_user_ns, tun->owner));
2467                 break;
2468
2469         case TUNSETGROUP:
2470                 /* Set group of the device */
2471                 group = make_kgid(current_user_ns(), arg);
2472                 if (!gid_valid(group)) {
2473                         ret = -EINVAL;
2474                         break;
2475                 }
2476                 tun->group = group;
2477                 tun_debug(KERN_INFO, tun, "group set to %u\n",
2478                           from_kgid(&init_user_ns, tun->group));
2479                 break;
2480
2481         case TUNSETLINK:
2482                 /* Only allow setting the type when the interface is down */
2483                 if (tun->dev->flags & IFF_UP) {
2484                         tun_debug(KERN_INFO, tun,
2485                                   "Linktype set failed because interface is up\n");
2486                         ret = -EBUSY;
2487                 } else {
2488                         tun->dev->type = (int) arg;
2489                         tun->dev->addr_len = tun_get_addr_len(tun->dev->type);
2490                         tun_debug(KERN_INFO, tun, "linktype set to %d\n",
2491                                   tun->dev->type);
2492                         ret = 0;
2493                 }
2494                 break;
2495
2496 #ifdef TUN_DEBUG
2497         case TUNSETDEBUG:
2498                 tun->debug = arg;
2499                 break;
2500 #endif
2501         case TUNSETOFFLOAD:
2502                 ret = set_offload(tun, arg);
2503                 break;
2504
2505         case TUNSETTXFILTER:
2506                 /* Can be set only for TAPs */
2507                 ret = -EINVAL;
2508                 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2509                         break;
2510                 ret = update_filter(&tun->txflt, (void __user *)arg);
2511                 break;
2512
2513         case SIOCGIFHWADDR:
2514                 /* Get hw address */
2515                 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2516                 ifr.ifr_hwaddr.sa_family = tun->dev->type;
2517                 if (copy_to_user(argp, &ifr, ifreq_len))
2518                         ret = -EFAULT;
2519                 break;
2520
2521         case SIOCSIFHWADDR:
2522                 /* Set hw address */
2523                 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
2524                           ifr.ifr_hwaddr.sa_data);
2525
2526                 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2527                 break;
2528
2529         case TUNGETSNDBUF:
2530                 sndbuf = tfile->socket.sk->sk_sndbuf;
2531                 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
2532                         ret = -EFAULT;
2533                 break;
2534
2535         case TUNSETSNDBUF:
2536                 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
2537                         ret = -EFAULT;
2538                         break;
2539                 }
2540                 if (sndbuf <= 0) {
2541                         ret = -EINVAL;
2542                         break;
2543                 }
2544
2545                 tun->sndbuf = sndbuf;
2546                 tun_set_sndbuf(tun);
2547                 break;
2548
2549         case TUNGETVNETHDRSZ:
2550                 vnet_hdr_sz = tun->vnet_hdr_sz;
2551                 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2552                         ret = -EFAULT;
2553                 break;
2554
2555         case TUNSETVNETHDRSZ:
2556                 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2557                         ret = -EFAULT;
2558                         break;
2559                 }
2560                 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2561                         ret = -EINVAL;
2562                         break;
2563                 }
2564
2565                 tun->vnet_hdr_sz = vnet_hdr_sz;
2566                 break;
2567
2568         case TUNGETVNETLE:
2569                 le = !!(tun->flags & TUN_VNET_LE);
2570                 if (put_user(le, (int __user *)argp))
2571                         ret = -EFAULT;
2572                 break;
2573
2574         case TUNSETVNETLE:
2575                 if (get_user(le, (int __user *)argp)) {
2576                         ret = -EFAULT;
2577                         break;
2578                 }
2579                 if (le)
2580                         tun->flags |= TUN_VNET_LE;
2581                 else
2582                         tun->flags &= ~TUN_VNET_LE;
2583                 break;
2584
2585         case TUNGETVNETBE:
2586                 ret = tun_get_vnet_be(tun, argp);
2587                 break;
2588
2589         case TUNSETVNETBE:
2590                 ret = tun_set_vnet_be(tun, argp);
2591                 break;
2592
2593         case TUNATTACHFILTER:
2594                 /* Can be set only for TAPs */
2595                 ret = -EINVAL;
2596                 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2597                         break;
2598                 ret = -EFAULT;
2599                 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
2600                         break;
2601
2602                 ret = tun_attach_filter(tun);
2603                 break;
2604
2605         case TUNDETACHFILTER:
2606                 /* Can be set only for TAPs */
2607                 ret = -EINVAL;
2608                 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2609                         break;
2610                 ret = 0;
2611                 tun_detach_filter(tun, tun->numqueues);
2612                 break;
2613
2614         case TUNGETFILTER:
2615                 ret = -EINVAL;
2616                 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2617                         break;
2618                 ret = -EFAULT;
2619                 if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
2620                         break;
2621                 ret = 0;
2622                 break;
2623
2624         default:
2625                 ret = -EINVAL;
2626                 break;
2627         }
2628
2629 unlock:
2630         rtnl_unlock();
2631         if (tun)
2632                 tun_put(tun);
2633         return ret;
2634 }
2635
2636 static long tun_chr_ioctl(struct file *file,
2637                           unsigned int cmd, unsigned long arg)
2638 {
2639         return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2640 }
2641
2642 #ifdef CONFIG_COMPAT
2643 static long tun_chr_compat_ioctl(struct file *file,
2644                          unsigned int cmd, unsigned long arg)
2645 {
2646         switch (cmd) {
2647         case TUNSETIFF:
2648         case TUNGETIFF:
2649         case TUNSETTXFILTER:
2650         case TUNGETSNDBUF:
2651         case TUNSETSNDBUF:
2652         case SIOCGIFHWADDR:
2653         case SIOCSIFHWADDR:
2654                 arg = (unsigned long)compat_ptr(arg);
2655                 break;
2656         default:
2657                 arg = (compat_ulong_t)arg;
2658                 break;
2659         }
2660
2661         /*
2662          * compat_ifreq is shorter than ifreq, so we must not access beyond
2663          * the end of that structure. All fields that are used in this
2664          * driver are compatible though, we don't need to convert the
2665          * contents.
2666          */
2667         return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2668 }
2669 #endif /* CONFIG_COMPAT */
2670
2671 static int tun_chr_fasync(int fd, struct file *file, int on)
2672 {
2673         struct tun_file *tfile = file->private_data;
2674         int ret;
2675
2676         if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
2677                 goto out;
2678
2679         if (on) {
2680                 __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
2681                 tfile->flags |= TUN_FASYNC;
2682         } else
2683                 tfile->flags &= ~TUN_FASYNC;
2684         ret = 0;
2685 out:
2686         return ret;
2687 }
2688
2689 static int tun_chr_open(struct inode *inode, struct file * file)
2690 {
2691         struct net *net = current->nsproxy->net_ns;
2692         struct tun_file *tfile;
2693
2694         DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2695
2696         tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
2697                                             &tun_proto, 0);
2698         if (!tfile)
2699                 return -ENOMEM;
2700         if (skb_array_init(&tfile->tx_array, 0, GFP_KERNEL)) {
2701                 sk_free(&tfile->sk);
2702                 return -ENOMEM;
2703         }
2704
2705         RCU_INIT_POINTER(tfile->tun, NULL);
2706         tfile->flags = 0;
2707         tfile->ifindex = 0;
2708
2709         init_waitqueue_head(&tfile->wq.wait);
2710         RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
2711
2712         tfile->socket.file = file;
2713         tfile->socket.ops = &tun_socket_ops;
2714
2715         sock_init_data(&tfile->socket, &tfile->sk);
2716
2717         tfile->sk.sk_write_space = tun_sock_write_space;
2718         tfile->sk.sk_sndbuf = INT_MAX;
2719
2720         file->private_data = tfile;
2721         INIT_LIST_HEAD(&tfile->next);
2722
2723         sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
2724
2725         return 0;
2726 }
2727
2728 static int tun_chr_close(struct inode *inode, struct file *file)
2729 {
2730         struct tun_file *tfile = file->private_data;
2731
2732         tun_detach(tfile, true);
2733
2734         return 0;
2735 }
2736
2737 #ifdef CONFIG_PROC_FS
2738 static void tun_chr_show_fdinfo(struct seq_file *m, struct file *f)
2739 {
2740         struct tun_struct *tun;
2741         struct ifreq ifr;
2742
2743         memset(&ifr, 0, sizeof(ifr));
2744
2745         rtnl_lock();
2746         tun = tun_get(f);
2747         if (tun)
2748                 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2749         rtnl_unlock();
2750
2751         if (tun)
2752                 tun_put(tun);
2753
2754         seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
2755 }
2756 #endif
2757
2758 static const struct file_operations tun_fops = {
2759         .owner  = THIS_MODULE,
2760         .llseek = no_llseek,
2761         .read_iter  = tun_chr_read_iter,
2762         .write_iter = tun_chr_write_iter,
2763         .poll   = tun_chr_poll,
2764         .unlocked_ioctl = tun_chr_ioctl,
2765 #ifdef CONFIG_COMPAT
2766         .compat_ioctl = tun_chr_compat_ioctl,
2767 #endif
2768         .open   = tun_chr_open,
2769         .release = tun_chr_close,
2770         .fasync = tun_chr_fasync,
2771 #ifdef CONFIG_PROC_FS
2772         .show_fdinfo = tun_chr_show_fdinfo,
2773 #endif
2774 };
2775
2776 static struct miscdevice tun_miscdev = {
2777         .minor = TUN_MINOR,
2778         .name = "tun",
2779         .nodename = "net/tun",
2780         .fops = &tun_fops,
2781 };
2782
2783 /* ethtool interface */
2784
2785 static int tun_get_link_ksettings(struct net_device *dev,
2786                                   struct ethtool_link_ksettings *cmd)
2787 {
2788         ethtool_link_ksettings_zero_link_mode(cmd, supported);
2789         ethtool_link_ksettings_zero_link_mode(cmd, advertising);
2790         cmd->base.speed         = SPEED_10;
2791         cmd->base.duplex        = DUPLEX_FULL;
2792         cmd->base.port          = PORT_TP;
2793         cmd->base.phy_address   = 0;
2794         cmd->base.autoneg       = AUTONEG_DISABLE;
2795         return 0;
2796 }
2797
2798 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2799 {
2800         struct tun_struct *tun = netdev_priv(dev);
2801
2802         strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
2803         strlcpy(info->version, DRV_VERSION, sizeof(info->version));
2804
2805         switch (tun->flags & TUN_TYPE_MASK) {
2806         case IFF_TUN:
2807                 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
2808                 break;
2809         case IFF_TAP:
2810                 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
2811                 break;
2812         }
2813 }
2814
2815 static u32 tun_get_msglevel(struct net_device *dev)
2816 {
2817 #ifdef TUN_DEBUG
2818         struct tun_struct *tun = netdev_priv(dev);
2819         return tun->debug;
2820 #else
2821         return -EOPNOTSUPP;
2822 #endif
2823 }
2824
2825 static void tun_set_msglevel(struct net_device *dev, u32 value)
2826 {
2827 #ifdef TUN_DEBUG
2828         struct tun_struct *tun = netdev_priv(dev);
2829         tun->debug = value;
2830 #endif
2831 }
2832
2833 static int tun_get_coalesce(struct net_device *dev,
2834                             struct ethtool_coalesce *ec)
2835 {
2836         struct tun_struct *tun = netdev_priv(dev);
2837
2838         ec->rx_max_coalesced_frames = tun->rx_batched;
2839
2840         return 0;
2841 }
2842
2843 static int tun_set_coalesce(struct net_device *dev,
2844                             struct ethtool_coalesce *ec)
2845 {
2846         struct tun_struct *tun = netdev_priv(dev);
2847
2848         if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
2849                 tun->rx_batched = NAPI_POLL_WEIGHT;
2850         else
2851                 tun->rx_batched = ec->rx_max_coalesced_frames;
2852
2853         return 0;
2854 }
2855
2856 static const struct ethtool_ops tun_ethtool_ops = {
2857         .get_drvinfo    = tun_get_drvinfo,
2858         .get_msglevel   = tun_get_msglevel,
2859         .set_msglevel   = tun_set_msglevel,
2860         .get_link       = ethtool_op_get_link,
2861         .get_ts_info    = ethtool_op_get_ts_info,
2862         .get_coalesce   = tun_get_coalesce,
2863         .set_coalesce   = tun_set_coalesce,
2864         .get_link_ksettings = tun_get_link_ksettings,
2865 };
2866
2867 static int tun_queue_resize(struct tun_struct *tun)
2868 {
2869         struct net_device *dev = tun->dev;
2870         struct tun_file *tfile;
2871         struct skb_array **arrays;
2872         int n = tun->numqueues + tun->numdisabled;
2873         int ret, i;
2874
2875         arrays = kmalloc_array(n, sizeof(*arrays), GFP_KERNEL);
2876         if (!arrays)
2877                 return -ENOMEM;
2878
2879         for (i = 0; i < tun->numqueues; i++) {
2880                 tfile = rtnl_dereference(tun->tfiles[i]);
2881                 arrays[i] = &tfile->tx_array;
2882         }
2883         list_for_each_entry(tfile, &tun->disabled, next)
2884                 arrays[i++] = &tfile->tx_array;
2885
2886         ret = skb_array_resize_multiple(arrays, n,
2887                                         dev->tx_queue_len, GFP_KERNEL);
2888
2889         kfree(arrays);
2890         return ret;
2891 }
2892
2893 static int tun_device_event(struct notifier_block *unused,
2894                             unsigned long event, void *ptr)
2895 {
2896         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
2897         struct tun_struct *tun = netdev_priv(dev);
2898         int i;
2899
2900         if (dev->rtnl_link_ops != &tun_link_ops)
2901                 return NOTIFY_DONE;
2902
2903         switch (event) {
2904         case NETDEV_CHANGE_TX_QUEUE_LEN:
2905                 if (tun_queue_resize(tun))
2906                         return NOTIFY_BAD;
2907                 break;
2908         case NETDEV_UP:
2909                 for (i = 0; i < tun->numqueues; i++) {
2910                         struct tun_file *tfile;
2911
2912                         tfile = rtnl_dereference(tun->tfiles[i]);
2913                         tfile->socket.sk->sk_write_space(tfile->socket.sk);
2914                 }
2915                 break;
2916         default:
2917                 break;
2918         }
2919
2920         return NOTIFY_DONE;
2921 }
2922
2923 static struct notifier_block tun_notifier_block __read_mostly = {
2924         .notifier_call  = tun_device_event,
2925 };
2926
2927 static int __init tun_init(void)
2928 {
2929         int ret = 0;
2930
2931         pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
2932
2933         ret = rtnl_link_register(&tun_link_ops);
2934         if (ret) {
2935                 pr_err("Can't register link_ops\n");
2936                 goto err_linkops;
2937         }
2938
2939         ret = misc_register(&tun_miscdev);
2940         if (ret) {
2941                 pr_err("Can't register misc device %d\n", TUN_MINOR);
2942                 goto err_misc;
2943         }
2944
2945         ret = register_netdevice_notifier(&tun_notifier_block);
2946         if (ret) {
2947                 pr_err("Can't register netdevice notifier\n");
2948                 goto err_notifier;
2949         }
2950
2951         return  0;
2952
2953 err_notifier:
2954         misc_deregister(&tun_miscdev);
2955 err_misc:
2956         rtnl_link_unregister(&tun_link_ops);
2957 err_linkops:
2958         return ret;
2959 }
2960
2961 static void tun_cleanup(void)
2962 {
2963         misc_deregister(&tun_miscdev);
2964         rtnl_link_unregister(&tun_link_ops);
2965         unregister_netdevice_notifier(&tun_notifier_block);
2966 }
2967
2968 /* Get an underlying socket object from tun file.  Returns error unless file is
2969  * attached to a device.  The returned object works like a packet socket, it
2970  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
2971  * holding a reference to the file for as long as the socket is in use. */
2972 struct socket *tun_get_socket(struct file *file)
2973 {
2974         struct tun_file *tfile;
2975         if (file->f_op != &tun_fops)
2976                 return ERR_PTR(-EINVAL);
2977         tfile = file->private_data;
2978         if (!tfile)
2979                 return ERR_PTR(-EBADFD);
2980         return &tfile->socket;
2981 }
2982 EXPORT_SYMBOL_GPL(tun_get_socket);
2983
2984 struct skb_array *tun_get_skb_array(struct file *file)
2985 {
2986         struct tun_file *tfile;
2987
2988         if (file->f_op != &tun_fops)
2989                 return ERR_PTR(-EINVAL);
2990         tfile = file->private_data;
2991         if (!tfile)
2992                 return ERR_PTR(-EBADFD);
2993         return &tfile->tx_array;
2994 }
2995 EXPORT_SYMBOL_GPL(tun_get_skb_array);
2996
2997 module_init(tun_init);
2998 module_exit(tun_cleanup);
2999 MODULE_DESCRIPTION(DRV_DESCRIPTION);
3000 MODULE_AUTHOR(DRV_COPYRIGHT);
3001 MODULE_LICENSE("GPL");
3002 MODULE_ALIAS_MISCDEV(TUN_MINOR);
3003 MODULE_ALIAS("devname:net/tun");