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