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