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