xref: /openbmc/linux/drivers/net/tun.c (revision 9dae47aba0a055f761176d9297371d5bb24289ec)
1 /*
2  *  TUN - Universal TUN/TAP device driver.
3  *  Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
16  */
17 
18 /*
19  *  Changes:
20  *
21  *  Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
22  *    Add TUNSETLINK ioctl to set the link encapsulation
23  *
24  *  Mark Smith <markzzzsmith@yahoo.com.au>
25  *    Use eth_random_addr() for tap MAC address.
26  *
27  *  Harald Roelle <harald.roelle@ifi.lmu.de>  2004/04/20
28  *    Fixes in packet dropping, queue length setting and queue wakeup.
29  *    Increased default tx queue length.
30  *    Added ethtool API.
31  *    Minor cleanups
32  *
33  *  Daniel Podlejski <underley@underley.eu.org>
34  *    Modifications for 2.3.99-pre5 kernel.
35  */
36 
37 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
38 
39 #define DRV_NAME	"tun"
40 #define DRV_VERSION	"1.6"
41 #define DRV_DESCRIPTION	"Universal TUN/TAP device driver"
42 #define DRV_COPYRIGHT	"(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
43 
44 #include <linux/module.h>
45 #include <linux/errno.h>
46 #include <linux/kernel.h>
47 #include <linux/sched/signal.h>
48 #include <linux/major.h>
49 #include <linux/slab.h>
50 #include <linux/poll.h>
51 #include <linux/fcntl.h>
52 #include <linux/init.h>
53 #include <linux/skbuff.h>
54 #include <linux/netdevice.h>
55 #include <linux/etherdevice.h>
56 #include <linux/miscdevice.h>
57 #include <linux/ethtool.h>
58 #include <linux/rtnetlink.h>
59 #include <linux/compat.h>
60 #include <linux/if.h>
61 #include <linux/if_arp.h>
62 #include <linux/if_ether.h>
63 #include <linux/if_tun.h>
64 #include <linux/if_vlan.h>
65 #include <linux/crc32.h>
66 #include <linux/nsproxy.h>
67 #include <linux/virtio_net.h>
68 #include <linux/rcupdate.h>
69 #include <net/net_namespace.h>
70 #include <net/netns/generic.h>
71 #include <net/rtnetlink.h>
72 #include <net/sock.h>
73 #include <linux/seq_file.h>
74 #include <linux/uio.h>
75 #include <linux/skb_array.h>
76 #include <linux/bpf.h>
77 #include <linux/bpf_trace.h>
78 #include <linux/mutex.h>
79 
80 #include <linux/uaccess.h>
81 
82 /* Uncomment to enable debugging */
83 /* #define TUN_DEBUG 1 */
84 
85 #ifdef TUN_DEBUG
86 static int debug;
87 
88 #define tun_debug(level, tun, fmt, args...)			\
89 do {								\
90 	if (tun->debug)						\
91 		netdev_printk(level, tun->dev, fmt, ##args);	\
92 } while (0)
93 #define DBG1(level, fmt, args...)				\
94 do {								\
95 	if (debug == 2)						\
96 		printk(level fmt, ##args);			\
97 } while (0)
98 #else
99 #define tun_debug(level, tun, fmt, args...)			\
100 do {								\
101 	if (0)							\
102 		netdev_printk(level, tun->dev, fmt, ##args);	\
103 } while (0)
104 #define DBG1(level, fmt, args...)				\
105 do {								\
106 	if (0)							\
107 		printk(level fmt, ##args);			\
108 } while (0)
109 #endif
110 
111 #define TUN_HEADROOM 256
112 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
113 
114 /* TUN device flags */
115 
116 /* IFF_ATTACH_QUEUE is never stored in device flags,
117  * overload it to mean fasync when stored there.
118  */
119 #define TUN_FASYNC	IFF_ATTACH_QUEUE
120 /* High bits in flags field are unused. */
121 #define TUN_VNET_LE     0x80000000
122 #define TUN_VNET_BE     0x40000000
123 
124 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
125 		      IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
126 
127 #define GOODCOPY_LEN 128
128 
129 #define FLT_EXACT_COUNT 8
130 struct tap_filter {
131 	unsigned int    count;    /* Number of addrs. Zero means disabled */
132 	u32             mask[2];  /* Mask of the hashed addrs */
133 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
134 };
135 
136 /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
137  * to max number of VCPUs in guest. */
138 #define MAX_TAP_QUEUES 256
139 #define MAX_TAP_FLOWS  4096
140 
141 #define TUN_FLOW_EXPIRE (3 * HZ)
142 
143 struct tun_pcpu_stats {
144 	u64 rx_packets;
145 	u64 rx_bytes;
146 	u64 tx_packets;
147 	u64 tx_bytes;
148 	struct u64_stats_sync syncp;
149 	u32 rx_dropped;
150 	u32 tx_dropped;
151 	u32 rx_frame_errors;
152 };
153 
154 /* A tun_file connects an open character device to a tuntap netdevice. It
155  * also contains all socket related structures (except sock_fprog and tap_filter)
156  * to serve as one transmit queue for tuntap device. The sock_fprog and
157  * tap_filter were kept in tun_struct since they were used for filtering for the
158  * netdevice not for a specific queue (at least I didn't see the requirement for
159  * this).
160  *
161  * RCU usage:
162  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
163  * other can only be read while rcu_read_lock or rtnl_lock is held.
164  */
165 struct tun_file {
166 	struct sock sk;
167 	struct socket socket;
168 	struct socket_wq wq;
169 	struct tun_struct __rcu *tun;
170 	struct fasync_struct *fasync;
171 	/* only used for fasnyc */
172 	unsigned int flags;
173 	union {
174 		u16 queue_index;
175 		unsigned int ifindex;
176 	};
177 	struct napi_struct napi;
178 	bool napi_enabled;
179 	struct mutex napi_mutex;	/* Protects access to the above napi */
180 	struct list_head next;
181 	struct tun_struct *detached;
182 	struct skb_array tx_array;
183 	struct xdp_rxq_info xdp_rxq;
184 };
185 
186 struct tun_flow_entry {
187 	struct hlist_node hash_link;
188 	struct rcu_head rcu;
189 	struct tun_struct *tun;
190 
191 	u32 rxhash;
192 	u32 rps_rxhash;
193 	int queue_index;
194 	unsigned long updated;
195 };
196 
197 #define TUN_NUM_FLOW_ENTRIES 1024
198 
199 struct tun_steering_prog {
200 	struct rcu_head rcu;
201 	struct bpf_prog *prog;
202 };
203 
204 /* Since the socket were moved to tun_file, to preserve the behavior of persist
205  * device, socket filter, sndbuf and vnet header size were restore when the
206  * file were attached to a persist device.
207  */
208 struct tun_struct {
209 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
210 	unsigned int            numqueues;
211 	unsigned int 		flags;
212 	kuid_t			owner;
213 	kgid_t			group;
214 
215 	struct net_device	*dev;
216 	netdev_features_t	set_features;
217 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
218 			  NETIF_F_TSO6)
219 
220 	int			align;
221 	int			vnet_hdr_sz;
222 	int			sndbuf;
223 	struct tap_filter	txflt;
224 	struct sock_fprog	fprog;
225 	/* protected by rtnl lock */
226 	bool			filter_attached;
227 #ifdef TUN_DEBUG
228 	int debug;
229 #endif
230 	spinlock_t lock;
231 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
232 	struct timer_list flow_gc_timer;
233 	unsigned long ageing_time;
234 	unsigned int numdisabled;
235 	struct list_head disabled;
236 	void *security;
237 	u32 flow_count;
238 	u32 rx_batched;
239 	struct tun_pcpu_stats __percpu *pcpu_stats;
240 	struct bpf_prog __rcu *xdp_prog;
241 	struct tun_steering_prog __rcu *steering_prog;
242 };
243 
244 static int tun_napi_receive(struct napi_struct *napi, int budget)
245 {
246 	struct tun_file *tfile = container_of(napi, struct tun_file, napi);
247 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
248 	struct sk_buff_head process_queue;
249 	struct sk_buff *skb;
250 	int received = 0;
251 
252 	__skb_queue_head_init(&process_queue);
253 
254 	spin_lock(&queue->lock);
255 	skb_queue_splice_tail_init(queue, &process_queue);
256 	spin_unlock(&queue->lock);
257 
258 	while (received < budget && (skb = __skb_dequeue(&process_queue))) {
259 		napi_gro_receive(napi, skb);
260 		++received;
261 	}
262 
263 	if (!skb_queue_empty(&process_queue)) {
264 		spin_lock(&queue->lock);
265 		skb_queue_splice(&process_queue, queue);
266 		spin_unlock(&queue->lock);
267 	}
268 
269 	return received;
270 }
271 
272 static int tun_napi_poll(struct napi_struct *napi, int budget)
273 {
274 	unsigned int received;
275 
276 	received = tun_napi_receive(napi, budget);
277 
278 	if (received < budget)
279 		napi_complete_done(napi, received);
280 
281 	return received;
282 }
283 
284 static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
285 			  bool napi_en)
286 {
287 	tfile->napi_enabled = napi_en;
288 	if (napi_en) {
289 		netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
290 			       NAPI_POLL_WEIGHT);
291 		napi_enable(&tfile->napi);
292 		mutex_init(&tfile->napi_mutex);
293 	}
294 }
295 
296 static void tun_napi_disable(struct tun_struct *tun, struct tun_file *tfile)
297 {
298 	if (tfile->napi_enabled)
299 		napi_disable(&tfile->napi);
300 }
301 
302 static void tun_napi_del(struct tun_struct *tun, struct tun_file *tfile)
303 {
304 	if (tfile->napi_enabled)
305 		netif_napi_del(&tfile->napi);
306 }
307 
308 static bool tun_napi_frags_enabled(const struct tun_struct *tun)
309 {
310 	return READ_ONCE(tun->flags) & IFF_NAPI_FRAGS;
311 }
312 
313 #ifdef CONFIG_TUN_VNET_CROSS_LE
314 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
315 {
316 	return tun->flags & TUN_VNET_BE ? false :
317 		virtio_legacy_is_little_endian();
318 }
319 
320 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
321 {
322 	int be = !!(tun->flags & TUN_VNET_BE);
323 
324 	if (put_user(be, argp))
325 		return -EFAULT;
326 
327 	return 0;
328 }
329 
330 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
331 {
332 	int be;
333 
334 	if (get_user(be, argp))
335 		return -EFAULT;
336 
337 	if (be)
338 		tun->flags |= TUN_VNET_BE;
339 	else
340 		tun->flags &= ~TUN_VNET_BE;
341 
342 	return 0;
343 }
344 #else
345 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
346 {
347 	return virtio_legacy_is_little_endian();
348 }
349 
350 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
351 {
352 	return -EINVAL;
353 }
354 
355 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
356 {
357 	return -EINVAL;
358 }
359 #endif /* CONFIG_TUN_VNET_CROSS_LE */
360 
361 static inline bool tun_is_little_endian(struct tun_struct *tun)
362 {
363 	return tun->flags & TUN_VNET_LE ||
364 		tun_legacy_is_little_endian(tun);
365 }
366 
367 static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
368 {
369 	return __virtio16_to_cpu(tun_is_little_endian(tun), val);
370 }
371 
372 static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
373 {
374 	return __cpu_to_virtio16(tun_is_little_endian(tun), val);
375 }
376 
377 static inline u32 tun_hashfn(u32 rxhash)
378 {
379 	return rxhash & 0x3ff;
380 }
381 
382 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
383 {
384 	struct tun_flow_entry *e;
385 
386 	hlist_for_each_entry_rcu(e, head, hash_link) {
387 		if (e->rxhash == rxhash)
388 			return e;
389 	}
390 	return NULL;
391 }
392 
393 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
394 					      struct hlist_head *head,
395 					      u32 rxhash, u16 queue_index)
396 {
397 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
398 
399 	if (e) {
400 		tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
401 			  rxhash, queue_index);
402 		e->updated = jiffies;
403 		e->rxhash = rxhash;
404 		e->rps_rxhash = 0;
405 		e->queue_index = queue_index;
406 		e->tun = tun;
407 		hlist_add_head_rcu(&e->hash_link, head);
408 		++tun->flow_count;
409 	}
410 	return e;
411 }
412 
413 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
414 {
415 	tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
416 		  e->rxhash, e->queue_index);
417 	hlist_del_rcu(&e->hash_link);
418 	kfree_rcu(e, rcu);
419 	--tun->flow_count;
420 }
421 
422 static void tun_flow_flush(struct tun_struct *tun)
423 {
424 	int i;
425 
426 	spin_lock_bh(&tun->lock);
427 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
428 		struct tun_flow_entry *e;
429 		struct hlist_node *n;
430 
431 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
432 			tun_flow_delete(tun, e);
433 	}
434 	spin_unlock_bh(&tun->lock);
435 }
436 
437 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
438 {
439 	int i;
440 
441 	spin_lock_bh(&tun->lock);
442 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
443 		struct tun_flow_entry *e;
444 		struct hlist_node *n;
445 
446 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
447 			if (e->queue_index == queue_index)
448 				tun_flow_delete(tun, e);
449 		}
450 	}
451 	spin_unlock_bh(&tun->lock);
452 }
453 
454 static void tun_flow_cleanup(struct timer_list *t)
455 {
456 	struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
457 	unsigned long delay = tun->ageing_time;
458 	unsigned long next_timer = jiffies + delay;
459 	unsigned long count = 0;
460 	int i;
461 
462 	tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
463 
464 	spin_lock(&tun->lock);
465 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
466 		struct tun_flow_entry *e;
467 		struct hlist_node *n;
468 
469 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
470 			unsigned long this_timer;
471 
472 			this_timer = e->updated + delay;
473 			if (time_before_eq(this_timer, jiffies)) {
474 				tun_flow_delete(tun, e);
475 				continue;
476 			}
477 			count++;
478 			if (time_before(this_timer, next_timer))
479 				next_timer = this_timer;
480 		}
481 	}
482 
483 	if (count)
484 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
485 	spin_unlock(&tun->lock);
486 }
487 
488 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
489 			    struct tun_file *tfile)
490 {
491 	struct hlist_head *head;
492 	struct tun_flow_entry *e;
493 	unsigned long delay = tun->ageing_time;
494 	u16 queue_index = tfile->queue_index;
495 
496 	if (!rxhash)
497 		return;
498 	else
499 		head = &tun->flows[tun_hashfn(rxhash)];
500 
501 	rcu_read_lock();
502 
503 	/* We may get a very small possibility of OOO during switching, not
504 	 * worth to optimize.*/
505 	if (tun->numqueues == 1 || tfile->detached)
506 		goto unlock;
507 
508 	e = tun_flow_find(head, rxhash);
509 	if (likely(e)) {
510 		/* TODO: keep queueing to old queue until it's empty? */
511 		e->queue_index = queue_index;
512 		e->updated = jiffies;
513 		sock_rps_record_flow_hash(e->rps_rxhash);
514 	} else {
515 		spin_lock_bh(&tun->lock);
516 		if (!tun_flow_find(head, rxhash) &&
517 		    tun->flow_count < MAX_TAP_FLOWS)
518 			tun_flow_create(tun, head, rxhash, queue_index);
519 
520 		if (!timer_pending(&tun->flow_gc_timer))
521 			mod_timer(&tun->flow_gc_timer,
522 				  round_jiffies_up(jiffies + delay));
523 		spin_unlock_bh(&tun->lock);
524 	}
525 
526 unlock:
527 	rcu_read_unlock();
528 }
529 
530 /**
531  * Save the hash received in the stack receive path and update the
532  * flow_hash table accordingly.
533  */
534 static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
535 {
536 	if (unlikely(e->rps_rxhash != hash))
537 		e->rps_rxhash = hash;
538 }
539 
540 /* We try to identify a flow through its rxhash first. The reason that
541  * we do not check rxq no. is because some cards(e.g 82599), chooses
542  * the rxq based on the txq where the last packet of the flow comes. As
543  * the userspace application move between processors, we may get a
544  * different rxq no. here. If we could not get rxhash, then we would
545  * hope the rxq no. may help here.
546  */
547 static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
548 {
549 	struct tun_flow_entry *e;
550 	u32 txq = 0;
551 	u32 numqueues = 0;
552 
553 	numqueues = READ_ONCE(tun->numqueues);
554 
555 	txq = __skb_get_hash_symmetric(skb);
556 	if (txq) {
557 		e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
558 		if (e) {
559 			tun_flow_save_rps_rxhash(e, txq);
560 			txq = e->queue_index;
561 		} else
562 			/* use multiply and shift instead of expensive divide */
563 			txq = ((u64)txq * numqueues) >> 32;
564 	} else if (likely(skb_rx_queue_recorded(skb))) {
565 		txq = skb_get_rx_queue(skb);
566 		while (unlikely(txq >= numqueues))
567 			txq -= numqueues;
568 	}
569 
570 	return txq;
571 }
572 
573 static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
574 {
575 	struct tun_steering_prog *prog;
576 	u16 ret = 0;
577 
578 	prog = rcu_dereference(tun->steering_prog);
579 	if (prog)
580 		ret = bpf_prog_run_clear_cb(prog->prog, skb);
581 
582 	return ret % tun->numqueues;
583 }
584 
585 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
586 			    void *accel_priv, select_queue_fallback_t fallback)
587 {
588 	struct tun_struct *tun = netdev_priv(dev);
589 	u16 ret;
590 
591 	rcu_read_lock();
592 	if (rcu_dereference(tun->steering_prog))
593 		ret = tun_ebpf_select_queue(tun, skb);
594 	else
595 		ret = tun_automq_select_queue(tun, skb);
596 	rcu_read_unlock();
597 
598 	return ret;
599 }
600 
601 static inline bool tun_not_capable(struct tun_struct *tun)
602 {
603 	const struct cred *cred = current_cred();
604 	struct net *net = dev_net(tun->dev);
605 
606 	return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
607 		  (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
608 		!ns_capable(net->user_ns, CAP_NET_ADMIN);
609 }
610 
611 static void tun_set_real_num_queues(struct tun_struct *tun)
612 {
613 	netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
614 	netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
615 }
616 
617 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
618 {
619 	tfile->detached = tun;
620 	list_add_tail(&tfile->next, &tun->disabled);
621 	++tun->numdisabled;
622 }
623 
624 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
625 {
626 	struct tun_struct *tun = tfile->detached;
627 
628 	tfile->detached = NULL;
629 	list_del_init(&tfile->next);
630 	--tun->numdisabled;
631 	return tun;
632 }
633 
634 static void tun_queue_purge(struct tun_file *tfile)
635 {
636 	struct sk_buff *skb;
637 
638 	while ((skb = skb_array_consume(&tfile->tx_array)) != NULL)
639 		kfree_skb(skb);
640 
641 	skb_queue_purge(&tfile->sk.sk_write_queue);
642 	skb_queue_purge(&tfile->sk.sk_error_queue);
643 }
644 
645 static void __tun_detach(struct tun_file *tfile, bool clean)
646 {
647 	struct tun_file *ntfile;
648 	struct tun_struct *tun;
649 
650 	tun = rtnl_dereference(tfile->tun);
651 
652 	if (tun && clean) {
653 		tun_napi_disable(tun, tfile);
654 		tun_napi_del(tun, tfile);
655 	}
656 
657 	if (tun && !tfile->detached) {
658 		u16 index = tfile->queue_index;
659 		BUG_ON(index >= tun->numqueues);
660 
661 		rcu_assign_pointer(tun->tfiles[index],
662 				   tun->tfiles[tun->numqueues - 1]);
663 		ntfile = rtnl_dereference(tun->tfiles[index]);
664 		ntfile->queue_index = index;
665 
666 		--tun->numqueues;
667 		if (clean) {
668 			RCU_INIT_POINTER(tfile->tun, NULL);
669 			sock_put(&tfile->sk);
670 		} else
671 			tun_disable_queue(tun, tfile);
672 
673 		synchronize_net();
674 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
675 		/* Drop read queue */
676 		tun_queue_purge(tfile);
677 		tun_set_real_num_queues(tun);
678 	} else if (tfile->detached && clean) {
679 		tun = tun_enable_queue(tfile);
680 		sock_put(&tfile->sk);
681 	}
682 
683 	if (clean) {
684 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
685 			netif_carrier_off(tun->dev);
686 
687 			if (!(tun->flags & IFF_PERSIST) &&
688 			    tun->dev->reg_state == NETREG_REGISTERED)
689 				unregister_netdevice(tun->dev);
690 		}
691 		if (tun) {
692 			skb_array_cleanup(&tfile->tx_array);
693 			xdp_rxq_info_unreg(&tfile->xdp_rxq);
694 		}
695 		sock_put(&tfile->sk);
696 	}
697 }
698 
699 static void tun_detach(struct tun_file *tfile, bool clean)
700 {
701 	rtnl_lock();
702 	__tun_detach(tfile, clean);
703 	rtnl_unlock();
704 }
705 
706 static void tun_detach_all(struct net_device *dev)
707 {
708 	struct tun_struct *tun = netdev_priv(dev);
709 	struct tun_file *tfile, *tmp;
710 	int i, n = tun->numqueues;
711 
712 	for (i = 0; i < n; i++) {
713 		tfile = rtnl_dereference(tun->tfiles[i]);
714 		BUG_ON(!tfile);
715 		tun_napi_disable(tun, tfile);
716 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
717 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
718 		RCU_INIT_POINTER(tfile->tun, NULL);
719 		--tun->numqueues;
720 	}
721 	list_for_each_entry(tfile, &tun->disabled, next) {
722 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
723 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
724 		RCU_INIT_POINTER(tfile->tun, NULL);
725 	}
726 	BUG_ON(tun->numqueues != 0);
727 
728 	synchronize_net();
729 	for (i = 0; i < n; i++) {
730 		tfile = rtnl_dereference(tun->tfiles[i]);
731 		tun_napi_del(tun, tfile);
732 		/* Drop read queue */
733 		tun_queue_purge(tfile);
734 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
735 		sock_put(&tfile->sk);
736 	}
737 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
738 		tun_enable_queue(tfile);
739 		tun_queue_purge(tfile);
740 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
741 		sock_put(&tfile->sk);
742 	}
743 	BUG_ON(tun->numdisabled != 0);
744 
745 	if (tun->flags & IFF_PERSIST)
746 		module_put(THIS_MODULE);
747 }
748 
749 static int tun_attach(struct tun_struct *tun, struct file *file,
750 		      bool skip_filter, bool napi)
751 {
752 	struct tun_file *tfile = file->private_data;
753 	struct net_device *dev = tun->dev;
754 	int err;
755 
756 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
757 	if (err < 0)
758 		goto out;
759 
760 	err = -EINVAL;
761 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
762 		goto out;
763 
764 	err = -EBUSY;
765 	if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
766 		goto out;
767 
768 	err = -E2BIG;
769 	if (!tfile->detached &&
770 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
771 		goto out;
772 
773 	err = 0;
774 
775 	/* Re-attach the filter to persist device */
776 	if (!skip_filter && (tun->filter_attached == true)) {
777 		lock_sock(tfile->socket.sk);
778 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
779 		release_sock(tfile->socket.sk);
780 		if (!err)
781 			goto out;
782 	}
783 
784 	if (!tfile->detached &&
785 	    skb_array_init(&tfile->tx_array, dev->tx_queue_len, GFP_KERNEL)) {
786 		err = -ENOMEM;
787 		goto out;
788 	}
789 
790 	tfile->queue_index = tun->numqueues;
791 	tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
792 
793 	if (tfile->detached) {
794 		/* Re-attach detached tfile, updating XDP queue_index */
795 		WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
796 
797 		if (tfile->xdp_rxq.queue_index    != tfile->queue_index)
798 			tfile->xdp_rxq.queue_index = tfile->queue_index;
799 	} else {
800 		/* Setup XDP RX-queue info, for new tfile getting attached */
801 		err = xdp_rxq_info_reg(&tfile->xdp_rxq,
802 				       tun->dev, tfile->queue_index);
803 		if (err < 0)
804 			goto out;
805 		err = 0;
806 	}
807 
808 	rcu_assign_pointer(tfile->tun, tun);
809 	rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
810 	tun->numqueues++;
811 
812 	if (tfile->detached) {
813 		tun_enable_queue(tfile);
814 	} else {
815 		sock_hold(&tfile->sk);
816 		tun_napi_init(tun, tfile, napi);
817 	}
818 
819 	tun_set_real_num_queues(tun);
820 
821 	/* device is allowed to go away first, so no need to hold extra
822 	 * refcnt.
823 	 */
824 
825 out:
826 	return err;
827 }
828 
829 static struct tun_struct *tun_get(struct tun_file *tfile)
830 {
831 	struct tun_struct *tun;
832 
833 	rcu_read_lock();
834 	tun = rcu_dereference(tfile->tun);
835 	if (tun)
836 		dev_hold(tun->dev);
837 	rcu_read_unlock();
838 
839 	return tun;
840 }
841 
842 static void tun_put(struct tun_struct *tun)
843 {
844 	dev_put(tun->dev);
845 }
846 
847 /* TAP filtering */
848 static void addr_hash_set(u32 *mask, const u8 *addr)
849 {
850 	int n = ether_crc(ETH_ALEN, addr) >> 26;
851 	mask[n >> 5] |= (1 << (n & 31));
852 }
853 
854 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
855 {
856 	int n = ether_crc(ETH_ALEN, addr) >> 26;
857 	return mask[n >> 5] & (1 << (n & 31));
858 }
859 
860 static int update_filter(struct tap_filter *filter, void __user *arg)
861 {
862 	struct { u8 u[ETH_ALEN]; } *addr;
863 	struct tun_filter uf;
864 	int err, alen, n, nexact;
865 
866 	if (copy_from_user(&uf, arg, sizeof(uf)))
867 		return -EFAULT;
868 
869 	if (!uf.count) {
870 		/* Disabled */
871 		filter->count = 0;
872 		return 0;
873 	}
874 
875 	alen = ETH_ALEN * uf.count;
876 	addr = memdup_user(arg + sizeof(uf), alen);
877 	if (IS_ERR(addr))
878 		return PTR_ERR(addr);
879 
880 	/* The filter is updated without holding any locks. Which is
881 	 * perfectly safe. We disable it first and in the worst
882 	 * case we'll accept a few undesired packets. */
883 	filter->count = 0;
884 	wmb();
885 
886 	/* Use first set of addresses as an exact filter */
887 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
888 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
889 
890 	nexact = n;
891 
892 	/* Remaining multicast addresses are hashed,
893 	 * unicast will leave the filter disabled. */
894 	memset(filter->mask, 0, sizeof(filter->mask));
895 	for (; n < uf.count; n++) {
896 		if (!is_multicast_ether_addr(addr[n].u)) {
897 			err = 0; /* no filter */
898 			goto free_addr;
899 		}
900 		addr_hash_set(filter->mask, addr[n].u);
901 	}
902 
903 	/* For ALLMULTI just set the mask to all ones.
904 	 * This overrides the mask populated above. */
905 	if ((uf.flags & TUN_FLT_ALLMULTI))
906 		memset(filter->mask, ~0, sizeof(filter->mask));
907 
908 	/* Now enable the filter */
909 	wmb();
910 	filter->count = nexact;
911 
912 	/* Return the number of exact filters */
913 	err = nexact;
914 free_addr:
915 	kfree(addr);
916 	return err;
917 }
918 
919 /* Returns: 0 - drop, !=0 - accept */
920 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
921 {
922 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
923 	 * at this point. */
924 	struct ethhdr *eh = (struct ethhdr *) skb->data;
925 	int i;
926 
927 	/* Exact match */
928 	for (i = 0; i < filter->count; i++)
929 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
930 			return 1;
931 
932 	/* Inexact match (multicast only) */
933 	if (is_multicast_ether_addr(eh->h_dest))
934 		return addr_hash_test(filter->mask, eh->h_dest);
935 
936 	return 0;
937 }
938 
939 /*
940  * Checks whether the packet is accepted or not.
941  * Returns: 0 - drop, !=0 - accept
942  */
943 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
944 {
945 	if (!filter->count)
946 		return 1;
947 
948 	return run_filter(filter, skb);
949 }
950 
951 /* Network device part of the driver */
952 
953 static const struct ethtool_ops tun_ethtool_ops;
954 
955 /* Net device detach from fd. */
956 static void tun_net_uninit(struct net_device *dev)
957 {
958 	tun_detach_all(dev);
959 }
960 
961 /* Net device open. */
962 static int tun_net_open(struct net_device *dev)
963 {
964 	struct tun_struct *tun = netdev_priv(dev);
965 	int i;
966 
967 	netif_tx_start_all_queues(dev);
968 
969 	for (i = 0; i < tun->numqueues; i++) {
970 		struct tun_file *tfile;
971 
972 		tfile = rtnl_dereference(tun->tfiles[i]);
973 		tfile->socket.sk->sk_write_space(tfile->socket.sk);
974 	}
975 
976 	return 0;
977 }
978 
979 /* Net device close. */
980 static int tun_net_close(struct net_device *dev)
981 {
982 	netif_tx_stop_all_queues(dev);
983 	return 0;
984 }
985 
986 /* Net device start xmit */
987 static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
988 {
989 #ifdef CONFIG_RPS
990 	if (tun->numqueues == 1 && static_key_false(&rps_needed)) {
991 		/* Select queue was not called for the skbuff, so we extract the
992 		 * RPS hash and save it into the flow_table here.
993 		 */
994 		__u32 rxhash;
995 
996 		rxhash = __skb_get_hash_symmetric(skb);
997 		if (rxhash) {
998 			struct tun_flow_entry *e;
999 			e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
1000 					rxhash);
1001 			if (e)
1002 				tun_flow_save_rps_rxhash(e, rxhash);
1003 		}
1004 	}
1005 #endif
1006 }
1007 
1008 /* Net device start xmit */
1009 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
1010 {
1011 	struct tun_struct *tun = netdev_priv(dev);
1012 	int txq = skb->queue_mapping;
1013 	struct tun_file *tfile;
1014 
1015 	rcu_read_lock();
1016 	tfile = rcu_dereference(tun->tfiles[txq]);
1017 
1018 	/* Drop packet if interface is not attached */
1019 	if (txq >= tun->numqueues)
1020 		goto drop;
1021 
1022 	if (!rcu_dereference(tun->steering_prog))
1023 		tun_automq_xmit(tun, skb);
1024 
1025 	tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
1026 
1027 	BUG_ON(!tfile);
1028 
1029 	/* Drop if the filter does not like it.
1030 	 * This is a noop if the filter is disabled.
1031 	 * Filter can be enabled only for the TAP devices. */
1032 	if (!check_filter(&tun->txflt, skb))
1033 		goto drop;
1034 
1035 	if (tfile->socket.sk->sk_filter &&
1036 	    sk_filter(tfile->socket.sk, skb))
1037 		goto drop;
1038 
1039 	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
1040 		goto drop;
1041 
1042 	skb_tx_timestamp(skb);
1043 
1044 	/* Orphan the skb - required as we might hang on to it
1045 	 * for indefinite time.
1046 	 */
1047 	skb_orphan(skb);
1048 
1049 	nf_reset(skb);
1050 
1051 	if (skb_array_produce(&tfile->tx_array, skb))
1052 		goto drop;
1053 
1054 	/* Notify and wake up reader process */
1055 	if (tfile->flags & TUN_FASYNC)
1056 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1057 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1058 
1059 	rcu_read_unlock();
1060 	return NETDEV_TX_OK;
1061 
1062 drop:
1063 	this_cpu_inc(tun->pcpu_stats->tx_dropped);
1064 	skb_tx_error(skb);
1065 	kfree_skb(skb);
1066 	rcu_read_unlock();
1067 	return NET_XMIT_DROP;
1068 }
1069 
1070 static void tun_net_mclist(struct net_device *dev)
1071 {
1072 	/*
1073 	 * This callback is supposed to deal with mc filter in
1074 	 * _rx_ path and has nothing to do with the _tx_ path.
1075 	 * In rx path we always accept everything userspace gives us.
1076 	 */
1077 }
1078 
1079 static netdev_features_t tun_net_fix_features(struct net_device *dev,
1080 	netdev_features_t features)
1081 {
1082 	struct tun_struct *tun = netdev_priv(dev);
1083 
1084 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
1085 }
1086 #ifdef CONFIG_NET_POLL_CONTROLLER
1087 static void tun_poll_controller(struct net_device *dev)
1088 {
1089 	/*
1090 	 * Tun only receives frames when:
1091 	 * 1) the char device endpoint gets data from user space
1092 	 * 2) the tun socket gets a sendmsg call from user space
1093 	 * If NAPI is not enabled, since both of those are synchronous
1094 	 * operations, we are guaranteed never to have pending data when we poll
1095 	 * for it so there is nothing to do here but return.
1096 	 * We need this though so netpoll recognizes us as an interface that
1097 	 * supports polling, which enables bridge devices in virt setups to
1098 	 * still use netconsole
1099 	 * If NAPI is enabled, however, we need to schedule polling for all
1100 	 * queues unless we are using napi_gro_frags(), which we call in
1101 	 * process context and not in NAPI context.
1102 	 */
1103 	struct tun_struct *tun = netdev_priv(dev);
1104 
1105 	if (tun->flags & IFF_NAPI) {
1106 		struct tun_file *tfile;
1107 		int i;
1108 
1109 		if (tun_napi_frags_enabled(tun))
1110 			return;
1111 
1112 		rcu_read_lock();
1113 		for (i = 0; i < tun->numqueues; i++) {
1114 			tfile = rcu_dereference(tun->tfiles[i]);
1115 			if (tfile->napi_enabled)
1116 				napi_schedule(&tfile->napi);
1117 		}
1118 		rcu_read_unlock();
1119 	}
1120 	return;
1121 }
1122 #endif
1123 
1124 static void tun_set_headroom(struct net_device *dev, int new_hr)
1125 {
1126 	struct tun_struct *tun = netdev_priv(dev);
1127 
1128 	if (new_hr < NET_SKB_PAD)
1129 		new_hr = NET_SKB_PAD;
1130 
1131 	tun->align = new_hr;
1132 }
1133 
1134 static void
1135 tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1136 {
1137 	u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1138 	struct tun_struct *tun = netdev_priv(dev);
1139 	struct tun_pcpu_stats *p;
1140 	int i;
1141 
1142 	for_each_possible_cpu(i) {
1143 		u64 rxpackets, rxbytes, txpackets, txbytes;
1144 		unsigned int start;
1145 
1146 		p = per_cpu_ptr(tun->pcpu_stats, i);
1147 		do {
1148 			start = u64_stats_fetch_begin(&p->syncp);
1149 			rxpackets	= p->rx_packets;
1150 			rxbytes		= p->rx_bytes;
1151 			txpackets	= p->tx_packets;
1152 			txbytes		= p->tx_bytes;
1153 		} while (u64_stats_fetch_retry(&p->syncp, start));
1154 
1155 		stats->rx_packets	+= rxpackets;
1156 		stats->rx_bytes		+= rxbytes;
1157 		stats->tx_packets	+= txpackets;
1158 		stats->tx_bytes		+= txbytes;
1159 
1160 		/* u32 counters */
1161 		rx_dropped	+= p->rx_dropped;
1162 		rx_frame_errors	+= p->rx_frame_errors;
1163 		tx_dropped	+= p->tx_dropped;
1164 	}
1165 	stats->rx_dropped  = rx_dropped;
1166 	stats->rx_frame_errors = rx_frame_errors;
1167 	stats->tx_dropped = tx_dropped;
1168 }
1169 
1170 static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1171 		       struct netlink_ext_ack *extack)
1172 {
1173 	struct tun_struct *tun = netdev_priv(dev);
1174 	struct bpf_prog *old_prog;
1175 
1176 	old_prog = rtnl_dereference(tun->xdp_prog);
1177 	rcu_assign_pointer(tun->xdp_prog, prog);
1178 	if (old_prog)
1179 		bpf_prog_put(old_prog);
1180 
1181 	return 0;
1182 }
1183 
1184 static u32 tun_xdp_query(struct net_device *dev)
1185 {
1186 	struct tun_struct *tun = netdev_priv(dev);
1187 	const struct bpf_prog *xdp_prog;
1188 
1189 	xdp_prog = rtnl_dereference(tun->xdp_prog);
1190 	if (xdp_prog)
1191 		return xdp_prog->aux->id;
1192 
1193 	return 0;
1194 }
1195 
1196 static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1197 {
1198 	switch (xdp->command) {
1199 	case XDP_SETUP_PROG:
1200 		return tun_xdp_set(dev, xdp->prog, xdp->extack);
1201 	case XDP_QUERY_PROG:
1202 		xdp->prog_id = tun_xdp_query(dev);
1203 		xdp->prog_attached = !!xdp->prog_id;
1204 		return 0;
1205 	default:
1206 		return -EINVAL;
1207 	}
1208 }
1209 
1210 static const struct net_device_ops tun_netdev_ops = {
1211 	.ndo_uninit		= tun_net_uninit,
1212 	.ndo_open		= tun_net_open,
1213 	.ndo_stop		= tun_net_close,
1214 	.ndo_start_xmit		= tun_net_xmit,
1215 	.ndo_fix_features	= tun_net_fix_features,
1216 	.ndo_select_queue	= tun_select_queue,
1217 #ifdef CONFIG_NET_POLL_CONTROLLER
1218 	.ndo_poll_controller	= tun_poll_controller,
1219 #endif
1220 	.ndo_set_rx_headroom	= tun_set_headroom,
1221 	.ndo_get_stats64	= tun_net_get_stats64,
1222 };
1223 
1224 static const struct net_device_ops tap_netdev_ops = {
1225 	.ndo_uninit		= tun_net_uninit,
1226 	.ndo_open		= tun_net_open,
1227 	.ndo_stop		= tun_net_close,
1228 	.ndo_start_xmit		= tun_net_xmit,
1229 	.ndo_fix_features	= tun_net_fix_features,
1230 	.ndo_set_rx_mode	= tun_net_mclist,
1231 	.ndo_set_mac_address	= eth_mac_addr,
1232 	.ndo_validate_addr	= eth_validate_addr,
1233 	.ndo_select_queue	= tun_select_queue,
1234 #ifdef CONFIG_NET_POLL_CONTROLLER
1235 	.ndo_poll_controller	= tun_poll_controller,
1236 #endif
1237 	.ndo_features_check	= passthru_features_check,
1238 	.ndo_set_rx_headroom	= tun_set_headroom,
1239 	.ndo_get_stats64	= tun_net_get_stats64,
1240 	.ndo_bpf		= tun_xdp,
1241 };
1242 
1243 static void tun_flow_init(struct tun_struct *tun)
1244 {
1245 	int i;
1246 
1247 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
1248 		INIT_HLIST_HEAD(&tun->flows[i]);
1249 
1250 	tun->ageing_time = TUN_FLOW_EXPIRE;
1251 	timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1252 	mod_timer(&tun->flow_gc_timer,
1253 		  round_jiffies_up(jiffies + tun->ageing_time));
1254 }
1255 
1256 static void tun_flow_uninit(struct tun_struct *tun)
1257 {
1258 	del_timer_sync(&tun->flow_gc_timer);
1259 	tun_flow_flush(tun);
1260 }
1261 
1262 #define MIN_MTU 68
1263 #define MAX_MTU 65535
1264 
1265 /* Initialize net device. */
1266 static void tun_net_init(struct net_device *dev)
1267 {
1268 	struct tun_struct *tun = netdev_priv(dev);
1269 
1270 	switch (tun->flags & TUN_TYPE_MASK) {
1271 	case IFF_TUN:
1272 		dev->netdev_ops = &tun_netdev_ops;
1273 
1274 		/* Point-to-Point TUN Device */
1275 		dev->hard_header_len = 0;
1276 		dev->addr_len = 0;
1277 		dev->mtu = 1500;
1278 
1279 		/* Zero header length */
1280 		dev->type = ARPHRD_NONE;
1281 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
1282 		break;
1283 
1284 	case IFF_TAP:
1285 		dev->netdev_ops = &tap_netdev_ops;
1286 		/* Ethernet TAP Device */
1287 		ether_setup(dev);
1288 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1289 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
1290 
1291 		eth_hw_addr_random(dev);
1292 
1293 		break;
1294 	}
1295 
1296 	dev->min_mtu = MIN_MTU;
1297 	dev->max_mtu = MAX_MTU - dev->hard_header_len;
1298 }
1299 
1300 /* Character device part */
1301 
1302 /* Poll */
1303 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
1304 {
1305 	struct tun_file *tfile = file->private_data;
1306 	struct tun_struct *tun = tun_get(tfile);
1307 	struct sock *sk;
1308 	unsigned int mask = 0;
1309 
1310 	if (!tun)
1311 		return POLLERR;
1312 
1313 	sk = tfile->socket.sk;
1314 
1315 	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
1316 
1317 	poll_wait(file, sk_sleep(sk), wait);
1318 
1319 	if (!skb_array_empty(&tfile->tx_array))
1320 		mask |= POLLIN | POLLRDNORM;
1321 
1322 	if (tun->dev->flags & IFF_UP &&
1323 	    (sock_writeable(sk) ||
1324 	     (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1325 	      sock_writeable(sk))))
1326 		mask |= POLLOUT | POLLWRNORM;
1327 
1328 	if (tun->dev->reg_state != NETREG_REGISTERED)
1329 		mask = POLLERR;
1330 
1331 	tun_put(tun);
1332 	return mask;
1333 }
1334 
1335 static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
1336 					    size_t len,
1337 					    const struct iov_iter *it)
1338 {
1339 	struct sk_buff *skb;
1340 	size_t linear;
1341 	int err;
1342 	int i;
1343 
1344 	if (it->nr_segs > MAX_SKB_FRAGS + 1)
1345 		return ERR_PTR(-ENOMEM);
1346 
1347 	local_bh_disable();
1348 	skb = napi_get_frags(&tfile->napi);
1349 	local_bh_enable();
1350 	if (!skb)
1351 		return ERR_PTR(-ENOMEM);
1352 
1353 	linear = iov_iter_single_seg_count(it);
1354 	err = __skb_grow(skb, linear);
1355 	if (err)
1356 		goto free;
1357 
1358 	skb->len = len;
1359 	skb->data_len = len - linear;
1360 	skb->truesize += skb->data_len;
1361 
1362 	for (i = 1; i < it->nr_segs; i++) {
1363 		size_t fragsz = it->iov[i].iov_len;
1364 		unsigned long offset;
1365 		struct page *page;
1366 		void *data;
1367 
1368 		if (fragsz == 0 || fragsz > PAGE_SIZE) {
1369 			err = -EINVAL;
1370 			goto free;
1371 		}
1372 
1373 		local_bh_disable();
1374 		data = napi_alloc_frag(fragsz);
1375 		local_bh_enable();
1376 		if (!data) {
1377 			err = -ENOMEM;
1378 			goto free;
1379 		}
1380 
1381 		page = virt_to_head_page(data);
1382 		offset = data - page_address(page);
1383 		skb_fill_page_desc(skb, i - 1, page, offset, fragsz);
1384 	}
1385 
1386 	return skb;
1387 free:
1388 	/* frees skb and all frags allocated with napi_alloc_frag() */
1389 	napi_free_frags(&tfile->napi);
1390 	return ERR_PTR(err);
1391 }
1392 
1393 /* prepad is the amount to reserve at front.  len is length after that.
1394  * linear is a hint as to how much to copy (usually headers). */
1395 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
1396 				     size_t prepad, size_t len,
1397 				     size_t linear, int noblock)
1398 {
1399 	struct sock *sk = tfile->socket.sk;
1400 	struct sk_buff *skb;
1401 	int err;
1402 
1403 	/* Under a page?  Don't bother with paged skb. */
1404 	if (prepad + len < PAGE_SIZE || !linear)
1405 		linear = len;
1406 
1407 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
1408 				   &err, 0);
1409 	if (!skb)
1410 		return ERR_PTR(err);
1411 
1412 	skb_reserve(skb, prepad);
1413 	skb_put(skb, linear);
1414 	skb->data_len = len - linear;
1415 	skb->len += len - linear;
1416 
1417 	return skb;
1418 }
1419 
1420 static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
1421 			   struct sk_buff *skb, int more)
1422 {
1423 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1424 	struct sk_buff_head process_queue;
1425 	u32 rx_batched = tun->rx_batched;
1426 	bool rcv = false;
1427 
1428 	if (!rx_batched || (!more && skb_queue_empty(queue))) {
1429 		local_bh_disable();
1430 		netif_receive_skb(skb);
1431 		local_bh_enable();
1432 		return;
1433 	}
1434 
1435 	spin_lock(&queue->lock);
1436 	if (!more || skb_queue_len(queue) == rx_batched) {
1437 		__skb_queue_head_init(&process_queue);
1438 		skb_queue_splice_tail_init(queue, &process_queue);
1439 		rcv = true;
1440 	} else {
1441 		__skb_queue_tail(queue, skb);
1442 	}
1443 	spin_unlock(&queue->lock);
1444 
1445 	if (rcv) {
1446 		struct sk_buff *nskb;
1447 
1448 		local_bh_disable();
1449 		while ((nskb = __skb_dequeue(&process_queue)))
1450 			netif_receive_skb(nskb);
1451 		netif_receive_skb(skb);
1452 		local_bh_enable();
1453 	}
1454 }
1455 
1456 static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
1457 			      int len, int noblock, bool zerocopy)
1458 {
1459 	if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
1460 		return false;
1461 
1462 	if (tfile->socket.sk->sk_sndbuf != INT_MAX)
1463 		return false;
1464 
1465 	if (!noblock)
1466 		return false;
1467 
1468 	if (zerocopy)
1469 		return false;
1470 
1471 	if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
1472 	    SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
1473 		return false;
1474 
1475 	return true;
1476 }
1477 
1478 static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1479 				     struct tun_file *tfile,
1480 				     struct iov_iter *from,
1481 				     struct virtio_net_hdr *hdr,
1482 				     int len, int *skb_xdp)
1483 {
1484 	struct page_frag *alloc_frag = &current->task_frag;
1485 	struct sk_buff *skb;
1486 	struct bpf_prog *xdp_prog;
1487 	int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1488 	unsigned int delta = 0;
1489 	char *buf;
1490 	size_t copied;
1491 	bool xdp_xmit = false;
1492 	int err, pad = TUN_RX_PAD;
1493 
1494 	rcu_read_lock();
1495 	xdp_prog = rcu_dereference(tun->xdp_prog);
1496 	if (xdp_prog)
1497 		pad += TUN_HEADROOM;
1498 	buflen += SKB_DATA_ALIGN(len + pad);
1499 	rcu_read_unlock();
1500 
1501 	alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
1502 	if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
1503 		return ERR_PTR(-ENOMEM);
1504 
1505 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1506 	copied = copy_page_from_iter(alloc_frag->page,
1507 				     alloc_frag->offset + pad,
1508 				     len, from);
1509 	if (copied != len)
1510 		return ERR_PTR(-EFAULT);
1511 
1512 	/* There's a small window that XDP may be set after the check
1513 	 * of xdp_prog above, this should be rare and for simplicity
1514 	 * we do XDP on skb in case the headroom is not enough.
1515 	 */
1516 	if (hdr->gso_type || !xdp_prog)
1517 		*skb_xdp = 1;
1518 	else
1519 		*skb_xdp = 0;
1520 
1521 	rcu_read_lock();
1522 	xdp_prog = rcu_dereference(tun->xdp_prog);
1523 	if (xdp_prog && !*skb_xdp) {
1524 		struct xdp_buff xdp;
1525 		void *orig_data;
1526 		u32 act;
1527 
1528 		xdp.data_hard_start = buf;
1529 		xdp.data = buf + pad;
1530 		xdp_set_data_meta_invalid(&xdp);
1531 		xdp.data_end = xdp.data + len;
1532 		xdp.rxq = &tfile->xdp_rxq;
1533 		orig_data = xdp.data;
1534 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
1535 
1536 		switch (act) {
1537 		case XDP_REDIRECT:
1538 			get_page(alloc_frag->page);
1539 			alloc_frag->offset += buflen;
1540 			err = xdp_do_redirect(tun->dev, &xdp, xdp_prog);
1541 			if (err)
1542 				goto err_redirect;
1543 			rcu_read_unlock();
1544 			return NULL;
1545 		case XDP_TX:
1546 			xdp_xmit = true;
1547 			/* fall through */
1548 		case XDP_PASS:
1549 			delta = orig_data - xdp.data;
1550 			break;
1551 		default:
1552 			bpf_warn_invalid_xdp_action(act);
1553 			/* fall through */
1554 		case XDP_ABORTED:
1555 			trace_xdp_exception(tun->dev, xdp_prog, act);
1556 			/* fall through */
1557 		case XDP_DROP:
1558 			goto err_xdp;
1559 		}
1560 	}
1561 
1562 	skb = build_skb(buf, buflen);
1563 	if (!skb) {
1564 		rcu_read_unlock();
1565 		return ERR_PTR(-ENOMEM);
1566 	}
1567 
1568 	skb_reserve(skb, pad - delta);
1569 	skb_put(skb, len + delta);
1570 	get_page(alloc_frag->page);
1571 	alloc_frag->offset += buflen;
1572 
1573 	if (xdp_xmit) {
1574 		skb->dev = tun->dev;
1575 		generic_xdp_tx(skb, xdp_prog);
1576 		rcu_read_unlock();
1577 		return NULL;
1578 	}
1579 
1580 	rcu_read_unlock();
1581 
1582 	return skb;
1583 
1584 err_redirect:
1585 	put_page(alloc_frag->page);
1586 err_xdp:
1587 	rcu_read_unlock();
1588 	this_cpu_inc(tun->pcpu_stats->rx_dropped);
1589 	return NULL;
1590 }
1591 
1592 /* Get packet from user space buffer */
1593 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1594 			    void *msg_control, struct iov_iter *from,
1595 			    int noblock, bool more)
1596 {
1597 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1598 	struct sk_buff *skb;
1599 	size_t total_len = iov_iter_count(from);
1600 	size_t len = total_len, align = tun->align, linear;
1601 	struct virtio_net_hdr gso = { 0 };
1602 	struct tun_pcpu_stats *stats;
1603 	int good_linear;
1604 	int copylen;
1605 	bool zerocopy = false;
1606 	int err;
1607 	u32 rxhash = 0;
1608 	int skb_xdp = 1;
1609 	bool frags = tun_napi_frags_enabled(tun);
1610 
1611 	if (!(tun->dev->flags & IFF_UP))
1612 		return -EIO;
1613 
1614 	if (!(tun->flags & IFF_NO_PI)) {
1615 		if (len < sizeof(pi))
1616 			return -EINVAL;
1617 		len -= sizeof(pi);
1618 
1619 		if (!copy_from_iter_full(&pi, sizeof(pi), from))
1620 			return -EFAULT;
1621 	}
1622 
1623 	if (tun->flags & IFF_VNET_HDR) {
1624 		int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1625 
1626 		if (len < vnet_hdr_sz)
1627 			return -EINVAL;
1628 		len -= vnet_hdr_sz;
1629 
1630 		if (!copy_from_iter_full(&gso, sizeof(gso), from))
1631 			return -EFAULT;
1632 
1633 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1634 		    tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
1635 			gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
1636 
1637 		if (tun16_to_cpu(tun, gso.hdr_len) > len)
1638 			return -EINVAL;
1639 		iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1640 	}
1641 
1642 	if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1643 		align += NET_IP_ALIGN;
1644 		if (unlikely(len < ETH_HLEN ||
1645 			     (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1646 			return -EINVAL;
1647 	}
1648 
1649 	good_linear = SKB_MAX_HEAD(align);
1650 
1651 	if (msg_control) {
1652 		struct iov_iter i = *from;
1653 
1654 		/* There are 256 bytes to be copied in skb, so there is
1655 		 * enough room for skb expand head in case it is used.
1656 		 * The rest of the buffer is mapped from userspace.
1657 		 */
1658 		copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
1659 		if (copylen > good_linear)
1660 			copylen = good_linear;
1661 		linear = copylen;
1662 		iov_iter_advance(&i, copylen);
1663 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
1664 			zerocopy = true;
1665 	}
1666 
1667 	if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
1668 		/* For the packet that is not easy to be processed
1669 		 * (e.g gso or jumbo packet), we will do it at after
1670 		 * skb was created with generic XDP routine.
1671 		 */
1672 		skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
1673 		if (IS_ERR(skb)) {
1674 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
1675 			return PTR_ERR(skb);
1676 		}
1677 		if (!skb)
1678 			return total_len;
1679 	} else {
1680 		if (!zerocopy) {
1681 			copylen = len;
1682 			if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
1683 				linear = good_linear;
1684 			else
1685 				linear = tun16_to_cpu(tun, gso.hdr_len);
1686 		}
1687 
1688 		if (frags) {
1689 			mutex_lock(&tfile->napi_mutex);
1690 			skb = tun_napi_alloc_frags(tfile, copylen, from);
1691 			/* tun_napi_alloc_frags() enforces a layout for the skb.
1692 			 * If zerocopy is enabled, then this layout will be
1693 			 * overwritten by zerocopy_sg_from_iter().
1694 			 */
1695 			zerocopy = false;
1696 		} else {
1697 			skb = tun_alloc_skb(tfile, align, copylen, linear,
1698 					    noblock);
1699 		}
1700 
1701 		if (IS_ERR(skb)) {
1702 			if (PTR_ERR(skb) != -EAGAIN)
1703 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
1704 			if (frags)
1705 				mutex_unlock(&tfile->napi_mutex);
1706 			return PTR_ERR(skb);
1707 		}
1708 
1709 		if (zerocopy)
1710 			err = zerocopy_sg_from_iter(skb, from);
1711 		else
1712 			err = skb_copy_datagram_from_iter(skb, 0, from, len);
1713 
1714 		if (err) {
1715 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
1716 			kfree_skb(skb);
1717 			if (frags) {
1718 				tfile->napi.skb = NULL;
1719 				mutex_unlock(&tfile->napi_mutex);
1720 			}
1721 
1722 			return -EFAULT;
1723 		}
1724 	}
1725 
1726 	if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1727 		this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1728 		kfree_skb(skb);
1729 		if (frags) {
1730 			tfile->napi.skb = NULL;
1731 			mutex_unlock(&tfile->napi_mutex);
1732 		}
1733 
1734 		return -EINVAL;
1735 	}
1736 
1737 	switch (tun->flags & TUN_TYPE_MASK) {
1738 	case IFF_TUN:
1739 		if (tun->flags & IFF_NO_PI) {
1740 			u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
1741 
1742 			switch (ip_version) {
1743 			case 4:
1744 				pi.proto = htons(ETH_P_IP);
1745 				break;
1746 			case 6:
1747 				pi.proto = htons(ETH_P_IPV6);
1748 				break;
1749 			default:
1750 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
1751 				kfree_skb(skb);
1752 				return -EINVAL;
1753 			}
1754 		}
1755 
1756 		skb_reset_mac_header(skb);
1757 		skb->protocol = pi.proto;
1758 		skb->dev = tun->dev;
1759 		break;
1760 	case IFF_TAP:
1761 		if (!frags)
1762 			skb->protocol = eth_type_trans(skb, tun->dev);
1763 		break;
1764 	}
1765 
1766 	/* copy skb_ubuf_info for callback when skb has no error */
1767 	if (zerocopy) {
1768 		skb_shinfo(skb)->destructor_arg = msg_control;
1769 		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1770 		skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1771 	} else if (msg_control) {
1772 		struct ubuf_info *uarg = msg_control;
1773 		uarg->callback(uarg, false);
1774 	}
1775 
1776 	skb_reset_network_header(skb);
1777 	skb_probe_transport_header(skb, 0);
1778 
1779 	if (skb_xdp) {
1780 		struct bpf_prog *xdp_prog;
1781 		int ret;
1782 
1783 		rcu_read_lock();
1784 		xdp_prog = rcu_dereference(tun->xdp_prog);
1785 		if (xdp_prog) {
1786 			ret = do_xdp_generic(xdp_prog, skb);
1787 			if (ret != XDP_PASS) {
1788 				rcu_read_unlock();
1789 				return total_len;
1790 			}
1791 		}
1792 		rcu_read_unlock();
1793 	}
1794 
1795 	rcu_read_lock();
1796 	if (!rcu_dereference(tun->steering_prog))
1797 		rxhash = __skb_get_hash_symmetric(skb);
1798 	rcu_read_unlock();
1799 
1800 	if (frags) {
1801 		/* Exercise flow dissector code path. */
1802 		u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
1803 
1804 		if (unlikely(headlen > skb_headlen(skb))) {
1805 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
1806 			napi_free_frags(&tfile->napi);
1807 			mutex_unlock(&tfile->napi_mutex);
1808 			WARN_ON(1);
1809 			return -ENOMEM;
1810 		}
1811 
1812 		local_bh_disable();
1813 		napi_gro_frags(&tfile->napi);
1814 		local_bh_enable();
1815 		mutex_unlock(&tfile->napi_mutex);
1816 	} else if (tfile->napi_enabled) {
1817 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1818 		int queue_len;
1819 
1820 		spin_lock_bh(&queue->lock);
1821 		__skb_queue_tail(queue, skb);
1822 		queue_len = skb_queue_len(queue);
1823 		spin_unlock(&queue->lock);
1824 
1825 		if (!more || queue_len > NAPI_POLL_WEIGHT)
1826 			napi_schedule(&tfile->napi);
1827 
1828 		local_bh_enable();
1829 	} else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
1830 		tun_rx_batched(tun, tfile, skb, more);
1831 	} else {
1832 		netif_rx_ni(skb);
1833 	}
1834 
1835 	stats = get_cpu_ptr(tun->pcpu_stats);
1836 	u64_stats_update_begin(&stats->syncp);
1837 	stats->rx_packets++;
1838 	stats->rx_bytes += len;
1839 	u64_stats_update_end(&stats->syncp);
1840 	put_cpu_ptr(stats);
1841 
1842 	if (rxhash)
1843 		tun_flow_update(tun, rxhash, tfile);
1844 
1845 	return total_len;
1846 }
1847 
1848 static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
1849 {
1850 	struct file *file = iocb->ki_filp;
1851 	struct tun_file *tfile = file->private_data;
1852 	struct tun_struct *tun = tun_get(tfile);
1853 	ssize_t result;
1854 
1855 	if (!tun)
1856 		return -EBADFD;
1857 
1858 	result = tun_get_user(tun, tfile, NULL, from,
1859 			      file->f_flags & O_NONBLOCK, false);
1860 
1861 	tun_put(tun);
1862 	return result;
1863 }
1864 
1865 /* Put packet to the user space buffer */
1866 static ssize_t tun_put_user(struct tun_struct *tun,
1867 			    struct tun_file *tfile,
1868 			    struct sk_buff *skb,
1869 			    struct iov_iter *iter)
1870 {
1871 	struct tun_pi pi = { 0, skb->protocol };
1872 	struct tun_pcpu_stats *stats;
1873 	ssize_t total;
1874 	int vlan_offset = 0;
1875 	int vlan_hlen = 0;
1876 	int vnet_hdr_sz = 0;
1877 
1878 	if (skb_vlan_tag_present(skb))
1879 		vlan_hlen = VLAN_HLEN;
1880 
1881 	if (tun->flags & IFF_VNET_HDR)
1882 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1883 
1884 	total = skb->len + vlan_hlen + vnet_hdr_sz;
1885 
1886 	if (!(tun->flags & IFF_NO_PI)) {
1887 		if (iov_iter_count(iter) < sizeof(pi))
1888 			return -EINVAL;
1889 
1890 		total += sizeof(pi);
1891 		if (iov_iter_count(iter) < total) {
1892 			/* Packet will be striped */
1893 			pi.flags |= TUN_PKT_STRIP;
1894 		}
1895 
1896 		if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
1897 			return -EFAULT;
1898 	}
1899 
1900 	if (vnet_hdr_sz) {
1901 		struct virtio_net_hdr gso;
1902 
1903 		if (iov_iter_count(iter) < vnet_hdr_sz)
1904 			return -EINVAL;
1905 
1906 		if (virtio_net_hdr_from_skb(skb, &gso,
1907 					    tun_is_little_endian(tun), true)) {
1908 			struct skb_shared_info *sinfo = skb_shinfo(skb);
1909 			pr_err("unexpected GSO type: "
1910 			       "0x%x, gso_size %d, hdr_len %d\n",
1911 			       sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
1912 			       tun16_to_cpu(tun, gso.hdr_len));
1913 			print_hex_dump(KERN_ERR, "tun: ",
1914 				       DUMP_PREFIX_NONE,
1915 				       16, 1, skb->head,
1916 				       min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
1917 			WARN_ON_ONCE(1);
1918 			return -EINVAL;
1919 		}
1920 
1921 		if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
1922 			return -EFAULT;
1923 
1924 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
1925 	}
1926 
1927 	if (vlan_hlen) {
1928 		int ret;
1929 		struct {
1930 			__be16 h_vlan_proto;
1931 			__be16 h_vlan_TCI;
1932 		} veth;
1933 
1934 		veth.h_vlan_proto = skb->vlan_proto;
1935 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
1936 
1937 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
1938 
1939 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
1940 		if (ret || !iov_iter_count(iter))
1941 			goto done;
1942 
1943 		ret = copy_to_iter(&veth, sizeof(veth), iter);
1944 		if (ret != sizeof(veth) || !iov_iter_count(iter))
1945 			goto done;
1946 	}
1947 
1948 	skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
1949 
1950 done:
1951 	/* caller is in process context, */
1952 	stats = get_cpu_ptr(tun->pcpu_stats);
1953 	u64_stats_update_begin(&stats->syncp);
1954 	stats->tx_packets++;
1955 	stats->tx_bytes += skb->len + vlan_hlen;
1956 	u64_stats_update_end(&stats->syncp);
1957 	put_cpu_ptr(tun->pcpu_stats);
1958 
1959 	return total;
1960 }
1961 
1962 static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock,
1963 				     int *err)
1964 {
1965 	DECLARE_WAITQUEUE(wait, current);
1966 	struct sk_buff *skb = NULL;
1967 	int error = 0;
1968 
1969 	skb = skb_array_consume(&tfile->tx_array);
1970 	if (skb)
1971 		goto out;
1972 	if (noblock) {
1973 		error = -EAGAIN;
1974 		goto out;
1975 	}
1976 
1977 	add_wait_queue(&tfile->wq.wait, &wait);
1978 	current->state = TASK_INTERRUPTIBLE;
1979 
1980 	while (1) {
1981 		skb = skb_array_consume(&tfile->tx_array);
1982 		if (skb)
1983 			break;
1984 		if (signal_pending(current)) {
1985 			error = -ERESTARTSYS;
1986 			break;
1987 		}
1988 		if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
1989 			error = -EFAULT;
1990 			break;
1991 		}
1992 
1993 		schedule();
1994 	}
1995 
1996 	current->state = TASK_RUNNING;
1997 	remove_wait_queue(&tfile->wq.wait, &wait);
1998 
1999 out:
2000 	*err = error;
2001 	return skb;
2002 }
2003 
2004 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
2005 			   struct iov_iter *to,
2006 			   int noblock, struct sk_buff *skb)
2007 {
2008 	ssize_t ret;
2009 	int err;
2010 
2011 	tun_debug(KERN_INFO, tun, "tun_do_read\n");
2012 
2013 	if (!iov_iter_count(to)) {
2014 		if (skb)
2015 			kfree_skb(skb);
2016 		return 0;
2017 	}
2018 
2019 	if (!skb) {
2020 		/* Read frames from ring */
2021 		skb = tun_ring_recv(tfile, noblock, &err);
2022 		if (!skb)
2023 			return err;
2024 	}
2025 
2026 	ret = tun_put_user(tun, tfile, skb, to);
2027 	if (unlikely(ret < 0))
2028 		kfree_skb(skb);
2029 	else
2030 		consume_skb(skb);
2031 
2032 	return ret;
2033 }
2034 
2035 static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
2036 {
2037 	struct file *file = iocb->ki_filp;
2038 	struct tun_file *tfile = file->private_data;
2039 	struct tun_struct *tun = tun_get(tfile);
2040 	ssize_t len = iov_iter_count(to), ret;
2041 
2042 	if (!tun)
2043 		return -EBADFD;
2044 	ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
2045 	ret = min_t(ssize_t, ret, len);
2046 	if (ret > 0)
2047 		iocb->ki_pos = ret;
2048 	tun_put(tun);
2049 	return ret;
2050 }
2051 
2052 static void tun_steering_prog_free(struct rcu_head *rcu)
2053 {
2054 	struct tun_steering_prog *prog = container_of(rcu,
2055 					 struct tun_steering_prog, rcu);
2056 
2057 	bpf_prog_destroy(prog->prog);
2058 	kfree(prog);
2059 }
2060 
2061 static int __tun_set_steering_ebpf(struct tun_struct *tun,
2062 				   struct bpf_prog *prog)
2063 {
2064 	struct tun_steering_prog *old, *new = NULL;
2065 
2066 	if (prog) {
2067 		new = kmalloc(sizeof(*new), GFP_KERNEL);
2068 		if (!new)
2069 			return -ENOMEM;
2070 		new->prog = prog;
2071 	}
2072 
2073 	spin_lock_bh(&tun->lock);
2074 	old = rcu_dereference_protected(tun->steering_prog,
2075 					lockdep_is_held(&tun->lock));
2076 	rcu_assign_pointer(tun->steering_prog, new);
2077 	spin_unlock_bh(&tun->lock);
2078 
2079 	if (old)
2080 		call_rcu(&old->rcu, tun_steering_prog_free);
2081 
2082 	return 0;
2083 }
2084 
2085 static void tun_free_netdev(struct net_device *dev)
2086 {
2087 	struct tun_struct *tun = netdev_priv(dev);
2088 
2089 	BUG_ON(!(list_empty(&tun->disabled)));
2090 	free_percpu(tun->pcpu_stats);
2091 	tun_flow_uninit(tun);
2092 	security_tun_dev_free_security(tun->security);
2093 	__tun_set_steering_ebpf(tun, NULL);
2094 }
2095 
2096 static void tun_setup(struct net_device *dev)
2097 {
2098 	struct tun_struct *tun = netdev_priv(dev);
2099 
2100 	tun->owner = INVALID_UID;
2101 	tun->group = INVALID_GID;
2102 
2103 	dev->ethtool_ops = &tun_ethtool_ops;
2104 	dev->needs_free_netdev = true;
2105 	dev->priv_destructor = tun_free_netdev;
2106 	/* We prefer our own queue length */
2107 	dev->tx_queue_len = TUN_READQ_SIZE;
2108 }
2109 
2110 /* Trivial set of netlink ops to allow deleting tun or tap
2111  * device with netlink.
2112  */
2113 static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2114 			struct netlink_ext_ack *extack)
2115 {
2116 	return -EINVAL;
2117 }
2118 
2119 static struct rtnl_link_ops tun_link_ops __read_mostly = {
2120 	.kind		= DRV_NAME,
2121 	.priv_size	= sizeof(struct tun_struct),
2122 	.setup		= tun_setup,
2123 	.validate	= tun_validate,
2124 };
2125 
2126 static void tun_sock_write_space(struct sock *sk)
2127 {
2128 	struct tun_file *tfile;
2129 	wait_queue_head_t *wqueue;
2130 
2131 	if (!sock_writeable(sk))
2132 		return;
2133 
2134 	if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
2135 		return;
2136 
2137 	wqueue = sk_sleep(sk);
2138 	if (wqueue && waitqueue_active(wqueue))
2139 		wake_up_interruptible_sync_poll(wqueue, POLLOUT |
2140 						POLLWRNORM | POLLWRBAND);
2141 
2142 	tfile = container_of(sk, struct tun_file, sk);
2143 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
2144 }
2145 
2146 static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
2147 {
2148 	int ret;
2149 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2150 	struct tun_struct *tun = tun_get(tfile);
2151 
2152 	if (!tun)
2153 		return -EBADFD;
2154 
2155 	ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
2156 			   m->msg_flags & MSG_DONTWAIT,
2157 			   m->msg_flags & MSG_MORE);
2158 	tun_put(tun);
2159 	return ret;
2160 }
2161 
2162 static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
2163 		       int flags)
2164 {
2165 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2166 	struct tun_struct *tun = tun_get(tfile);
2167 	struct sk_buff *skb = m->msg_control;
2168 	int ret;
2169 
2170 	if (!tun) {
2171 		ret = -EBADFD;
2172 		goto out_free_skb;
2173 	}
2174 
2175 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
2176 		ret = -EINVAL;
2177 		goto out_put_tun;
2178 	}
2179 	if (flags & MSG_ERRQUEUE) {
2180 		ret = sock_recv_errqueue(sock->sk, m, total_len,
2181 					 SOL_PACKET, TUN_TX_TIMESTAMP);
2182 		goto out;
2183 	}
2184 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, skb);
2185 	if (ret > (ssize_t)total_len) {
2186 		m->msg_flags |= MSG_TRUNC;
2187 		ret = flags & MSG_TRUNC ? ret : total_len;
2188 	}
2189 out:
2190 	tun_put(tun);
2191 	return ret;
2192 
2193 out_put_tun:
2194 	tun_put(tun);
2195 out_free_skb:
2196 	if (skb)
2197 		kfree_skb(skb);
2198 	return ret;
2199 }
2200 
2201 static int tun_peek_len(struct socket *sock)
2202 {
2203 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2204 	struct tun_struct *tun;
2205 	int ret = 0;
2206 
2207 	tun = tun_get(tfile);
2208 	if (!tun)
2209 		return 0;
2210 
2211 	ret = skb_array_peek_len(&tfile->tx_array);
2212 	tun_put(tun);
2213 
2214 	return ret;
2215 }
2216 
2217 /* Ops structure to mimic raw sockets with tun */
2218 static const struct proto_ops tun_socket_ops = {
2219 	.peek_len = tun_peek_len,
2220 	.sendmsg = tun_sendmsg,
2221 	.recvmsg = tun_recvmsg,
2222 };
2223 
2224 static struct proto tun_proto = {
2225 	.name		= "tun",
2226 	.owner		= THIS_MODULE,
2227 	.obj_size	= sizeof(struct tun_file),
2228 };
2229 
2230 static int tun_flags(struct tun_struct *tun)
2231 {
2232 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2233 }
2234 
2235 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2236 			      char *buf)
2237 {
2238 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2239 	return sprintf(buf, "0x%x\n", tun_flags(tun));
2240 }
2241 
2242 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2243 			      char *buf)
2244 {
2245 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2246 	return uid_valid(tun->owner)?
2247 		sprintf(buf, "%u\n",
2248 			from_kuid_munged(current_user_ns(), tun->owner)):
2249 		sprintf(buf, "-1\n");
2250 }
2251 
2252 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2253 			      char *buf)
2254 {
2255 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2256 	return gid_valid(tun->group) ?
2257 		sprintf(buf, "%u\n",
2258 			from_kgid_munged(current_user_ns(), tun->group)):
2259 		sprintf(buf, "-1\n");
2260 }
2261 
2262 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2263 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2264 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2265 
2266 static struct attribute *tun_dev_attrs[] = {
2267 	&dev_attr_tun_flags.attr,
2268 	&dev_attr_owner.attr,
2269 	&dev_attr_group.attr,
2270 	NULL
2271 };
2272 
2273 static const struct attribute_group tun_attr_group = {
2274 	.attrs = tun_dev_attrs
2275 };
2276 
2277 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
2278 {
2279 	struct tun_struct *tun;
2280 	struct tun_file *tfile = file->private_data;
2281 	struct net_device *dev;
2282 	int err;
2283 
2284 	if (tfile->detached)
2285 		return -EINVAL;
2286 
2287 	if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
2288 		if (!capable(CAP_NET_ADMIN))
2289 			return -EPERM;
2290 
2291 		if (!(ifr->ifr_flags & IFF_NAPI) ||
2292 		    (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
2293 			return -EINVAL;
2294 	}
2295 
2296 	dev = __dev_get_by_name(net, ifr->ifr_name);
2297 	if (dev) {
2298 		if (ifr->ifr_flags & IFF_TUN_EXCL)
2299 			return -EBUSY;
2300 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
2301 			tun = netdev_priv(dev);
2302 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
2303 			tun = netdev_priv(dev);
2304 		else
2305 			return -EINVAL;
2306 
2307 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
2308 		    !!(tun->flags & IFF_MULTI_QUEUE))
2309 			return -EINVAL;
2310 
2311 		if (tun_not_capable(tun))
2312 			return -EPERM;
2313 		err = security_tun_dev_open(tun->security);
2314 		if (err < 0)
2315 			return err;
2316 
2317 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
2318 				 ifr->ifr_flags & IFF_NAPI);
2319 		if (err < 0)
2320 			return err;
2321 
2322 		if (tun->flags & IFF_MULTI_QUEUE &&
2323 		    (tun->numqueues + tun->numdisabled > 1)) {
2324 			/* One or more queue has already been attached, no need
2325 			 * to initialize the device again.
2326 			 */
2327 			return 0;
2328 		}
2329 	}
2330 	else {
2331 		char *name;
2332 		unsigned long flags = 0;
2333 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2334 			     MAX_TAP_QUEUES : 1;
2335 
2336 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2337 			return -EPERM;
2338 		err = security_tun_dev_create();
2339 		if (err < 0)
2340 			return err;
2341 
2342 		/* Set dev type */
2343 		if (ifr->ifr_flags & IFF_TUN) {
2344 			/* TUN device */
2345 			flags |= IFF_TUN;
2346 			name = "tun%d";
2347 		} else if (ifr->ifr_flags & IFF_TAP) {
2348 			/* TAP device */
2349 			flags |= IFF_TAP;
2350 			name = "tap%d";
2351 		} else
2352 			return -EINVAL;
2353 
2354 		if (*ifr->ifr_name)
2355 			name = ifr->ifr_name;
2356 
2357 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2358 				       NET_NAME_UNKNOWN, tun_setup, queues,
2359 				       queues);
2360 
2361 		if (!dev)
2362 			return -ENOMEM;
2363 		err = dev_get_valid_name(net, dev, name);
2364 		if (err < 0)
2365 			goto err_free_dev;
2366 
2367 		dev_net_set(dev, net);
2368 		dev->rtnl_link_ops = &tun_link_ops;
2369 		dev->ifindex = tfile->ifindex;
2370 		dev->sysfs_groups[0] = &tun_attr_group;
2371 
2372 		tun = netdev_priv(dev);
2373 		tun->dev = dev;
2374 		tun->flags = flags;
2375 		tun->txflt.count = 0;
2376 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
2377 
2378 		tun->align = NET_SKB_PAD;
2379 		tun->filter_attached = false;
2380 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
2381 		tun->rx_batched = 0;
2382 		RCU_INIT_POINTER(tun->steering_prog, NULL);
2383 
2384 		tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2385 		if (!tun->pcpu_stats) {
2386 			err = -ENOMEM;
2387 			goto err_free_dev;
2388 		}
2389 
2390 		spin_lock_init(&tun->lock);
2391 
2392 		err = security_tun_dev_alloc_security(&tun->security);
2393 		if (err < 0)
2394 			goto err_free_stat;
2395 
2396 		tun_net_init(dev);
2397 		tun_flow_init(tun);
2398 
2399 		dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
2400 				   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
2401 				   NETIF_F_HW_VLAN_STAG_TX;
2402 		dev->features = dev->hw_features | NETIF_F_LLTX;
2403 		dev->vlan_features = dev->features &
2404 				     ~(NETIF_F_HW_VLAN_CTAG_TX |
2405 				       NETIF_F_HW_VLAN_STAG_TX);
2406 
2407 		INIT_LIST_HEAD(&tun->disabled);
2408 		err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI);
2409 		if (err < 0)
2410 			goto err_free_flow;
2411 
2412 		err = register_netdevice(tun->dev);
2413 		if (err < 0)
2414 			goto err_detach;
2415 	}
2416 
2417 	netif_carrier_on(tun->dev);
2418 
2419 	tun_debug(KERN_INFO, tun, "tun_set_iff\n");
2420 
2421 	tun->flags = (tun->flags & ~TUN_FEATURES) |
2422 		(ifr->ifr_flags & TUN_FEATURES);
2423 
2424 	/* Make sure persistent devices do not get stuck in
2425 	 * xoff state.
2426 	 */
2427 	if (netif_running(tun->dev))
2428 		netif_tx_wake_all_queues(tun->dev);
2429 
2430 	strcpy(ifr->ifr_name, tun->dev->name);
2431 	return 0;
2432 
2433 err_detach:
2434 	tun_detach_all(dev);
2435 	/* register_netdevice() already called tun_free_netdev() */
2436 	goto err_free_dev;
2437 
2438 err_free_flow:
2439 	tun_flow_uninit(tun);
2440 	security_tun_dev_free_security(tun->security);
2441 err_free_stat:
2442 	free_percpu(tun->pcpu_stats);
2443 err_free_dev:
2444 	free_netdev(dev);
2445 	return err;
2446 }
2447 
2448 static void tun_get_iff(struct net *net, struct tun_struct *tun,
2449 		       struct ifreq *ifr)
2450 {
2451 	tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2452 
2453 	strcpy(ifr->ifr_name, tun->dev->name);
2454 
2455 	ifr->ifr_flags = tun_flags(tun);
2456 
2457 }
2458 
2459 /* This is like a cut-down ethtool ops, except done via tun fd so no
2460  * privs required. */
2461 static int set_offload(struct tun_struct *tun, unsigned long arg)
2462 {
2463 	netdev_features_t features = 0;
2464 
2465 	if (arg & TUN_F_CSUM) {
2466 		features |= NETIF_F_HW_CSUM;
2467 		arg &= ~TUN_F_CSUM;
2468 
2469 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
2470 			if (arg & TUN_F_TSO_ECN) {
2471 				features |= NETIF_F_TSO_ECN;
2472 				arg &= ~TUN_F_TSO_ECN;
2473 			}
2474 			if (arg & TUN_F_TSO4)
2475 				features |= NETIF_F_TSO;
2476 			if (arg & TUN_F_TSO6)
2477 				features |= NETIF_F_TSO6;
2478 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
2479 		}
2480 
2481 		arg &= ~TUN_F_UFO;
2482 	}
2483 
2484 	/* This gives the user a way to test for new features in future by
2485 	 * trying to set them. */
2486 	if (arg)
2487 		return -EINVAL;
2488 
2489 	tun->set_features = features;
2490 	tun->dev->wanted_features &= ~TUN_USER_FEATURES;
2491 	tun->dev->wanted_features |= features;
2492 	netdev_update_features(tun->dev);
2493 
2494 	return 0;
2495 }
2496 
2497 static void tun_detach_filter(struct tun_struct *tun, int n)
2498 {
2499 	int i;
2500 	struct tun_file *tfile;
2501 
2502 	for (i = 0; i < n; i++) {
2503 		tfile = rtnl_dereference(tun->tfiles[i]);
2504 		lock_sock(tfile->socket.sk);
2505 		sk_detach_filter(tfile->socket.sk);
2506 		release_sock(tfile->socket.sk);
2507 	}
2508 
2509 	tun->filter_attached = false;
2510 }
2511 
2512 static int tun_attach_filter(struct tun_struct *tun)
2513 {
2514 	int i, ret = 0;
2515 	struct tun_file *tfile;
2516 
2517 	for (i = 0; i < tun->numqueues; i++) {
2518 		tfile = rtnl_dereference(tun->tfiles[i]);
2519 		lock_sock(tfile->socket.sk);
2520 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
2521 		release_sock(tfile->socket.sk);
2522 		if (ret) {
2523 			tun_detach_filter(tun, i);
2524 			return ret;
2525 		}
2526 	}
2527 
2528 	tun->filter_attached = true;
2529 	return ret;
2530 }
2531 
2532 static void tun_set_sndbuf(struct tun_struct *tun)
2533 {
2534 	struct tun_file *tfile;
2535 	int i;
2536 
2537 	for (i = 0; i < tun->numqueues; i++) {
2538 		tfile = rtnl_dereference(tun->tfiles[i]);
2539 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2540 	}
2541 }
2542 
2543 static int tun_set_queue(struct file *file, struct ifreq *ifr)
2544 {
2545 	struct tun_file *tfile = file->private_data;
2546 	struct tun_struct *tun;
2547 	int ret = 0;
2548 
2549 	rtnl_lock();
2550 
2551 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
2552 		tun = tfile->detached;
2553 		if (!tun) {
2554 			ret = -EINVAL;
2555 			goto unlock;
2556 		}
2557 		ret = security_tun_dev_attach_queue(tun->security);
2558 		if (ret < 0)
2559 			goto unlock;
2560 		ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI);
2561 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2562 		tun = rtnl_dereference(tfile->tun);
2563 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
2564 			ret = -EINVAL;
2565 		else
2566 			__tun_detach(tfile, false);
2567 	} else
2568 		ret = -EINVAL;
2569 
2570 unlock:
2571 	rtnl_unlock();
2572 	return ret;
2573 }
2574 
2575 static int tun_set_steering_ebpf(struct tun_struct *tun, void __user *data)
2576 {
2577 	struct bpf_prog *prog;
2578 	int fd;
2579 
2580 	if (copy_from_user(&fd, data, sizeof(fd)))
2581 		return -EFAULT;
2582 
2583 	if (fd == -1) {
2584 		prog = NULL;
2585 	} else {
2586 		prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
2587 		if (IS_ERR(prog))
2588 			return PTR_ERR(prog);
2589 	}
2590 
2591 	return __tun_set_steering_ebpf(tun, prog);
2592 }
2593 
2594 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
2595 			    unsigned long arg, int ifreq_len)
2596 {
2597 	struct tun_file *tfile = file->private_data;
2598 	struct tun_struct *tun;
2599 	void __user* argp = (void __user*)arg;
2600 	struct ifreq ifr;
2601 	kuid_t owner;
2602 	kgid_t group;
2603 	int sndbuf;
2604 	int vnet_hdr_sz;
2605 	unsigned int ifindex;
2606 	int le;
2607 	int ret;
2608 
2609 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) {
2610 		if (copy_from_user(&ifr, argp, ifreq_len))
2611 			return -EFAULT;
2612 	} else {
2613 		memset(&ifr, 0, sizeof(ifr));
2614 	}
2615 	if (cmd == TUNGETFEATURES) {
2616 		/* Currently this just means: "what IFF flags are valid?".
2617 		 * This is needed because we never checked for invalid flags on
2618 		 * TUNSETIFF.
2619 		 */
2620 		return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
2621 				(unsigned int __user*)argp);
2622 	} else if (cmd == TUNSETQUEUE)
2623 		return tun_set_queue(file, &ifr);
2624 
2625 	ret = 0;
2626 	rtnl_lock();
2627 
2628 	tun = tun_get(tfile);
2629 	if (cmd == TUNSETIFF) {
2630 		ret = -EEXIST;
2631 		if (tun)
2632 			goto unlock;
2633 
2634 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
2635 
2636 		ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr);
2637 
2638 		if (ret)
2639 			goto unlock;
2640 
2641 		if (copy_to_user(argp, &ifr, ifreq_len))
2642 			ret = -EFAULT;
2643 		goto unlock;
2644 	}
2645 	if (cmd == TUNSETIFINDEX) {
2646 		ret = -EPERM;
2647 		if (tun)
2648 			goto unlock;
2649 
2650 		ret = -EFAULT;
2651 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
2652 			goto unlock;
2653 
2654 		ret = 0;
2655 		tfile->ifindex = ifindex;
2656 		goto unlock;
2657 	}
2658 
2659 	ret = -EBADFD;
2660 	if (!tun)
2661 		goto unlock;
2662 
2663 	tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
2664 
2665 	ret = 0;
2666 	switch (cmd) {
2667 	case TUNGETIFF:
2668 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2669 
2670 		if (tfile->detached)
2671 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
2672 		if (!tfile->socket.sk->sk_filter)
2673 			ifr.ifr_flags |= IFF_NOFILTER;
2674 
2675 		if (copy_to_user(argp, &ifr, ifreq_len))
2676 			ret = -EFAULT;
2677 		break;
2678 
2679 	case TUNSETNOCSUM:
2680 		/* Disable/Enable checksum */
2681 
2682 		/* [unimplemented] */
2683 		tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
2684 			  arg ? "disabled" : "enabled");
2685 		break;
2686 
2687 	case TUNSETPERSIST:
2688 		/* Disable/Enable persist mode. Keep an extra reference to the
2689 		 * module to prevent the module being unprobed.
2690 		 */
2691 		if (arg && !(tun->flags & IFF_PERSIST)) {
2692 			tun->flags |= IFF_PERSIST;
2693 			__module_get(THIS_MODULE);
2694 		}
2695 		if (!arg && (tun->flags & IFF_PERSIST)) {
2696 			tun->flags &= ~IFF_PERSIST;
2697 			module_put(THIS_MODULE);
2698 		}
2699 
2700 		tun_debug(KERN_INFO, tun, "persist %s\n",
2701 			  arg ? "enabled" : "disabled");
2702 		break;
2703 
2704 	case TUNSETOWNER:
2705 		/* Set owner of the device */
2706 		owner = make_kuid(current_user_ns(), arg);
2707 		if (!uid_valid(owner)) {
2708 			ret = -EINVAL;
2709 			break;
2710 		}
2711 		tun->owner = owner;
2712 		tun_debug(KERN_INFO, tun, "owner set to %u\n",
2713 			  from_kuid(&init_user_ns, tun->owner));
2714 		break;
2715 
2716 	case TUNSETGROUP:
2717 		/* Set group of the device */
2718 		group = make_kgid(current_user_ns(), arg);
2719 		if (!gid_valid(group)) {
2720 			ret = -EINVAL;
2721 			break;
2722 		}
2723 		tun->group = group;
2724 		tun_debug(KERN_INFO, tun, "group set to %u\n",
2725 			  from_kgid(&init_user_ns, tun->group));
2726 		break;
2727 
2728 	case TUNSETLINK:
2729 		/* Only allow setting the type when the interface is down */
2730 		if (tun->dev->flags & IFF_UP) {
2731 			tun_debug(KERN_INFO, tun,
2732 				  "Linktype set failed because interface is up\n");
2733 			ret = -EBUSY;
2734 		} else {
2735 			tun->dev->type = (int) arg;
2736 			tun_debug(KERN_INFO, tun, "linktype set to %d\n",
2737 				  tun->dev->type);
2738 			ret = 0;
2739 		}
2740 		break;
2741 
2742 #ifdef TUN_DEBUG
2743 	case TUNSETDEBUG:
2744 		tun->debug = arg;
2745 		break;
2746 #endif
2747 	case TUNSETOFFLOAD:
2748 		ret = set_offload(tun, arg);
2749 		break;
2750 
2751 	case TUNSETTXFILTER:
2752 		/* Can be set only for TAPs */
2753 		ret = -EINVAL;
2754 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2755 			break;
2756 		ret = update_filter(&tun->txflt, (void __user *)arg);
2757 		break;
2758 
2759 	case SIOCGIFHWADDR:
2760 		/* Get hw address */
2761 		memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2762 		ifr.ifr_hwaddr.sa_family = tun->dev->type;
2763 		if (copy_to_user(argp, &ifr, ifreq_len))
2764 			ret = -EFAULT;
2765 		break;
2766 
2767 	case SIOCSIFHWADDR:
2768 		/* Set hw address */
2769 		tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
2770 			  ifr.ifr_hwaddr.sa_data);
2771 
2772 		ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2773 		break;
2774 
2775 	case TUNGETSNDBUF:
2776 		sndbuf = tfile->socket.sk->sk_sndbuf;
2777 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
2778 			ret = -EFAULT;
2779 		break;
2780 
2781 	case TUNSETSNDBUF:
2782 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
2783 			ret = -EFAULT;
2784 			break;
2785 		}
2786 		if (sndbuf <= 0) {
2787 			ret = -EINVAL;
2788 			break;
2789 		}
2790 
2791 		tun->sndbuf = sndbuf;
2792 		tun_set_sndbuf(tun);
2793 		break;
2794 
2795 	case TUNGETVNETHDRSZ:
2796 		vnet_hdr_sz = tun->vnet_hdr_sz;
2797 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2798 			ret = -EFAULT;
2799 		break;
2800 
2801 	case TUNSETVNETHDRSZ:
2802 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2803 			ret = -EFAULT;
2804 			break;
2805 		}
2806 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2807 			ret = -EINVAL;
2808 			break;
2809 		}
2810 
2811 		tun->vnet_hdr_sz = vnet_hdr_sz;
2812 		break;
2813 
2814 	case TUNGETVNETLE:
2815 		le = !!(tun->flags & TUN_VNET_LE);
2816 		if (put_user(le, (int __user *)argp))
2817 			ret = -EFAULT;
2818 		break;
2819 
2820 	case TUNSETVNETLE:
2821 		if (get_user(le, (int __user *)argp)) {
2822 			ret = -EFAULT;
2823 			break;
2824 		}
2825 		if (le)
2826 			tun->flags |= TUN_VNET_LE;
2827 		else
2828 			tun->flags &= ~TUN_VNET_LE;
2829 		break;
2830 
2831 	case TUNGETVNETBE:
2832 		ret = tun_get_vnet_be(tun, argp);
2833 		break;
2834 
2835 	case TUNSETVNETBE:
2836 		ret = tun_set_vnet_be(tun, argp);
2837 		break;
2838 
2839 	case TUNATTACHFILTER:
2840 		/* Can be set only for TAPs */
2841 		ret = -EINVAL;
2842 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2843 			break;
2844 		ret = -EFAULT;
2845 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
2846 			break;
2847 
2848 		ret = tun_attach_filter(tun);
2849 		break;
2850 
2851 	case TUNDETACHFILTER:
2852 		/* Can be set only for TAPs */
2853 		ret = -EINVAL;
2854 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2855 			break;
2856 		ret = 0;
2857 		tun_detach_filter(tun, tun->numqueues);
2858 		break;
2859 
2860 	case TUNGETFILTER:
2861 		ret = -EINVAL;
2862 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2863 			break;
2864 		ret = -EFAULT;
2865 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
2866 			break;
2867 		ret = 0;
2868 		break;
2869 
2870 	case TUNSETSTEERINGEBPF:
2871 		ret = tun_set_steering_ebpf(tun, argp);
2872 		break;
2873 
2874 	default:
2875 		ret = -EINVAL;
2876 		break;
2877 	}
2878 
2879 unlock:
2880 	rtnl_unlock();
2881 	if (tun)
2882 		tun_put(tun);
2883 	return ret;
2884 }
2885 
2886 static long tun_chr_ioctl(struct file *file,
2887 			  unsigned int cmd, unsigned long arg)
2888 {
2889 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2890 }
2891 
2892 #ifdef CONFIG_COMPAT
2893 static long tun_chr_compat_ioctl(struct file *file,
2894 			 unsigned int cmd, unsigned long arg)
2895 {
2896 	switch (cmd) {
2897 	case TUNSETIFF:
2898 	case TUNGETIFF:
2899 	case TUNSETTXFILTER:
2900 	case TUNGETSNDBUF:
2901 	case TUNSETSNDBUF:
2902 	case SIOCGIFHWADDR:
2903 	case SIOCSIFHWADDR:
2904 		arg = (unsigned long)compat_ptr(arg);
2905 		break;
2906 	default:
2907 		arg = (compat_ulong_t)arg;
2908 		break;
2909 	}
2910 
2911 	/*
2912 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
2913 	 * the end of that structure. All fields that are used in this
2914 	 * driver are compatible though, we don't need to convert the
2915 	 * contents.
2916 	 */
2917 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2918 }
2919 #endif /* CONFIG_COMPAT */
2920 
2921 static int tun_chr_fasync(int fd, struct file *file, int on)
2922 {
2923 	struct tun_file *tfile = file->private_data;
2924 	int ret;
2925 
2926 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
2927 		goto out;
2928 
2929 	if (on) {
2930 		__f_setown(file, task_pid(current), PIDTYPE_PID, 0);
2931 		tfile->flags |= TUN_FASYNC;
2932 	} else
2933 		tfile->flags &= ~TUN_FASYNC;
2934 	ret = 0;
2935 out:
2936 	return ret;
2937 }
2938 
2939 static int tun_chr_open(struct inode *inode, struct file * file)
2940 {
2941 	struct net *net = current->nsproxy->net_ns;
2942 	struct tun_file *tfile;
2943 
2944 	DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2945 
2946 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
2947 					    &tun_proto, 0);
2948 	if (!tfile)
2949 		return -ENOMEM;
2950 	RCU_INIT_POINTER(tfile->tun, NULL);
2951 	tfile->flags = 0;
2952 	tfile->ifindex = 0;
2953 
2954 	init_waitqueue_head(&tfile->wq.wait);
2955 	RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
2956 
2957 	tfile->socket.file = file;
2958 	tfile->socket.ops = &tun_socket_ops;
2959 
2960 	sock_init_data(&tfile->socket, &tfile->sk);
2961 
2962 	tfile->sk.sk_write_space = tun_sock_write_space;
2963 	tfile->sk.sk_sndbuf = INT_MAX;
2964 
2965 	file->private_data = tfile;
2966 	INIT_LIST_HEAD(&tfile->next);
2967 
2968 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
2969 
2970 	return 0;
2971 }
2972 
2973 static int tun_chr_close(struct inode *inode, struct file *file)
2974 {
2975 	struct tun_file *tfile = file->private_data;
2976 
2977 	tun_detach(tfile, true);
2978 
2979 	return 0;
2980 }
2981 
2982 #ifdef CONFIG_PROC_FS
2983 static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
2984 {
2985 	struct tun_file *tfile = file->private_data;
2986 	struct tun_struct *tun;
2987 	struct ifreq ifr;
2988 
2989 	memset(&ifr, 0, sizeof(ifr));
2990 
2991 	rtnl_lock();
2992 	tun = tun_get(tfile);
2993 	if (tun)
2994 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2995 	rtnl_unlock();
2996 
2997 	if (tun)
2998 		tun_put(tun);
2999 
3000 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
3001 }
3002 #endif
3003 
3004 static const struct file_operations tun_fops = {
3005 	.owner	= THIS_MODULE,
3006 	.llseek = no_llseek,
3007 	.read_iter  = tun_chr_read_iter,
3008 	.write_iter = tun_chr_write_iter,
3009 	.poll	= tun_chr_poll,
3010 	.unlocked_ioctl	= tun_chr_ioctl,
3011 #ifdef CONFIG_COMPAT
3012 	.compat_ioctl = tun_chr_compat_ioctl,
3013 #endif
3014 	.open	= tun_chr_open,
3015 	.release = tun_chr_close,
3016 	.fasync = tun_chr_fasync,
3017 #ifdef CONFIG_PROC_FS
3018 	.show_fdinfo = tun_chr_show_fdinfo,
3019 #endif
3020 };
3021 
3022 static struct miscdevice tun_miscdev = {
3023 	.minor = TUN_MINOR,
3024 	.name = "tun",
3025 	.nodename = "net/tun",
3026 	.fops = &tun_fops,
3027 };
3028 
3029 /* ethtool interface */
3030 
3031 static int tun_get_link_ksettings(struct net_device *dev,
3032 				  struct ethtool_link_ksettings *cmd)
3033 {
3034 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
3035 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
3036 	cmd->base.speed		= SPEED_10;
3037 	cmd->base.duplex	= DUPLEX_FULL;
3038 	cmd->base.port		= PORT_TP;
3039 	cmd->base.phy_address	= 0;
3040 	cmd->base.autoneg	= AUTONEG_DISABLE;
3041 	return 0;
3042 }
3043 
3044 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
3045 {
3046 	struct tun_struct *tun = netdev_priv(dev);
3047 
3048 	strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
3049 	strlcpy(info->version, DRV_VERSION, sizeof(info->version));
3050 
3051 	switch (tun->flags & TUN_TYPE_MASK) {
3052 	case IFF_TUN:
3053 		strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
3054 		break;
3055 	case IFF_TAP:
3056 		strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
3057 		break;
3058 	}
3059 }
3060 
3061 static u32 tun_get_msglevel(struct net_device *dev)
3062 {
3063 #ifdef TUN_DEBUG
3064 	struct tun_struct *tun = netdev_priv(dev);
3065 	return tun->debug;
3066 #else
3067 	return -EOPNOTSUPP;
3068 #endif
3069 }
3070 
3071 static void tun_set_msglevel(struct net_device *dev, u32 value)
3072 {
3073 #ifdef TUN_DEBUG
3074 	struct tun_struct *tun = netdev_priv(dev);
3075 	tun->debug = value;
3076 #endif
3077 }
3078 
3079 static int tun_get_coalesce(struct net_device *dev,
3080 			    struct ethtool_coalesce *ec)
3081 {
3082 	struct tun_struct *tun = netdev_priv(dev);
3083 
3084 	ec->rx_max_coalesced_frames = tun->rx_batched;
3085 
3086 	return 0;
3087 }
3088 
3089 static int tun_set_coalesce(struct net_device *dev,
3090 			    struct ethtool_coalesce *ec)
3091 {
3092 	struct tun_struct *tun = netdev_priv(dev);
3093 
3094 	if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
3095 		tun->rx_batched = NAPI_POLL_WEIGHT;
3096 	else
3097 		tun->rx_batched = ec->rx_max_coalesced_frames;
3098 
3099 	return 0;
3100 }
3101 
3102 static const struct ethtool_ops tun_ethtool_ops = {
3103 	.get_drvinfo	= tun_get_drvinfo,
3104 	.get_msglevel	= tun_get_msglevel,
3105 	.set_msglevel	= tun_set_msglevel,
3106 	.get_link	= ethtool_op_get_link,
3107 	.get_ts_info	= ethtool_op_get_ts_info,
3108 	.get_coalesce   = tun_get_coalesce,
3109 	.set_coalesce   = tun_set_coalesce,
3110 	.get_link_ksettings = tun_get_link_ksettings,
3111 };
3112 
3113 static int tun_queue_resize(struct tun_struct *tun)
3114 {
3115 	struct net_device *dev = tun->dev;
3116 	struct tun_file *tfile;
3117 	struct skb_array **arrays;
3118 	int n = tun->numqueues + tun->numdisabled;
3119 	int ret, i;
3120 
3121 	arrays = kmalloc_array(n, sizeof(*arrays), GFP_KERNEL);
3122 	if (!arrays)
3123 		return -ENOMEM;
3124 
3125 	for (i = 0; i < tun->numqueues; i++) {
3126 		tfile = rtnl_dereference(tun->tfiles[i]);
3127 		arrays[i] = &tfile->tx_array;
3128 	}
3129 	list_for_each_entry(tfile, &tun->disabled, next)
3130 		arrays[i++] = &tfile->tx_array;
3131 
3132 	ret = skb_array_resize_multiple(arrays, n,
3133 					dev->tx_queue_len, GFP_KERNEL);
3134 
3135 	kfree(arrays);
3136 	return ret;
3137 }
3138 
3139 static int tun_device_event(struct notifier_block *unused,
3140 			    unsigned long event, void *ptr)
3141 {
3142 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3143 	struct tun_struct *tun = netdev_priv(dev);
3144 
3145 	if (dev->rtnl_link_ops != &tun_link_ops)
3146 		return NOTIFY_DONE;
3147 
3148 	switch (event) {
3149 	case NETDEV_CHANGE_TX_QUEUE_LEN:
3150 		if (tun_queue_resize(tun))
3151 			return NOTIFY_BAD;
3152 		break;
3153 	default:
3154 		break;
3155 	}
3156 
3157 	return NOTIFY_DONE;
3158 }
3159 
3160 static struct notifier_block tun_notifier_block __read_mostly = {
3161 	.notifier_call	= tun_device_event,
3162 };
3163 
3164 static int __init tun_init(void)
3165 {
3166 	int ret = 0;
3167 
3168 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
3169 
3170 	ret = rtnl_link_register(&tun_link_ops);
3171 	if (ret) {
3172 		pr_err("Can't register link_ops\n");
3173 		goto err_linkops;
3174 	}
3175 
3176 	ret = misc_register(&tun_miscdev);
3177 	if (ret) {
3178 		pr_err("Can't register misc device %d\n", TUN_MINOR);
3179 		goto err_misc;
3180 	}
3181 
3182 	ret = register_netdevice_notifier(&tun_notifier_block);
3183 	if (ret) {
3184 		pr_err("Can't register netdevice notifier\n");
3185 		goto err_notifier;
3186 	}
3187 
3188 	return  0;
3189 
3190 err_notifier:
3191 	misc_deregister(&tun_miscdev);
3192 err_misc:
3193 	rtnl_link_unregister(&tun_link_ops);
3194 err_linkops:
3195 	return ret;
3196 }
3197 
3198 static void tun_cleanup(void)
3199 {
3200 	misc_deregister(&tun_miscdev);
3201 	rtnl_link_unregister(&tun_link_ops);
3202 	unregister_netdevice_notifier(&tun_notifier_block);
3203 }
3204 
3205 /* Get an underlying socket object from tun file.  Returns error unless file is
3206  * attached to a device.  The returned object works like a packet socket, it
3207  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
3208  * holding a reference to the file for as long as the socket is in use. */
3209 struct socket *tun_get_socket(struct file *file)
3210 {
3211 	struct tun_file *tfile;
3212 	if (file->f_op != &tun_fops)
3213 		return ERR_PTR(-EINVAL);
3214 	tfile = file->private_data;
3215 	if (!tfile)
3216 		return ERR_PTR(-EBADFD);
3217 	return &tfile->socket;
3218 }
3219 EXPORT_SYMBOL_GPL(tun_get_socket);
3220 
3221 struct skb_array *tun_get_skb_array(struct file *file)
3222 {
3223 	struct tun_file *tfile;
3224 
3225 	if (file->f_op != &tun_fops)
3226 		return ERR_PTR(-EINVAL);
3227 	tfile = file->private_data;
3228 	if (!tfile)
3229 		return ERR_PTR(-EBADFD);
3230 	return &tfile->tx_array;
3231 }
3232 EXPORT_SYMBOL_GPL(tun_get_skb_array);
3233 
3234 module_init(tun_init);
3235 module_exit(tun_cleanup);
3236 MODULE_DESCRIPTION(DRV_DESCRIPTION);
3237 MODULE_AUTHOR(DRV_COPYRIGHT);
3238 MODULE_LICENSE("GPL");
3239 MODULE_ALIAS_MISCDEV(TUN_MINOR);
3240 MODULE_ALIAS("devname:net/tun");
3241