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