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