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