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