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