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