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