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