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