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