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