xref: /linux/drivers/net/tun.c (revision d603517771d8e08a2d8fc9e1f7682ce393d3973a)
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 		return -EINVAL;
2463 
2464 	xdp_prog = rcu_dereference(tun->xdp_prog);
2465 	if (xdp_prog) {
2466 		if (gso->gso_type) {
2467 			skb_xdp = true;
2468 			goto build;
2469 		}
2470 
2471 		xdp_init_buff(xdp, buflen, &tfile->xdp_rxq);
2472 
2473 		act = bpf_prog_run_xdp(xdp_prog, xdp);
2474 		ret = tun_xdp_act(tun, xdp_prog, xdp, act);
2475 		if (ret < 0) {
2476 			put_page(virt_to_head_page(xdp->data));
2477 			return ret;
2478 		}
2479 
2480 		switch (ret) {
2481 		case XDP_REDIRECT:
2482 			*flush = true;
2483 			fallthrough;
2484 		case XDP_TX:
2485 			return 0;
2486 		case XDP_PASS:
2487 			break;
2488 		default:
2489 			page = virt_to_head_page(xdp->data);
2490 			if (tpage->page == page) {
2491 				++tpage->count;
2492 			} else {
2493 				tun_put_page(tpage);
2494 				tpage->page = page;
2495 				tpage->count = 1;
2496 			}
2497 			return 0;
2498 		}
2499 	}
2500 
2501 build:
2502 	skb = build_skb(xdp->data_hard_start, buflen);
2503 	if (!skb) {
2504 		ret = -ENOMEM;
2505 		goto out;
2506 	}
2507 
2508 	skb_reserve(skb, xdp->data - xdp->data_hard_start);
2509 	skb_put(skb, xdp->data_end - xdp->data);
2510 
2511 	/* The externally provided xdp_buff may have no metadata support, which
2512 	 * is marked by xdp->data_meta being xdp->data + 1. This will lead to a
2513 	 * metasize of -1 and is the reason why the condition checks for > 0.
2514 	 */
2515 	metasize = xdp->data - xdp->data_meta;
2516 	if (metasize > 0)
2517 		skb_metadata_set(skb, metasize);
2518 
2519 	features = tun_vnet_hdr_guest_features(READ_ONCE(tun->vnet_hdr_sz));
2520 	tnl_hdr = (struct virtio_net_hdr_v1_hash_tunnel *)gso;
2521 	if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr)) {
2522 		atomic_long_inc(&tun->rx_frame_errors);
2523 		kfree_skb(skb);
2524 		ret = -EINVAL;
2525 		goto out;
2526 	}
2527 
2528 	skb->protocol = eth_type_trans(skb, tun->dev);
2529 	skb_reset_network_header(skb);
2530 	skb_probe_transport_header(skb);
2531 	skb_record_rx_queue(skb, tfile->queue_index);
2532 
2533 	if (skb_xdp) {
2534 		ret = do_xdp_generic(xdp_prog, &skb);
2535 		if (ret != XDP_PASS) {
2536 			ret = 0;
2537 			goto out;
2538 		}
2539 	}
2540 
2541 	if (!rcu_dereference(tun->steering_prog) && tun->numqueues > 1 &&
2542 	    !tfile->detached)
2543 		rxhash = __skb_get_hash_symmetric(skb);
2544 
2545 	if (tfile->napi_enabled) {
2546 		queue = &tfile->sk.sk_write_queue;
2547 		spin_lock(&queue->lock);
2548 
2549 		if (unlikely(tfile->detached)) {
2550 			spin_unlock(&queue->lock);
2551 			kfree_skb(skb);
2552 			return -EBUSY;
2553 		}
2554 
2555 		__skb_queue_tail(queue, skb);
2556 		spin_unlock(&queue->lock);
2557 		ret = 1;
2558 	} else {
2559 		netif_receive_skb(skb);
2560 		ret = 0;
2561 	}
2562 
2563 	/* No need to disable preemption here since this function is
2564 	 * always called with bh disabled
2565 	 */
2566 	dev_sw_netstats_rx_add(tun->dev, datasize);
2567 
2568 	if (rxhash)
2569 		tun_flow_update(tun, rxhash, tfile);
2570 
2571 out:
2572 	return ret;
2573 }
2574 
2575 static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
2576 {
2577 	int ret, i;
2578 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2579 	struct tun_struct *tun = tun_get(tfile);
2580 	struct tun_msg_ctl *ctl = m->msg_control;
2581 	struct xdp_buff *xdp;
2582 
2583 	if (!tun)
2584 		return -EBADFD;
2585 
2586 	if (m->msg_controllen == sizeof(struct tun_msg_ctl) &&
2587 	    ctl && ctl->type == TUN_MSG_PTR) {
2588 		struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
2589 		struct tun_page tpage;
2590 		int n = ctl->num;
2591 		int flush = 0, queued = 0;
2592 
2593 		memset(&tpage, 0, sizeof(tpage));
2594 
2595 		local_bh_disable();
2596 		rcu_read_lock();
2597 		bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
2598 
2599 		for (i = 0; i < n; i++) {
2600 			xdp = &((struct xdp_buff *)ctl->ptr)[i];
2601 			ret = tun_xdp_one(tun, tfile, xdp, &flush, &tpage);
2602 			if (ret > 0)
2603 				queued += ret;
2604 		}
2605 
2606 		if (flush)
2607 			xdp_do_flush();
2608 
2609 		if (tfile->napi_enabled && queued > 0)
2610 			napi_schedule(&tfile->napi);
2611 
2612 		bpf_net_ctx_clear(bpf_net_ctx);
2613 		rcu_read_unlock();
2614 		local_bh_enable();
2615 
2616 		tun_put_page(&tpage);
2617 
2618 		ret = total_len;
2619 		goto out;
2620 	}
2621 
2622 	ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
2623 			   m->msg_flags & MSG_DONTWAIT,
2624 			   m->msg_flags & MSG_MORE);
2625 out:
2626 	tun_put(tun);
2627 	return ret;
2628 }
2629 
2630 static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
2631 		       int flags)
2632 {
2633 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2634 	struct tun_struct *tun = tun_get(tfile);
2635 	void *ptr = m->msg_control;
2636 	int ret;
2637 
2638 	if (!tun) {
2639 		ret = -EBADFD;
2640 		goto out_free;
2641 	}
2642 
2643 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
2644 		ret = -EINVAL;
2645 		goto out_put_tun;
2646 	}
2647 	if (flags & MSG_ERRQUEUE) {
2648 		ret = sock_recv_errqueue(sock->sk, m, total_len,
2649 					 SOL_PACKET, TUN_TX_TIMESTAMP);
2650 		goto out;
2651 	}
2652 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
2653 	if (ret > (ssize_t)total_len) {
2654 		m->msg_flags |= MSG_TRUNC;
2655 		ret = flags & MSG_TRUNC ? ret : total_len;
2656 	}
2657 out:
2658 	tun_put(tun);
2659 	return ret;
2660 
2661 out_put_tun:
2662 	tun_put(tun);
2663 out_free:
2664 	tun_ptr_free(ptr);
2665 	return ret;
2666 }
2667 
2668 static int tun_ptr_peek_len(void *ptr)
2669 {
2670 	if (likely(ptr)) {
2671 		if (tun_is_xdp_frame(ptr)) {
2672 			struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2673 
2674 			return xdpf->len;
2675 		}
2676 		return __skb_array_len_with_tag(ptr);
2677 	} else {
2678 		return 0;
2679 	}
2680 }
2681 
2682 static int tun_peek_len(struct socket *sock)
2683 {
2684 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2685 	struct tun_struct *tun;
2686 	int ret = 0;
2687 
2688 	tun = tun_get(tfile);
2689 	if (!tun)
2690 		return 0;
2691 
2692 	ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
2693 	tun_put(tun);
2694 
2695 	return ret;
2696 }
2697 
2698 /* Ops structure to mimic raw sockets with tun */
2699 static const struct proto_ops tun_socket_ops = {
2700 	.peek_len = tun_peek_len,
2701 	.sendmsg = tun_sendmsg,
2702 	.recvmsg = tun_recvmsg,
2703 };
2704 
2705 static struct proto tun_proto = {
2706 	.name		= "tun",
2707 	.owner		= THIS_MODULE,
2708 	.obj_size	= sizeof(struct tun_file),
2709 };
2710 
2711 static int tun_flags(struct tun_struct *tun)
2712 {
2713 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2714 }
2715 
2716 static ssize_t tun_flags_show(struct device *dev, struct device_attribute *attr,
2717 			      char *buf)
2718 {
2719 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2720 	return sysfs_emit(buf, "0x%x\n", tun_flags(tun));
2721 }
2722 
2723 static ssize_t owner_show(struct device *dev, struct device_attribute *attr,
2724 			  char *buf)
2725 {
2726 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2727 	return uid_valid(tun->owner)?
2728 		sysfs_emit(buf, "%u\n",
2729 			   from_kuid_munged(current_user_ns(), tun->owner)) :
2730 		sysfs_emit(buf, "-1\n");
2731 }
2732 
2733 static ssize_t group_show(struct device *dev, struct device_attribute *attr,
2734 			  char *buf)
2735 {
2736 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2737 	return gid_valid(tun->group) ?
2738 		sysfs_emit(buf, "%u\n",
2739 			   from_kgid_munged(current_user_ns(), tun->group)) :
2740 		sysfs_emit(buf, "-1\n");
2741 }
2742 
2743 static DEVICE_ATTR_RO(tun_flags);
2744 static DEVICE_ATTR_RO(owner);
2745 static DEVICE_ATTR_RO(group);
2746 
2747 static struct attribute *tun_dev_attrs[] = {
2748 	&dev_attr_tun_flags.attr,
2749 	&dev_attr_owner.attr,
2750 	&dev_attr_group.attr,
2751 	NULL
2752 };
2753 
2754 static const struct attribute_group tun_attr_group = {
2755 	.attrs = tun_dev_attrs
2756 };
2757 
2758 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
2759 {
2760 	struct tun_struct *tun;
2761 	struct tun_file *tfile = file->private_data;
2762 	struct net_device *dev;
2763 	int err;
2764 
2765 	if (tfile->detached)
2766 		return -EINVAL;
2767 
2768 	if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
2769 		if (!capable(CAP_NET_ADMIN))
2770 			return -EPERM;
2771 
2772 		if (!(ifr->ifr_flags & IFF_NAPI) ||
2773 		    (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
2774 			return -EINVAL;
2775 	}
2776 
2777 	dev = __dev_get_by_name(net, ifr->ifr_name);
2778 	if (dev) {
2779 		if (ifr->ifr_flags & IFF_TUN_EXCL)
2780 			return -EBUSY;
2781 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
2782 			tun = netdev_priv(dev);
2783 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
2784 			tun = netdev_priv(dev);
2785 		else
2786 			return -EINVAL;
2787 
2788 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
2789 		    !!(tun->flags & IFF_MULTI_QUEUE))
2790 			return -EINVAL;
2791 
2792 		if (tun_not_capable(tun))
2793 			return -EPERM;
2794 		err = security_tun_dev_open(tun->security);
2795 		if (err < 0)
2796 			return err;
2797 
2798 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
2799 				 ifr->ifr_flags & IFF_NAPI,
2800 				 ifr->ifr_flags & IFF_NAPI_FRAGS, true);
2801 		if (err < 0)
2802 			return err;
2803 
2804 		if (tun->flags & IFF_MULTI_QUEUE &&
2805 		    (tun->numqueues + tun->numdisabled > 1)) {
2806 			/* One or more queue has already been attached, no need
2807 			 * to initialize the device again.
2808 			 */
2809 			netdev_state_change(dev);
2810 			return 0;
2811 		}
2812 
2813 		tun->flags = (tun->flags & ~TUN_FEATURES) |
2814 			      (ifr->ifr_flags & TUN_FEATURES);
2815 
2816 		netdev_state_change(dev);
2817 	} else {
2818 		char *name;
2819 		unsigned long flags = 0;
2820 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2821 			     MAX_TAP_QUEUES : 1;
2822 
2823 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2824 			return -EPERM;
2825 		err = security_tun_dev_create();
2826 		if (err < 0)
2827 			return err;
2828 
2829 		/* Set dev type */
2830 		if (ifr->ifr_flags & IFF_TUN) {
2831 			/* TUN device */
2832 			flags |= IFF_TUN;
2833 			name = "tun%d";
2834 		} else if (ifr->ifr_flags & IFF_TAP) {
2835 			/* TAP device */
2836 			flags |= IFF_TAP;
2837 			name = "tap%d";
2838 		} else
2839 			return -EINVAL;
2840 
2841 		if (*ifr->ifr_name)
2842 			name = ifr->ifr_name;
2843 
2844 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2845 				       NET_NAME_UNKNOWN, tun_setup, queues,
2846 				       queues);
2847 
2848 		if (!dev)
2849 			return -ENOMEM;
2850 
2851 		dev_net_set(dev, net);
2852 		dev->rtnl_link_ops = &tun_link_ops;
2853 		dev->ifindex = tfile->ifindex;
2854 		dev->sysfs_groups[0] = &tun_attr_group;
2855 
2856 		tun = netdev_priv(dev);
2857 		tun->dev = dev;
2858 		tun->flags = flags;
2859 		tun->txflt.count = 0;
2860 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
2861 
2862 		tun->align = NET_SKB_PAD;
2863 		tun->filter_attached = false;
2864 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
2865 		tun->rx_batched = 0;
2866 		RCU_INIT_POINTER(tun->steering_prog, NULL);
2867 
2868 		tun->ifr = ifr;
2869 		tun->file = file;
2870 
2871 		tun_net_initialize(dev);
2872 
2873 		err = register_netdevice(tun->dev);
2874 		if (err < 0) {
2875 			free_netdev(dev);
2876 			return err;
2877 		}
2878 		/* free_netdev() won't check refcnt, to avoid race
2879 		 * with dev_put() we need publish tun after registration.
2880 		 */
2881 		rcu_assign_pointer(tfile->tun, tun);
2882 	}
2883 
2884 	if (ifr->ifr_flags & IFF_NO_CARRIER)
2885 		netif_carrier_off(tun->dev);
2886 	else
2887 		netif_carrier_on(tun->dev);
2888 
2889 	/* Make sure persistent devices do not get stuck in
2890 	 * xoff state.
2891 	 */
2892 	if (netif_running(tun->dev))
2893 		netif_tx_wake_all_queues(tun->dev);
2894 
2895 	strscpy(ifr->ifr_name, tun->dev->name);
2896 	return 0;
2897 }
2898 
2899 static void tun_get_iff(struct tun_struct *tun, struct ifreq *ifr)
2900 {
2901 	strscpy(ifr->ifr_name, tun->dev->name);
2902 
2903 	ifr->ifr_flags = tun_flags(tun);
2904 
2905 }
2906 
2907 #define PLAIN_GSO (NETIF_F_GSO_UDP_L4 | NETIF_F_TSO | NETIF_F_TSO6)
2908 
2909 /* This is like a cut-down ethtool ops, except done via tun fd so no
2910  * privs required. */
2911 static int set_offload(struct tun_struct *tun, unsigned long arg)
2912 {
2913 	netdev_features_t features = 0;
2914 
2915 	if (arg & TUN_F_CSUM) {
2916 		features |= NETIF_F_HW_CSUM;
2917 		arg &= ~TUN_F_CSUM;
2918 
2919 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
2920 			if (arg & TUN_F_TSO_ECN) {
2921 				features |= NETIF_F_TSO_ECN;
2922 				arg &= ~TUN_F_TSO_ECN;
2923 			}
2924 			if (arg & TUN_F_TSO4)
2925 				features |= NETIF_F_TSO;
2926 			if (arg & TUN_F_TSO6)
2927 				features |= NETIF_F_TSO6;
2928 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
2929 		}
2930 
2931 		arg &= ~TUN_F_UFO;
2932 
2933 		/* TODO: for now USO4 and USO6 should work simultaneously */
2934 		if (arg & TUN_F_USO4 && arg & TUN_F_USO6) {
2935 			features |= NETIF_F_GSO_UDP_L4;
2936 			arg &= ~(TUN_F_USO4 | TUN_F_USO6);
2937 		}
2938 
2939 		/*
2940 		 * Tunnel offload is allowed only if some plain offload is
2941 		 * available, too.
2942 		 */
2943 		if (features & PLAIN_GSO && arg & TUN_F_UDP_TUNNEL_GSO) {
2944 			features |= NETIF_F_GSO_UDP_TUNNEL;
2945 			if (arg & TUN_F_UDP_TUNNEL_GSO_CSUM)
2946 				features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
2947 			arg &= ~(TUN_F_UDP_TUNNEL_GSO |
2948 				 TUN_F_UDP_TUNNEL_GSO_CSUM);
2949 		}
2950 	}
2951 
2952 	/* This gives the user a way to test for new features in future by
2953 	 * trying to set them. */
2954 	if (arg)
2955 		return -EINVAL;
2956 
2957 	tun->set_features = features;
2958 	tun->dev->wanted_features &= ~TUN_USER_FEATURES;
2959 	tun->dev->wanted_features |= features;
2960 	netdev_update_features(tun->dev);
2961 
2962 	return 0;
2963 }
2964 
2965 static void tun_detach_filter(struct tun_struct *tun, int n)
2966 {
2967 	int i;
2968 	struct tun_file *tfile;
2969 
2970 	for (i = 0; i < n; i++) {
2971 		tfile = rtnl_dereference(tun->tfiles[i]);
2972 		lock_sock(tfile->socket.sk);
2973 		sk_detach_filter(tfile->socket.sk);
2974 		release_sock(tfile->socket.sk);
2975 	}
2976 
2977 	tun->filter_attached = false;
2978 }
2979 
2980 static int tun_attach_filter(struct tun_struct *tun)
2981 {
2982 	int i, ret = 0;
2983 	struct tun_file *tfile;
2984 
2985 	for (i = 0; i < tun->numqueues; i++) {
2986 		tfile = rtnl_dereference(tun->tfiles[i]);
2987 		lock_sock(tfile->socket.sk);
2988 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
2989 		release_sock(tfile->socket.sk);
2990 		if (ret) {
2991 			tun_detach_filter(tun, i);
2992 			return ret;
2993 		}
2994 	}
2995 
2996 	tun->filter_attached = true;
2997 	return ret;
2998 }
2999 
3000 static void tun_set_sndbuf(struct tun_struct *tun)
3001 {
3002 	struct tun_file *tfile;
3003 	int i;
3004 
3005 	for (i = 0; i < tun->numqueues; i++) {
3006 		tfile = rtnl_dereference(tun->tfiles[i]);
3007 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
3008 	}
3009 }
3010 
3011 static int tun_set_queue(struct file *file, struct ifreq *ifr)
3012 {
3013 	struct tun_file *tfile = file->private_data;
3014 	struct tun_struct *tun;
3015 	int ret = 0;
3016 
3017 	rtnl_lock();
3018 
3019 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
3020 		tun = tfile->detached;
3021 		if (!tun) {
3022 			ret = -EINVAL;
3023 			goto unlock;
3024 		}
3025 		ret = security_tun_dev_attach_queue(tun->security);
3026 		if (ret < 0)
3027 			goto unlock;
3028 		ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
3029 				 tun->flags & IFF_NAPI_FRAGS, true);
3030 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
3031 		tun = rtnl_dereference(tfile->tun);
3032 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
3033 			ret = -EINVAL;
3034 		else
3035 			__tun_detach(tfile, false);
3036 	} else
3037 		ret = -EINVAL;
3038 
3039 	if (ret >= 0)
3040 		netdev_state_change(tun->dev);
3041 
3042 unlock:
3043 	rtnl_unlock();
3044 	return ret;
3045 }
3046 
3047 static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog __rcu **prog_p,
3048 			void __user *data)
3049 {
3050 	struct bpf_prog *prog;
3051 	int fd;
3052 
3053 	if (copy_from_user(&fd, data, sizeof(fd)))
3054 		return -EFAULT;
3055 
3056 	if (fd == -1) {
3057 		prog = NULL;
3058 	} else {
3059 		prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
3060 		if (IS_ERR(prog))
3061 			return PTR_ERR(prog);
3062 	}
3063 
3064 	return __tun_set_ebpf(tun, prog_p, prog);
3065 }
3066 
3067 /* Return correct value for tun->dev->addr_len based on tun->dev->type. */
3068 static unsigned char tun_get_addr_len(unsigned short type)
3069 {
3070 	switch (type) {
3071 	case ARPHRD_IP6GRE:
3072 	case ARPHRD_TUNNEL6:
3073 		return sizeof(struct in6_addr);
3074 	case ARPHRD_IPGRE:
3075 	case ARPHRD_TUNNEL:
3076 	case ARPHRD_SIT:
3077 		return 4;
3078 	case ARPHRD_ETHER:
3079 		return ETH_ALEN;
3080 	case ARPHRD_IEEE802154:
3081 	case ARPHRD_IEEE802154_MONITOR:
3082 		return IEEE802154_EXTENDED_ADDR_LEN;
3083 	case ARPHRD_PHONET_PIPE:
3084 	case ARPHRD_PPP:
3085 	case ARPHRD_NONE:
3086 		return 0;
3087 	case ARPHRD_6LOWPAN:
3088 		return EUI64_ADDR_LEN;
3089 	case ARPHRD_FDDI:
3090 		return FDDI_K_ALEN;
3091 	case ARPHRD_HIPPI:
3092 		return HIPPI_ALEN;
3093 	case ARPHRD_IEEE802:
3094 		return FC_ALEN;
3095 	case ARPHRD_ROSE:
3096 		return ROSE_ADDR_LEN;
3097 	case ARPHRD_NETROM:
3098 		return AX25_ADDR_LEN;
3099 	case ARPHRD_LOCALTLK:
3100 		return LTALK_ALEN;
3101 	default:
3102 		return 0;
3103 	}
3104 }
3105 
3106 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
3107 			    unsigned long arg, int ifreq_len)
3108 {
3109 	struct tun_file *tfile = file->private_data;
3110 	struct net *net = sock_net(&tfile->sk);
3111 	struct tun_struct *tun;
3112 	void __user* argp = (void __user*)arg;
3113 	unsigned int carrier;
3114 	struct ifreq ifr;
3115 	kuid_t owner;
3116 	kgid_t group;
3117 	int ifindex;
3118 	int sndbuf;
3119 	int ret;
3120 	bool do_notify = false;
3121 
3122 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
3123 	    (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
3124 		if (copy_from_user(&ifr, argp, ifreq_len))
3125 			return -EFAULT;
3126 	} else {
3127 		memset(&ifr, 0, sizeof(ifr));
3128 	}
3129 	if (cmd == TUNGETFEATURES) {
3130 		/* Currently this just means: "what IFF flags are valid?".
3131 		 * This is needed because we never checked for invalid flags on
3132 		 * TUNSETIFF.
3133 		 */
3134 		return put_user(IFF_TUN | IFF_TAP | IFF_NO_CARRIER |
3135 				TUN_FEATURES, (unsigned int __user*)argp);
3136 	} else if (cmd == TUNSETQUEUE) {
3137 		return tun_set_queue(file, &ifr);
3138 	} else if (cmd == SIOCGSKNS) {
3139 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3140 			return -EPERM;
3141 		return open_related_ns(&net->ns, get_net_ns);
3142 	}
3143 
3144 	rtnl_lock();
3145 
3146 	tun = tun_get(tfile);
3147 	if (cmd == TUNSETIFF) {
3148 		ret = -EEXIST;
3149 		if (tun)
3150 			goto unlock;
3151 
3152 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
3153 
3154 		ret = tun_set_iff(net, file, &ifr);
3155 
3156 		if (ret)
3157 			goto unlock;
3158 
3159 		if (copy_to_user(argp, &ifr, ifreq_len))
3160 			ret = -EFAULT;
3161 		goto unlock;
3162 	}
3163 	if (cmd == TUNSETIFINDEX) {
3164 		ret = -EPERM;
3165 		if (tun)
3166 			goto unlock;
3167 
3168 		ret = -EFAULT;
3169 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
3170 			goto unlock;
3171 		ret = -EINVAL;
3172 		if (ifindex < 0)
3173 			goto unlock;
3174 		ret = 0;
3175 		tfile->ifindex = ifindex;
3176 		goto unlock;
3177 	}
3178 
3179 	ret = -EBADFD;
3180 	if (!tun)
3181 		goto unlock;
3182 
3183 	netif_info(tun, drv, tun->dev, "tun_chr_ioctl cmd %u\n", cmd);
3184 
3185 	net = dev_net(tun->dev);
3186 	ret = 0;
3187 	switch (cmd) {
3188 	case TUNGETIFF:
3189 		tun_get_iff(tun, &ifr);
3190 
3191 		if (tfile->detached)
3192 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
3193 		if (!tfile->socket.sk->sk_filter)
3194 			ifr.ifr_flags |= IFF_NOFILTER;
3195 
3196 		if (copy_to_user(argp, &ifr, ifreq_len))
3197 			ret = -EFAULT;
3198 		break;
3199 
3200 	case TUNSETNOCSUM:
3201 		/* Disable/Enable checksum */
3202 
3203 		/* [unimplemented] */
3204 		netif_info(tun, drv, tun->dev, "ignored: set checksum %s\n",
3205 			   arg ? "disabled" : "enabled");
3206 		break;
3207 
3208 	case TUNSETPERSIST:
3209 		/* Disable/Enable persist mode. Keep an extra reference to the
3210 		 * module to prevent the module being unprobed.
3211 		 */
3212 		if (arg && !(tun->flags & IFF_PERSIST)) {
3213 			tun->flags |= IFF_PERSIST;
3214 			__module_get(THIS_MODULE);
3215 			do_notify = true;
3216 		}
3217 		if (!arg && (tun->flags & IFF_PERSIST)) {
3218 			tun->flags &= ~IFF_PERSIST;
3219 			module_put(THIS_MODULE);
3220 			do_notify = true;
3221 		}
3222 
3223 		netif_info(tun, drv, tun->dev, "persist %s\n",
3224 			   arg ? "enabled" : "disabled");
3225 		break;
3226 
3227 	case TUNSETOWNER:
3228 		/* Set owner of the device */
3229 		owner = make_kuid(current_user_ns(), arg);
3230 		if (!uid_valid(owner)) {
3231 			ret = -EINVAL;
3232 			break;
3233 		}
3234 		tun->owner = owner;
3235 		do_notify = true;
3236 		netif_info(tun, drv, tun->dev, "owner set to %u\n",
3237 			   from_kuid(&init_user_ns, tun->owner));
3238 		break;
3239 
3240 	case TUNSETGROUP:
3241 		/* Set group of the device */
3242 		group = make_kgid(current_user_ns(), arg);
3243 		if (!gid_valid(group)) {
3244 			ret = -EINVAL;
3245 			break;
3246 		}
3247 		tun->group = group;
3248 		do_notify = true;
3249 		netif_info(tun, drv, tun->dev, "group set to %u\n",
3250 			   from_kgid(&init_user_ns, tun->group));
3251 		break;
3252 
3253 	case TUNSETLINK:
3254 		/* Only allow setting the type when the interface is down */
3255 		if (tun->dev->flags & IFF_UP) {
3256 			netif_info(tun, drv, tun->dev,
3257 				   "Linktype set failed because interface is up\n");
3258 			ret = -EBUSY;
3259 		} else {
3260 			ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE,
3261 						       tun->dev);
3262 			ret = notifier_to_errno(ret);
3263 			if (ret) {
3264 				netif_info(tun, drv, tun->dev,
3265 					   "Refused to change device type\n");
3266 				break;
3267 			}
3268 			tun->dev->type = (int) arg;
3269 			tun->dev->addr_len = tun_get_addr_len(tun->dev->type);
3270 			netif_info(tun, drv, tun->dev, "linktype set to %d\n",
3271 				   tun->dev->type);
3272 			call_netdevice_notifiers(NETDEV_POST_TYPE_CHANGE,
3273 						 tun->dev);
3274 		}
3275 		break;
3276 
3277 	case TUNSETDEBUG:
3278 		tun->msg_enable = (u32)arg;
3279 		break;
3280 
3281 	case TUNSETOFFLOAD:
3282 		ret = set_offload(tun, arg);
3283 		break;
3284 
3285 	case TUNSETTXFILTER:
3286 		/* Can be set only for TAPs */
3287 		ret = -EINVAL;
3288 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3289 			break;
3290 		ret = update_filter(&tun->txflt, (void __user *)arg);
3291 		break;
3292 
3293 	case SIOCGIFHWADDR:
3294 		/* Get hw address */
3295 		netif_get_mac_address(&ifr.ifr_hwaddr, net, tun->dev->name);
3296 		if (copy_to_user(argp, &ifr, ifreq_len))
3297 			ret = -EFAULT;
3298 		break;
3299 
3300 	case SIOCSIFHWADDR:
3301 		/* Set hw address */
3302 		if (tun->dev->addr_len > sizeof(ifr.ifr_hwaddr)) {
3303 			ret = -EINVAL;
3304 			break;
3305 		}
3306 		ret = dev_set_mac_address_user(tun->dev,
3307 					       (struct sockaddr_storage *)&ifr.ifr_hwaddr,
3308 					       NULL);
3309 		break;
3310 
3311 	case TUNGETSNDBUF:
3312 		sndbuf = tfile->socket.sk->sk_sndbuf;
3313 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
3314 			ret = -EFAULT;
3315 		break;
3316 
3317 	case TUNSETSNDBUF:
3318 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
3319 			ret = -EFAULT;
3320 			break;
3321 		}
3322 		if (sndbuf <= 0) {
3323 			ret = -EINVAL;
3324 			break;
3325 		}
3326 
3327 		tun->sndbuf = sndbuf;
3328 		tun_set_sndbuf(tun);
3329 		break;
3330 
3331 	case TUNATTACHFILTER:
3332 		/* Can be set only for TAPs */
3333 		ret = -EINVAL;
3334 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3335 			break;
3336 		ret = -EFAULT;
3337 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
3338 			break;
3339 
3340 		ret = tun_attach_filter(tun);
3341 		break;
3342 
3343 	case TUNDETACHFILTER:
3344 		/* Can be set only for TAPs */
3345 		ret = -EINVAL;
3346 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3347 			break;
3348 		ret = 0;
3349 		tun_detach_filter(tun, tun->numqueues);
3350 		break;
3351 
3352 	case TUNGETFILTER:
3353 		ret = -EINVAL;
3354 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3355 			break;
3356 		ret = -EFAULT;
3357 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
3358 			break;
3359 		ret = 0;
3360 		break;
3361 
3362 	case TUNSETSTEERINGEBPF:
3363 		ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
3364 		break;
3365 
3366 	case TUNSETFILTEREBPF:
3367 		ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3368 		break;
3369 
3370 	case TUNSETCARRIER:
3371 		ret = -EFAULT;
3372 		if (copy_from_user(&carrier, argp, sizeof(carrier)))
3373 			goto unlock;
3374 
3375 		ret = tun_net_change_carrier(tun->dev, (bool)carrier);
3376 		break;
3377 
3378 	case TUNGETDEVNETNS:
3379 		ret = -EPERM;
3380 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3381 			goto unlock;
3382 		ret = open_related_ns(&net->ns, get_net_ns);
3383 		break;
3384 
3385 	default:
3386 		ret = tun_vnet_ioctl(&tun->vnet_hdr_sz, &tun->flags, cmd, argp);
3387 		break;
3388 	}
3389 
3390 	if (do_notify)
3391 		netdev_state_change(tun->dev);
3392 
3393 unlock:
3394 	rtnl_unlock();
3395 	if (tun)
3396 		tun_put(tun);
3397 	return ret;
3398 }
3399 
3400 static long tun_chr_ioctl(struct file *file,
3401 			  unsigned int cmd, unsigned long arg)
3402 {
3403 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
3404 }
3405 
3406 #ifdef CONFIG_COMPAT
3407 static long tun_chr_compat_ioctl(struct file *file,
3408 			 unsigned int cmd, unsigned long arg)
3409 {
3410 	switch (cmd) {
3411 	case TUNSETIFF:
3412 	case TUNGETIFF:
3413 	case TUNSETTXFILTER:
3414 	case TUNGETSNDBUF:
3415 	case TUNSETSNDBUF:
3416 	case SIOCGIFHWADDR:
3417 	case SIOCSIFHWADDR:
3418 		arg = (unsigned long)compat_ptr(arg);
3419 		break;
3420 	default:
3421 		arg = (compat_ulong_t)arg;
3422 		break;
3423 	}
3424 
3425 	/*
3426 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
3427 	 * the end of that structure. All fields that are used in this
3428 	 * driver are compatible though, we don't need to convert the
3429 	 * contents.
3430 	 */
3431 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
3432 }
3433 #endif /* CONFIG_COMPAT */
3434 
3435 static int tun_chr_fasync(int fd, struct file *file, int on)
3436 {
3437 	struct tun_file *tfile = file->private_data;
3438 	int ret;
3439 
3440 	if (on) {
3441 		ret = file_f_owner_allocate(file);
3442 		if (ret)
3443 			goto out;
3444 	}
3445 
3446 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
3447 		goto out;
3448 
3449 	if (on) {
3450 		__f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
3451 		tfile->flags |= TUN_FASYNC;
3452 	} else
3453 		tfile->flags &= ~TUN_FASYNC;
3454 	ret = 0;
3455 out:
3456 	return ret;
3457 }
3458 
3459 static int tun_chr_open(struct inode *inode, struct file * file)
3460 {
3461 	struct net *net = current->nsproxy->net_ns;
3462 	struct tun_file *tfile;
3463 
3464 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
3465 					    &tun_proto, 0);
3466 	if (!tfile)
3467 		return -ENOMEM;
3468 	if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
3469 		sk_free(&tfile->sk);
3470 		return -ENOMEM;
3471 	}
3472 
3473 	mutex_init(&tfile->napi_mutex);
3474 	RCU_INIT_POINTER(tfile->tun, NULL);
3475 	tfile->flags = 0;
3476 	tfile->ifindex = 0;
3477 
3478 	init_waitqueue_head(&tfile->socket.wq.wait);
3479 
3480 	tfile->socket.file = file;
3481 	tfile->socket.ops = &tun_socket_ops;
3482 
3483 	sock_init_data_uid(&tfile->socket, &tfile->sk, current_fsuid());
3484 
3485 	tfile->sk.sk_write_space = tun_sock_write_space;
3486 	tfile->sk.sk_sndbuf = INT_MAX;
3487 
3488 	file->private_data = tfile;
3489 	INIT_LIST_HEAD(&tfile->next);
3490 
3491 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
3492 
3493 	/* tun groks IOCB_NOWAIT just fine, mark it as such */
3494 	file->f_mode |= FMODE_NOWAIT;
3495 	return 0;
3496 }
3497 
3498 static int tun_chr_close(struct inode *inode, struct file *file)
3499 {
3500 	struct tun_file *tfile = file->private_data;
3501 
3502 	tun_detach(tfile, true);
3503 
3504 	return 0;
3505 }
3506 
3507 #ifdef CONFIG_PROC_FS
3508 static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
3509 {
3510 	struct tun_file *tfile = file->private_data;
3511 	struct tun_struct *tun;
3512 	struct ifreq ifr;
3513 
3514 	memset(&ifr, 0, sizeof(ifr));
3515 
3516 	rtnl_lock();
3517 	tun = tun_get(tfile);
3518 	if (tun)
3519 		tun_get_iff(tun, &ifr);
3520 	rtnl_unlock();
3521 
3522 	if (tun)
3523 		tun_put(tun);
3524 
3525 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
3526 }
3527 #endif
3528 
3529 static const struct file_operations tun_fops = {
3530 	.owner	= THIS_MODULE,
3531 	.read_iter  = tun_chr_read_iter,
3532 	.write_iter = tun_chr_write_iter,
3533 	.poll	= tun_chr_poll,
3534 	.unlocked_ioctl	= tun_chr_ioctl,
3535 #ifdef CONFIG_COMPAT
3536 	.compat_ioctl = tun_chr_compat_ioctl,
3537 #endif
3538 	.open	= tun_chr_open,
3539 	.release = tun_chr_close,
3540 	.fasync = tun_chr_fasync,
3541 #ifdef CONFIG_PROC_FS
3542 	.show_fdinfo = tun_chr_show_fdinfo,
3543 #endif
3544 };
3545 
3546 static struct miscdevice tun_miscdev = {
3547 	.minor = TUN_MINOR,
3548 	.name = "tun",
3549 	.nodename = "net/tun",
3550 	.fops = &tun_fops,
3551 };
3552 
3553 /* ethtool interface */
3554 
3555 static void tun_default_link_ksettings(struct net_device *dev,
3556 				       struct ethtool_link_ksettings *cmd)
3557 {
3558 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
3559 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
3560 	cmd->base.speed		= SPEED_10000;
3561 	cmd->base.duplex	= DUPLEX_FULL;
3562 	cmd->base.port		= PORT_TP;
3563 	cmd->base.phy_address	= 0;
3564 	cmd->base.autoneg	= AUTONEG_DISABLE;
3565 }
3566 
3567 static int tun_get_link_ksettings(struct net_device *dev,
3568 				  struct ethtool_link_ksettings *cmd)
3569 {
3570 	struct tun_struct *tun = netdev_priv(dev);
3571 
3572 	memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
3573 	return 0;
3574 }
3575 
3576 static int tun_set_link_ksettings(struct net_device *dev,
3577 				  const struct ethtool_link_ksettings *cmd)
3578 {
3579 	struct tun_struct *tun = netdev_priv(dev);
3580 
3581 	memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
3582 	return 0;
3583 }
3584 
3585 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
3586 {
3587 	struct tun_struct *tun = netdev_priv(dev);
3588 
3589 	strscpy(info->driver, DRV_NAME, sizeof(info->driver));
3590 	strscpy(info->version, DRV_VERSION, sizeof(info->version));
3591 
3592 	switch (tun->flags & TUN_TYPE_MASK) {
3593 	case IFF_TUN:
3594 		strscpy(info->bus_info, "tun", sizeof(info->bus_info));
3595 		break;
3596 	case IFF_TAP:
3597 		strscpy(info->bus_info, "tap", sizeof(info->bus_info));
3598 		break;
3599 	}
3600 }
3601 
3602 static u32 tun_get_msglevel(struct net_device *dev)
3603 {
3604 	struct tun_struct *tun = netdev_priv(dev);
3605 
3606 	return tun->msg_enable;
3607 }
3608 
3609 static void tun_set_msglevel(struct net_device *dev, u32 value)
3610 {
3611 	struct tun_struct *tun = netdev_priv(dev);
3612 
3613 	tun->msg_enable = value;
3614 }
3615 
3616 static int tun_get_coalesce(struct net_device *dev,
3617 			    struct ethtool_coalesce *ec,
3618 			    struct kernel_ethtool_coalesce *kernel_coal,
3619 			    struct netlink_ext_ack *extack)
3620 {
3621 	struct tun_struct *tun = netdev_priv(dev);
3622 
3623 	ec->rx_max_coalesced_frames = tun->rx_batched;
3624 
3625 	return 0;
3626 }
3627 
3628 static int tun_set_coalesce(struct net_device *dev,
3629 			    struct ethtool_coalesce *ec,
3630 			    struct kernel_ethtool_coalesce *kernel_coal,
3631 			    struct netlink_ext_ack *extack)
3632 {
3633 	struct tun_struct *tun = netdev_priv(dev);
3634 
3635 	if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
3636 		tun->rx_batched = NAPI_POLL_WEIGHT;
3637 	else
3638 		tun->rx_batched = ec->rx_max_coalesced_frames;
3639 
3640 	return 0;
3641 }
3642 
3643 static void tun_get_channels(struct net_device *dev,
3644 			     struct ethtool_channels *channels)
3645 {
3646 	struct tun_struct *tun = netdev_priv(dev);
3647 
3648 	channels->combined_count = tun->numqueues;
3649 	channels->max_combined = tun->flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1;
3650 }
3651 
3652 static const struct ethtool_ops tun_ethtool_ops = {
3653 	.supported_coalesce_params = ETHTOOL_COALESCE_RX_MAX_FRAMES,
3654 	.get_drvinfo	= tun_get_drvinfo,
3655 	.get_msglevel	= tun_get_msglevel,
3656 	.set_msglevel	= tun_set_msglevel,
3657 	.get_link	= ethtool_op_get_link,
3658 	.get_channels   = tun_get_channels,
3659 	.get_ts_info	= ethtool_op_get_ts_info,
3660 	.get_coalesce   = tun_get_coalesce,
3661 	.set_coalesce   = tun_set_coalesce,
3662 	.get_link_ksettings = tun_get_link_ksettings,
3663 	.set_link_ksettings = tun_set_link_ksettings,
3664 };
3665 
3666 static int tun_queue_resize(struct tun_struct *tun)
3667 {
3668 	struct net_device *dev = tun->dev;
3669 	struct tun_file *tfile;
3670 	struct ptr_ring **rings;
3671 	int n = tun->numqueues + tun->numdisabled;
3672 	int ret, i;
3673 
3674 	rings = kmalloc_objs(*rings, n);
3675 	if (!rings)
3676 		return -ENOMEM;
3677 
3678 	for (i = 0; i < tun->numqueues; i++) {
3679 		tfile = rtnl_dereference(tun->tfiles[i]);
3680 		rings[i] = &tfile->tx_ring;
3681 	}
3682 	list_for_each_entry(tfile, &tun->disabled, next)
3683 		rings[i++] = &tfile->tx_ring;
3684 
3685 	ret = ptr_ring_resize_multiple_bh(rings, n,
3686 					  dev->tx_queue_len, GFP_KERNEL,
3687 					  tun_ptr_free);
3688 
3689 	if (!ret) {
3690 		for (i = 0; i < tun->numqueues; i++) {
3691 			tfile = rtnl_dereference(tun->tfiles[i]);
3692 			spin_lock(&tfile->tx_ring.consumer_lock);
3693 			netif_wake_subqueue(tun->dev, tfile->queue_index);
3694 			tfile->cons_cnt = 0;
3695 			spin_unlock(&tfile->tx_ring.consumer_lock);
3696 		}
3697 	}
3698 
3699 	kfree(rings);
3700 	return ret;
3701 }
3702 
3703 static int tun_device_event(struct notifier_block *unused,
3704 			    unsigned long event, void *ptr)
3705 {
3706 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3707 	struct tun_struct *tun = netdev_priv(dev);
3708 	int i;
3709 
3710 	if (dev->rtnl_link_ops != &tun_link_ops)
3711 		return NOTIFY_DONE;
3712 
3713 	switch (event) {
3714 	case NETDEV_CHANGE_TX_QUEUE_LEN:
3715 		if (tun_queue_resize(tun))
3716 			return NOTIFY_BAD;
3717 		break;
3718 	case NETDEV_UP:
3719 		for (i = 0; i < tun->numqueues; i++) {
3720 			struct tun_file *tfile;
3721 
3722 			tfile = rtnl_dereference(tun->tfiles[i]);
3723 			tfile->socket.sk->sk_write_space(tfile->socket.sk);
3724 		}
3725 		break;
3726 	default:
3727 		break;
3728 	}
3729 
3730 	return NOTIFY_DONE;
3731 }
3732 
3733 static struct notifier_block tun_notifier_block __read_mostly = {
3734 	.notifier_call	= tun_device_event,
3735 };
3736 
3737 static int __init tun_init(void)
3738 {
3739 	int ret = 0;
3740 
3741 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
3742 
3743 	ret = rtnl_link_register(&tun_link_ops);
3744 	if (ret) {
3745 		pr_err("Can't register link_ops\n");
3746 		goto err_linkops;
3747 	}
3748 
3749 	ret = misc_register(&tun_miscdev);
3750 	if (ret) {
3751 		pr_err("Can't register misc device %d\n", TUN_MINOR);
3752 		goto err_misc;
3753 	}
3754 
3755 	ret = register_netdevice_notifier(&tun_notifier_block);
3756 	if (ret) {
3757 		pr_err("Can't register netdevice notifier\n");
3758 		goto err_notifier;
3759 	}
3760 
3761 	return  0;
3762 
3763 err_notifier:
3764 	misc_deregister(&tun_miscdev);
3765 err_misc:
3766 	rtnl_link_unregister(&tun_link_ops);
3767 err_linkops:
3768 	return ret;
3769 }
3770 
3771 static void __exit tun_cleanup(void)
3772 {
3773 	misc_deregister(&tun_miscdev);
3774 	rtnl_link_unregister(&tun_link_ops);
3775 	unregister_netdevice_notifier(&tun_notifier_block);
3776 }
3777 
3778 /* Get an underlying socket object from tun file.  Returns error unless file is
3779  * attached to a device.  The returned object works like a packet socket, it
3780  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
3781  * holding a reference to the file for as long as the socket is in use. */
3782 struct socket *tun_get_socket(struct file *file)
3783 {
3784 	struct tun_file *tfile;
3785 	if (file->f_op != &tun_fops)
3786 		return ERR_PTR(-EINVAL);
3787 	tfile = file->private_data;
3788 	if (!tfile)
3789 		return ERR_PTR(-EBADFD);
3790 	return &tfile->socket;
3791 }
3792 EXPORT_SYMBOL_GPL(tun_get_socket);
3793 
3794 struct ptr_ring *tun_get_tx_ring(struct file *file)
3795 {
3796 	struct tun_file *tfile;
3797 
3798 	if (file->f_op != &tun_fops)
3799 		return ERR_PTR(-EINVAL);
3800 	tfile = file->private_data;
3801 	if (!tfile)
3802 		return ERR_PTR(-EBADFD);
3803 	return &tfile->tx_ring;
3804 }
3805 EXPORT_SYMBOL_GPL(tun_get_tx_ring);
3806 
3807 /* Callers must hold ring.consumer_lock */
3808 void tun_wake_queue(struct file *file, int consumed)
3809 {
3810 	struct tun_file *tfile;
3811 	struct tun_struct *tun;
3812 
3813 	if (file->f_op != &tun_fops)
3814 		return;
3815 
3816 	tfile = file->private_data;
3817 	if (!tfile)
3818 		return;
3819 
3820 	rcu_read_lock();
3821 
3822 	tun = rcu_dereference(tfile->tun);
3823 	if (tun)
3824 		__tun_wake_queue(tun, tfile, consumed);
3825 
3826 	rcu_read_unlock();
3827 }
3828 EXPORT_SYMBOL_GPL(tun_wake_queue);
3829 
3830 module_init(tun_init);
3831 module_exit(tun_cleanup);
3832 MODULE_DESCRIPTION(DRV_DESCRIPTION);
3833 MODULE_AUTHOR(DRV_COPYRIGHT);
3834 MODULE_LICENSE("GPL");
3835 MODULE_ALIAS_MISCDEV(TUN_MINOR);
3836 MODULE_ALIAS("devname:net/tun");
3837 MODULE_IMPORT_NS("NETDEV_INTERNAL");
3838