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