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