xref: /openbmc/linux/drivers/net/tun.c (revision 9bc3047374d5bec163e83e743709e23753376f0c)
1c942fddfSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  TUN - Universal TUN/TAP device driver.
41da177e4SLinus Torvalds  *  Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *  $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
71da177e4SLinus Torvalds  */
81da177e4SLinus Torvalds 
91da177e4SLinus Torvalds /*
101da177e4SLinus Torvalds  *  Changes:
111da177e4SLinus Torvalds  *
12ff4cc3acSMike Kershaw  *  Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
13ff4cc3acSMike Kershaw  *    Add TUNSETLINK ioctl to set the link encapsulation
14ff4cc3acSMike Kershaw  *
151da177e4SLinus Torvalds  *  Mark Smith <markzzzsmith@yahoo.com.au>
16344dc8edSJoe Perches  *    Use eth_random_addr() for tap MAC address.
171da177e4SLinus Torvalds  *
181da177e4SLinus Torvalds  *  Harald Roelle <harald.roelle@ifi.lmu.de>  2004/04/20
191da177e4SLinus Torvalds  *    Fixes in packet dropping, queue length setting and queue wakeup.
201da177e4SLinus Torvalds  *    Increased default tx queue length.
211da177e4SLinus Torvalds  *    Added ethtool API.
221da177e4SLinus Torvalds  *    Minor cleanups
231da177e4SLinus Torvalds  *
241da177e4SLinus Torvalds  *  Daniel Podlejski <underley@underley.eu.org>
251da177e4SLinus Torvalds  *    Modifications for 2.3.99-pre5 kernel.
261da177e4SLinus Torvalds  */
271da177e4SLinus Torvalds 
286b8a66eeSJoe Perches #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
296b8a66eeSJoe Perches 
301da177e4SLinus Torvalds #define DRV_NAME	"tun"
311da177e4SLinus Torvalds #define DRV_VERSION	"1.6"
321da177e4SLinus Torvalds #define DRV_DESCRIPTION	"Universal TUN/TAP device driver"
331da177e4SLinus Torvalds #define DRV_COPYRIGHT	"(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
341da177e4SLinus Torvalds 
351da177e4SLinus Torvalds #include <linux/module.h>
361da177e4SLinus Torvalds #include <linux/errno.h>
371da177e4SLinus Torvalds #include <linux/kernel.h>
38174cd4b1SIngo Molnar #include <linux/sched/signal.h>
391da177e4SLinus Torvalds #include <linux/major.h>
401da177e4SLinus Torvalds #include <linux/slab.h>
411da177e4SLinus Torvalds #include <linux/poll.h>
421da177e4SLinus Torvalds #include <linux/fcntl.h>
431da177e4SLinus Torvalds #include <linux/init.h>
441da177e4SLinus Torvalds #include <linux/skbuff.h>
451da177e4SLinus Torvalds #include <linux/netdevice.h>
461da177e4SLinus Torvalds #include <linux/etherdevice.h>
471da177e4SLinus Torvalds #include <linux/miscdevice.h>
481da177e4SLinus Torvalds #include <linux/ethtool.h>
491da177e4SLinus Torvalds #include <linux/rtnetlink.h>
5050857e2aSArnd Bergmann #include <linux/compat.h>
511da177e4SLinus Torvalds #include <linux/if.h>
521da177e4SLinus Torvalds #include <linux/if_arp.h>
531da177e4SLinus Torvalds #include <linux/if_ether.h>
541da177e4SLinus Torvalds #include <linux/if_tun.h>
556680ec68SJason Wang #include <linux/if_vlan.h>
561da177e4SLinus Torvalds #include <linux/crc32.h>
57d647a591SPavel Emelyanov #include <linux/nsproxy.h>
58f43798c2SRusty Russell #include <linux/virtio_net.h>
5999405162SMichael S. Tsirkin #include <linux/rcupdate.h>
60881d966bSEric W. Biederman #include <net/net_namespace.h>
6179d17604SPavel Emelyanov #include <net/netns/generic.h>
62f019a7a5SEric W. Biederman #include <net/rtnetlink.h>
6333dccbb0SHerbert Xu #include <net/sock.h>
64735fc405SJesper Dangaard Brouer #include <net/xdp.h>
65b9815eb1SJason A. Donenfeld #include <net/ip_tunnels.h>
6693e14b6dSMasatake YAMATO #include <linux/seq_file.h>
67e0b46d0eSHerbert Xu #include <linux/uio.h>
681576d986SJason Wang #include <linux/skb_array.h>
69761876c8SJason Wang #include <linux/bpf.h>
70761876c8SJason Wang #include <linux/bpf_trace.h>
7190e33d45SPetar Penkov #include <linux/mutex.h>
72cca8ea3bSPhillip Potter #include <linux/ieee802154.h>
73cca8ea3bSPhillip Potter #include <linux/if_ltalk.h>
74cca8ea3bSPhillip Potter #include <uapi/linux/if_fddi.h>
75cca8ea3bSPhillip Potter #include <uapi/linux/if_hippi.h>
76cca8ea3bSPhillip Potter #include <uapi/linux/if_fc.h>
77cca8ea3bSPhillip Potter #include <net/ax25.h>
78cca8ea3bSPhillip Potter #include <net/rose.h>
79cca8ea3bSPhillip Potter #include <net/6lowpan.h>
801da177e4SLinus Torvalds 
817c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
82f2780d6dSKirill Tkhai #include <linux/proc_fs.h>
831da177e4SLinus Torvalds 
844e24f2ddSChas Williams static void tun_default_link_ksettings(struct net_device *dev,
854e24f2ddSChas Williams 				       struct ethtool_link_ksettings *cmd);
864e24f2ddSChas Williams 
877df13219SJason Wang #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
8866ccbc9cSJason Wang 
89031f5e03SMichael S. Tsirkin /* TUN device flags */
90031f5e03SMichael S. Tsirkin 
91031f5e03SMichael S. Tsirkin /* IFF_ATTACH_QUEUE is never stored in device flags,
92031f5e03SMichael S. Tsirkin  * overload it to mean fasync when stored there.
93031f5e03SMichael S. Tsirkin  */
94031f5e03SMichael S. Tsirkin #define TUN_FASYNC	IFF_ATTACH_QUEUE
951cf8e410SMichael S. Tsirkin /* High bits in flags field are unused. */
961cf8e410SMichael S. Tsirkin #define TUN_VNET_LE     0x80000000
978b8e658bSGreg Kurz #define TUN_VNET_BE     0x40000000
98031f5e03SMichael S. Tsirkin 
99031f5e03SMichael S. Tsirkin #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
10090e33d45SPetar Penkov 		      IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
10190e33d45SPetar Penkov 
1020690899bSMichael S. Tsirkin #define GOODCOPY_LEN 128
1030690899bSMichael S. Tsirkin 
104f271b2ccSMax Krasnyansky #define FLT_EXACT_COUNT 8
105f271b2ccSMax Krasnyansky struct tap_filter {
106f271b2ccSMax Krasnyansky 	unsigned int    count;    /* Number of addrs. Zero means disabled */
107f271b2ccSMax Krasnyansky 	u32             mask[2];  /* Mask of the hashed addrs */
108f271b2ccSMax Krasnyansky 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
109f271b2ccSMax Krasnyansky };
110f271b2ccSMax Krasnyansky 
111baf71c5cSPankaj Gupta /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
112baf71c5cSPankaj Gupta  * to max number of VCPUs in guest. */
113baf71c5cSPankaj Gupta #define MAX_TAP_QUEUES 256
114b8732fb7SJason Wang #define MAX_TAP_FLOWS  4096
115c8d68e6bSJason Wang 
11696442e42SJason Wang #define TUN_FLOW_EXPIRE (3 * HZ)
11796442e42SJason Wang 
11854f968d6SJason Wang /* A tun_file connects an open character device to a tuntap netdevice. It
11992d4ea6eSstephen hemminger  * also contains all socket related structures (except sock_fprog and tap_filter)
12054f968d6SJason Wang  * to serve as one transmit queue for tuntap device. The sock_fprog and
12154f968d6SJason Wang  * tap_filter were kept in tun_struct since they were used for filtering for the
12236fe8c09SRami Rosen  * netdevice not for a specific queue (at least I didn't see the requirement for
12354f968d6SJason Wang  * this).
1246e914fc7SJason Wang  *
1256e914fc7SJason Wang  * RCU usage:
12636fe8c09SRami Rosen  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
1276e914fc7SJason Wang  * other can only be read while rcu_read_lock or rtnl_lock is held.
12854f968d6SJason Wang  */
129631ab46bSEric W. Biederman struct tun_file {
13054f968d6SJason Wang 	struct sock sk;
13154f968d6SJason Wang 	struct socket socket;
1326e914fc7SJason Wang 	struct tun_struct __rcu *tun;
13354f968d6SJason Wang 	struct fasync_struct *fasync;
13454f968d6SJason Wang 	/* only used for fasnyc */
13554f968d6SJason Wang 	unsigned int flags;
136fb7589a1SPavel Emelyanov 	union {
137c8d68e6bSJason Wang 		u16 queue_index;
138fb7589a1SPavel Emelyanov 		unsigned int ifindex;
139fb7589a1SPavel Emelyanov 	};
14094317099SPetar Penkov 	struct napi_struct napi;
141aec72f33SEric Dumazet 	bool napi_enabled;
142af3fb24eSEric Dumazet 	bool napi_frags_enabled;
14390e33d45SPetar Penkov 	struct mutex napi_mutex;	/* Protects access to the above napi */
1444008e97fSJason Wang 	struct list_head next;
1454008e97fSJason Wang 	struct tun_struct *detached;
1465990a305SJason Wang 	struct ptr_ring tx_ring;
1478bf5c4eeSJesper Dangaard Brouer 	struct xdp_rxq_info xdp_rxq;
148631ab46bSEric W. Biederman };
149631ab46bSEric W. Biederman 
150f9e06c45SJason Wang struct tun_page {
151f9e06c45SJason Wang 	struct page *page;
152f9e06c45SJason Wang 	int count;
153f9e06c45SJason Wang };
154f9e06c45SJason Wang 
15596442e42SJason Wang struct tun_flow_entry {
15696442e42SJason Wang 	struct hlist_node hash_link;
15796442e42SJason Wang 	struct rcu_head rcu;
15896442e42SJason Wang 	struct tun_struct *tun;
15996442e42SJason Wang 
16096442e42SJason Wang 	u32 rxhash;
1619bc88939STom Herbert 	u32 rps_rxhash;
16296442e42SJason Wang 	int queue_index;
16383b1bc12SLi RongQing 	unsigned long updated ____cacheline_aligned_in_smp;
16496442e42SJason Wang };
16596442e42SJason Wang 
16696442e42SJason Wang #define TUN_NUM_FLOW_ENTRIES 1024
167f13b5468SLi RongQing #define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
16896442e42SJason Wang 
169cd5681d7SJason Wang struct tun_prog {
17096f84061SJason Wang 	struct rcu_head rcu;
17196f84061SJason Wang 	struct bpf_prog *prog;
17296f84061SJason Wang };
17396f84061SJason Wang 
17454f968d6SJason Wang /* Since the socket were moved to tun_file, to preserve the behavior of persist
17536fe8c09SRami Rosen  * device, socket filter, sndbuf and vnet header size were restore when the
17654f968d6SJason Wang  * file were attached to a persist device.
17754f968d6SJason Wang  */
17814daa021SRusty Russell struct tun_struct {
179c8d68e6bSJason Wang 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
180c8d68e6bSJason Wang 	unsigned int            numqueues;
181f271b2ccSMax Krasnyansky 	unsigned int 		flags;
1820625c883SEric W. Biederman 	kuid_t			owner;
1830625c883SEric W. Biederman 	kgid_t			group;
18414daa021SRusty Russell 
18514daa021SRusty Russell 	struct net_device	*dev;
186c8f44affSMichał Mirosław 	netdev_features_t	set_features;
18788255375SMichał Mirosław #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
188399e0827SAndrew Melnychenko 			  NETIF_F_TSO6 | NETIF_F_GSO_UDP_L4)
189d9d52b51SMichael S. Tsirkin 
190eaea34b2SPaolo Abeni 	int			align;
191d9d52b51SMichael S. Tsirkin 	int			vnet_hdr_sz;
19254f968d6SJason Wang 	int			sndbuf;
19354f968d6SJason Wang 	struct tap_filter	txflt;
19454f968d6SJason Wang 	struct sock_fprog	fprog;
19554f968d6SJason Wang 	/* protected by rtnl lock */
19654f968d6SJason Wang 	bool			filter_attached;
1973424170fSMichal Kubecek 	u32			msg_enable;
19896442e42SJason Wang 	spinlock_t lock;
19996442e42SJason Wang 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
20096442e42SJason Wang 	struct timer_list flow_gc_timer;
20196442e42SJason Wang 	unsigned long ageing_time;
2024008e97fSJason Wang 	unsigned int numdisabled;
2034008e97fSJason Wang 	struct list_head disabled;
2045dbbaf2dSPaul Moore 	void *security;
205b8732fb7SJason Wang 	u32 flow_count;
2065503fcecSJason Wang 	u32 rx_batched;
207497a5757SHeiner Kallweit 	atomic_long_t rx_frame_errors;
208761876c8SJason Wang 	struct bpf_prog __rcu *xdp_prog;
209cd5681d7SJason Wang 	struct tun_prog __rcu *steering_prog;
210aff3d70aSJason Wang 	struct tun_prog __rcu *filter_prog;
2114e24f2ddSChas Williams 	struct ethtool_link_ksettings link_ksettings;
212158b515fSGeorge Kennedy 	/* init args */
213158b515fSGeorge Kennedy 	struct file *file;
214158b515fSGeorge Kennedy 	struct ifreq *ifr;
21514daa021SRusty Russell };
21614daa021SRusty Russell 
217aff3d70aSJason Wang struct veth {
218aff3d70aSJason Wang 	__be16 h_vlan_proto;
219aff3d70aSJason Wang 	__be16 h_vlan_TCI;
2201da177e4SLinus Torvalds };
2211da177e4SLinus Torvalds 
222158b515fSGeorge Kennedy static void tun_flow_init(struct tun_struct *tun);
223158b515fSGeorge Kennedy static void tun_flow_uninit(struct tun_struct *tun);
224158b515fSGeorge Kennedy 
22594317099SPetar Penkov static int tun_napi_receive(struct napi_struct *napi, int budget)
22694317099SPetar Penkov {
22794317099SPetar Penkov 	struct tun_file *tfile = container_of(napi, struct tun_file, napi);
22894317099SPetar Penkov 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
22994317099SPetar Penkov 	struct sk_buff_head process_queue;
23094317099SPetar Penkov 	struct sk_buff *skb;
23194317099SPetar Penkov 	int received = 0;
23294317099SPetar Penkov 
23394317099SPetar Penkov 	__skb_queue_head_init(&process_queue);
23494317099SPetar Penkov 
23594317099SPetar Penkov 	spin_lock(&queue->lock);
23694317099SPetar Penkov 	skb_queue_splice_tail_init(queue, &process_queue);
23794317099SPetar Penkov 	spin_unlock(&queue->lock);
23894317099SPetar Penkov 
23994317099SPetar Penkov 	while (received < budget && (skb = __skb_dequeue(&process_queue))) {
24094317099SPetar Penkov 		napi_gro_receive(napi, skb);
24194317099SPetar Penkov 		++received;
24294317099SPetar Penkov 	}
24394317099SPetar Penkov 
24494317099SPetar Penkov 	if (!skb_queue_empty(&process_queue)) {
24594317099SPetar Penkov 		spin_lock(&queue->lock);
24694317099SPetar Penkov 		skb_queue_splice(&process_queue, queue);
24794317099SPetar Penkov 		spin_unlock(&queue->lock);
24894317099SPetar Penkov 	}
24994317099SPetar Penkov 
25094317099SPetar Penkov 	return received;
25194317099SPetar Penkov }
25294317099SPetar Penkov 
25394317099SPetar Penkov static int tun_napi_poll(struct napi_struct *napi, int budget)
25494317099SPetar Penkov {
25594317099SPetar Penkov 	unsigned int received;
25694317099SPetar Penkov 
25794317099SPetar Penkov 	received = tun_napi_receive(napi, budget);
25894317099SPetar Penkov 
25994317099SPetar Penkov 	if (received < budget)
26094317099SPetar Penkov 		napi_complete_done(napi, received);
26194317099SPetar Penkov 
26294317099SPetar Penkov 	return received;
26394317099SPetar Penkov }
26494317099SPetar Penkov 
26594317099SPetar Penkov static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
266af3fb24eSEric Dumazet 			  bool napi_en, bool napi_frags)
26794317099SPetar Penkov {
268aec72f33SEric Dumazet 	tfile->napi_enabled = napi_en;
269af3fb24eSEric Dumazet 	tfile->napi_frags_enabled = napi_en && napi_frags;
27094317099SPetar Penkov 	if (napi_en) {
27116d083e2SJakub Kicinski 		netif_napi_add_tx(tun->dev, &tfile->napi, tun_napi_poll);
27294317099SPetar Penkov 		napi_enable(&tfile->napi);
27394317099SPetar Penkov 	}
27494317099SPetar Penkov }
27594317099SPetar Penkov 
276a8fc8cb5SJakub Kicinski static void tun_napi_enable(struct tun_file *tfile)
277a8fc8cb5SJakub Kicinski {
278a8fc8cb5SJakub Kicinski 	if (tfile->napi_enabled)
279a8fc8cb5SJakub Kicinski 		napi_enable(&tfile->napi);
280a8fc8cb5SJakub Kicinski }
281a8fc8cb5SJakub Kicinski 
28206e55addSEric Dumazet static void tun_napi_disable(struct tun_file *tfile)
28394317099SPetar Penkov {
284aec72f33SEric Dumazet 	if (tfile->napi_enabled)
28594317099SPetar Penkov 		napi_disable(&tfile->napi);
28694317099SPetar Penkov }
28794317099SPetar Penkov 
28806e55addSEric Dumazet static void tun_napi_del(struct tun_file *tfile)
28994317099SPetar Penkov {
290aec72f33SEric Dumazet 	if (tfile->napi_enabled)
29194317099SPetar Penkov 		netif_napi_del(&tfile->napi);
29294317099SPetar Penkov }
29394317099SPetar Penkov 
294af3fb24eSEric Dumazet static bool tun_napi_frags_enabled(const struct tun_file *tfile)
29590e33d45SPetar Penkov {
296af3fb24eSEric Dumazet 	return tfile->napi_frags_enabled;
29790e33d45SPetar Penkov }
29890e33d45SPetar Penkov 
2998b8e658bSGreg Kurz #ifdef CONFIG_TUN_VNET_CROSS_LE
3008b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3018b8e658bSGreg Kurz {
3028b8e658bSGreg Kurz 	return tun->flags & TUN_VNET_BE ? false :
3038b8e658bSGreg Kurz 		virtio_legacy_is_little_endian();
3048b8e658bSGreg Kurz }
3058b8e658bSGreg Kurz 
3068b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3078b8e658bSGreg Kurz {
3088b8e658bSGreg Kurz 	int be = !!(tun->flags & TUN_VNET_BE);
3098b8e658bSGreg Kurz 
3108b8e658bSGreg Kurz 	if (put_user(be, argp))
3118b8e658bSGreg Kurz 		return -EFAULT;
3128b8e658bSGreg Kurz 
3138b8e658bSGreg Kurz 	return 0;
3148b8e658bSGreg Kurz }
3158b8e658bSGreg Kurz 
3168b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3178b8e658bSGreg Kurz {
3188b8e658bSGreg Kurz 	int be;
3198b8e658bSGreg Kurz 
3208b8e658bSGreg Kurz 	if (get_user(be, argp))
3218b8e658bSGreg Kurz 		return -EFAULT;
3228b8e658bSGreg Kurz 
3238b8e658bSGreg Kurz 	if (be)
3248b8e658bSGreg Kurz 		tun->flags |= TUN_VNET_BE;
3258b8e658bSGreg Kurz 	else
3268b8e658bSGreg Kurz 		tun->flags &= ~TUN_VNET_BE;
3278b8e658bSGreg Kurz 
3288b8e658bSGreg Kurz 	return 0;
3298b8e658bSGreg Kurz }
3308b8e658bSGreg Kurz #else
3318b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3328b8e658bSGreg Kurz {
3338b8e658bSGreg Kurz 	return virtio_legacy_is_little_endian();
3348b8e658bSGreg Kurz }
3358b8e658bSGreg Kurz 
3368b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3378b8e658bSGreg Kurz {
3388b8e658bSGreg Kurz 	return -EINVAL;
3398b8e658bSGreg Kurz }
3408b8e658bSGreg Kurz 
3418b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3428b8e658bSGreg Kurz {
3438b8e658bSGreg Kurz 	return -EINVAL;
3448b8e658bSGreg Kurz }
3458b8e658bSGreg Kurz #endif /* CONFIG_TUN_VNET_CROSS_LE */
3468b8e658bSGreg Kurz 
34725bd55bbSGreg Kurz static inline bool tun_is_little_endian(struct tun_struct *tun)
34825bd55bbSGreg Kurz {
3497d824109SGreg Kurz 	return tun->flags & TUN_VNET_LE ||
3508b8e658bSGreg Kurz 		tun_legacy_is_little_endian(tun);
35125bd55bbSGreg Kurz }
35225bd55bbSGreg Kurz 
35356f0dcc5SMichael S. Tsirkin static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
35456f0dcc5SMichael S. Tsirkin {
35525bd55bbSGreg Kurz 	return __virtio16_to_cpu(tun_is_little_endian(tun), val);
35656f0dcc5SMichael S. Tsirkin }
35756f0dcc5SMichael S. Tsirkin 
35856f0dcc5SMichael S. Tsirkin static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
35956f0dcc5SMichael S. Tsirkin {
36025bd55bbSGreg Kurz 	return __cpu_to_virtio16(tun_is_little_endian(tun), val);
36156f0dcc5SMichael S. Tsirkin }
36256f0dcc5SMichael S. Tsirkin 
36396442e42SJason Wang static inline u32 tun_hashfn(u32 rxhash)
36496442e42SJason Wang {
365f13b5468SLi RongQing 	return rxhash & TUN_MASK_FLOW_ENTRIES;
36696442e42SJason Wang }
36796442e42SJason Wang 
36896442e42SJason Wang static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
36996442e42SJason Wang {
37096442e42SJason Wang 	struct tun_flow_entry *e;
37196442e42SJason Wang 
372b67bfe0dSSasha Levin 	hlist_for_each_entry_rcu(e, head, hash_link) {
37396442e42SJason Wang 		if (e->rxhash == rxhash)
37496442e42SJason Wang 			return e;
37596442e42SJason Wang 	}
37696442e42SJason Wang 	return NULL;
37796442e42SJason Wang }
37896442e42SJason Wang 
37996442e42SJason Wang static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
38096442e42SJason Wang 					      struct hlist_head *head,
38196442e42SJason Wang 					      u32 rxhash, u16 queue_index)
38296442e42SJason Wang {
3839fdc6befSEric Dumazet 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
3849fdc6befSEric Dumazet 
38596442e42SJason Wang 	if (e) {
3863424170fSMichal Kubecek 		netif_info(tun, tx_queued, tun->dev,
3873424170fSMichal Kubecek 			   "create flow: hash %u index %u\n",
38896442e42SJason Wang 			   rxhash, queue_index);
38996442e42SJason Wang 		e->updated = jiffies;
39096442e42SJason Wang 		e->rxhash = rxhash;
3919bc88939STom Herbert 		e->rps_rxhash = 0;
39296442e42SJason Wang 		e->queue_index = queue_index;
39396442e42SJason Wang 		e->tun = tun;
39496442e42SJason Wang 		hlist_add_head_rcu(&e->hash_link, head);
395b8732fb7SJason Wang 		++tun->flow_count;
39696442e42SJason Wang 	}
39796442e42SJason Wang 	return e;
39896442e42SJason Wang }
39996442e42SJason Wang 
40096442e42SJason Wang static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
40196442e42SJason Wang {
4023424170fSMichal Kubecek 	netif_info(tun, tx_queued, tun->dev, "delete flow: hash %u index %u\n",
40396442e42SJason Wang 		   e->rxhash, e->queue_index);
40496442e42SJason Wang 	hlist_del_rcu(&e->hash_link);
4059fdc6befSEric Dumazet 	kfree_rcu(e, rcu);
406b8732fb7SJason Wang 	--tun->flow_count;
40796442e42SJason Wang }
40896442e42SJason Wang 
40996442e42SJason Wang static void tun_flow_flush(struct tun_struct *tun)
41096442e42SJason Wang {
41196442e42SJason Wang 	int i;
41296442e42SJason Wang 
41396442e42SJason Wang 	spin_lock_bh(&tun->lock);
41496442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
41596442e42SJason Wang 		struct tun_flow_entry *e;
416b67bfe0dSSasha Levin 		struct hlist_node *n;
41796442e42SJason Wang 
418b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
41996442e42SJason Wang 			tun_flow_delete(tun, e);
42096442e42SJason Wang 	}
42196442e42SJason Wang 	spin_unlock_bh(&tun->lock);
42296442e42SJason Wang }
42396442e42SJason Wang 
42496442e42SJason Wang static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
42596442e42SJason Wang {
42696442e42SJason Wang 	int i;
42796442e42SJason Wang 
42896442e42SJason Wang 	spin_lock_bh(&tun->lock);
42996442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
43096442e42SJason Wang 		struct tun_flow_entry *e;
431b67bfe0dSSasha Levin 		struct hlist_node *n;
43296442e42SJason Wang 
433b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
43496442e42SJason Wang 			if (e->queue_index == queue_index)
43596442e42SJason Wang 				tun_flow_delete(tun, e);
43696442e42SJason Wang 		}
43796442e42SJason Wang 	}
43896442e42SJason Wang 	spin_unlock_bh(&tun->lock);
43996442e42SJason Wang }
44096442e42SJason Wang 
441e99e88a9SKees Cook static void tun_flow_cleanup(struct timer_list *t)
44296442e42SJason Wang {
443e99e88a9SKees Cook 	struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
44496442e42SJason Wang 	unsigned long delay = tun->ageing_time;
44596442e42SJason Wang 	unsigned long next_timer = jiffies + delay;
44696442e42SJason Wang 	unsigned long count = 0;
44796442e42SJason Wang 	int i;
44896442e42SJason Wang 
4497dbfb4efSEric Dumazet 	spin_lock(&tun->lock);
45096442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
45196442e42SJason Wang 		struct tun_flow_entry *e;
452b67bfe0dSSasha Levin 		struct hlist_node *n;
45396442e42SJason Wang 
454b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
45596442e42SJason Wang 			unsigned long this_timer;
45681d98fa4SEric Dumazet 
45796442e42SJason Wang 			this_timer = e->updated + delay;
45881d98fa4SEric Dumazet 			if (time_before_eq(this_timer, jiffies)) {
45996442e42SJason Wang 				tun_flow_delete(tun, e);
46081d98fa4SEric Dumazet 				continue;
46181d98fa4SEric Dumazet 			}
46281d98fa4SEric Dumazet 			count++;
46381d98fa4SEric Dumazet 			if (time_before(this_timer, next_timer))
46496442e42SJason Wang 				next_timer = this_timer;
46596442e42SJason Wang 		}
46696442e42SJason Wang 	}
46796442e42SJason Wang 
46896442e42SJason Wang 	if (count)
46996442e42SJason Wang 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
4707dbfb4efSEric Dumazet 	spin_unlock(&tun->lock);
47196442e42SJason Wang }
47296442e42SJason Wang 
47349974420SEric Dumazet static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
4749e85722dSJason Wang 			    struct tun_file *tfile)
47596442e42SJason Wang {
47696442e42SJason Wang 	struct hlist_head *head;
47796442e42SJason Wang 	struct tun_flow_entry *e;
47896442e42SJason Wang 	unsigned long delay = tun->ageing_time;
4799e85722dSJason Wang 	u16 queue_index = tfile->queue_index;
48096442e42SJason Wang 
48196442e42SJason Wang 	head = &tun->flows[tun_hashfn(rxhash)];
48296442e42SJason Wang 
48396442e42SJason Wang 	rcu_read_lock();
48496442e42SJason Wang 
48596442e42SJason Wang 	e = tun_flow_find(head, rxhash);
48696442e42SJason Wang 	if (likely(e)) {
48796442e42SJason Wang 		/* TODO: keep queueing to old queue until it's empty? */
4884ffdd22eSEric Dumazet 		if (READ_ONCE(e->queue_index) != queue_index)
4894ffdd22eSEric Dumazet 			WRITE_ONCE(e->queue_index, queue_index);
49083b1bc12SLi RongQing 		if (e->updated != jiffies)
49196442e42SJason Wang 			e->updated = jiffies;
4929bc88939STom Herbert 		sock_rps_record_flow_hash(e->rps_rxhash);
49396442e42SJason Wang 	} else {
49496442e42SJason Wang 		spin_lock_bh(&tun->lock);
495b8732fb7SJason Wang 		if (!tun_flow_find(head, rxhash) &&
496b8732fb7SJason Wang 		    tun->flow_count < MAX_TAP_FLOWS)
49796442e42SJason Wang 			tun_flow_create(tun, head, rxhash, queue_index);
49896442e42SJason Wang 
49996442e42SJason Wang 		if (!timer_pending(&tun->flow_gc_timer))
50096442e42SJason Wang 			mod_timer(&tun->flow_gc_timer,
50196442e42SJason Wang 				  round_jiffies_up(jiffies + delay));
50296442e42SJason Wang 		spin_unlock_bh(&tun->lock);
50396442e42SJason Wang 	}
50496442e42SJason Wang 
50596442e42SJason Wang 	rcu_read_unlock();
50696442e42SJason Wang }
50796442e42SJason Wang 
508516c512bSMichal Kubecek /* Save the hash received in the stack receive path and update the
5099bc88939STom Herbert  * flow_hash table accordingly.
5109bc88939STom Herbert  */
5119bc88939STom Herbert static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
5129bc88939STom Herbert {
513567e4b79SEric Dumazet 	if (unlikely(e->rps_rxhash != hash))
5149bc88939STom Herbert 		e->rps_rxhash = hash;
5159bc88939STom Herbert }
5169bc88939STom Herbert 
5174b035271SWang Li /* We try to identify a flow through its rxhash. The reason that
51892d4ea6eSstephen hemminger  * we do not check rxq no. is because some cards(e.g 82599), chooses
519c8d68e6bSJason Wang  * the rxq based on the txq where the last packet of the flow comes. As
520c8d68e6bSJason Wang  * the userspace application move between processors, we may get a
5214b035271SWang Li  * different rxq no. here.
522c8d68e6bSJason Wang  */
52396f84061SJason Wang static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
524c8d68e6bSJason Wang {
52596442e42SJason Wang 	struct tun_flow_entry *e;
526c8d68e6bSJason Wang 	u32 txq = 0;
527c8d68e6bSJason Wang 	u32 numqueues = 0;
528c8d68e6bSJason Wang 
5296aa7de05SMark Rutland 	numqueues = READ_ONCE(tun->numqueues);
530c8d68e6bSJason Wang 
531feec084aSJason Wang 	txq = __skb_get_hash_symmetric(skb);
53296442e42SJason Wang 	e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
5339bc88939STom Herbert 	if (e) {
5349bc88939STom Herbert 		tun_flow_save_rps_rxhash(e, txq);
535fbe4d456SZhi Yong Wu 		txq = e->queue_index;
5364b035271SWang Li 	} else {
537c8d68e6bSJason Wang 		/* use multiply and shift instead of expensive divide */
538c8d68e6bSJason Wang 		txq = ((u64)txq * numqueues) >> 32;
539c8d68e6bSJason Wang 	}
540c8d68e6bSJason Wang 
541c8d68e6bSJason Wang 	return txq;
542c8d68e6bSJason Wang }
543c8d68e6bSJason Wang 
54496f84061SJason Wang static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
54596f84061SJason Wang {
546cd5681d7SJason Wang 	struct tun_prog *prog;
547a35d310fSJason Wang 	u32 numqueues;
54896f84061SJason Wang 	u16 ret = 0;
54996f84061SJason Wang 
550a35d310fSJason Wang 	numqueues = READ_ONCE(tun->numqueues);
551a35d310fSJason Wang 	if (!numqueues)
552a35d310fSJason Wang 		return 0;
553a35d310fSJason Wang 
55496f84061SJason Wang 	prog = rcu_dereference(tun->steering_prog);
55596f84061SJason Wang 	if (prog)
55696f84061SJason Wang 		ret = bpf_prog_run_clear_cb(prog->prog, skb);
55796f84061SJason Wang 
558a35d310fSJason Wang 	return ret % numqueues;
55996f84061SJason Wang }
56096f84061SJason Wang 
56196f84061SJason Wang static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
562a350ecceSPaolo Abeni 			    struct net_device *sb_dev)
56396f84061SJason Wang {
56496f84061SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
56596f84061SJason Wang 	u16 ret;
56696f84061SJason Wang 
56796f84061SJason Wang 	rcu_read_lock();
56896f84061SJason Wang 	if (rcu_dereference(tun->steering_prog))
56996f84061SJason Wang 		ret = tun_ebpf_select_queue(tun, skb);
57096f84061SJason Wang 	else
57196f84061SJason Wang 		ret = tun_automq_select_queue(tun, skb);
57296f84061SJason Wang 	rcu_read_unlock();
57396f84061SJason Wang 
57496f84061SJason Wang 	return ret;
57596f84061SJason Wang }
57696f84061SJason Wang 
577cde8b15fSJason Wang static inline bool tun_not_capable(struct tun_struct *tun)
578cde8b15fSJason Wang {
579cde8b15fSJason Wang 	const struct cred *cred = current_cred();
580c260b772SEric W. Biederman 	struct net *net = dev_net(tun->dev);
581cde8b15fSJason Wang 
582cde8b15fSJason Wang 	return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
583cde8b15fSJason Wang 		  (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
584c260b772SEric W. Biederman 		!ns_capable(net->user_ns, CAP_NET_ADMIN);
585cde8b15fSJason Wang }
586cde8b15fSJason Wang 
587c8d68e6bSJason Wang static void tun_set_real_num_queues(struct tun_struct *tun)
588c8d68e6bSJason Wang {
589c8d68e6bSJason Wang 	netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
590c8d68e6bSJason Wang 	netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
591c8d68e6bSJason Wang }
592c8d68e6bSJason Wang 
5934008e97fSJason Wang static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
5944008e97fSJason Wang {
5954008e97fSJason Wang 	tfile->detached = tun;
5964008e97fSJason Wang 	list_add_tail(&tfile->next, &tun->disabled);
5974008e97fSJason Wang 	++tun->numdisabled;
5984008e97fSJason Wang }
5994008e97fSJason Wang 
600d32649d1SJason Wang static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
6014008e97fSJason Wang {
6024008e97fSJason Wang 	struct tun_struct *tun = tfile->detached;
6034008e97fSJason Wang 
6044008e97fSJason Wang 	tfile->detached = NULL;
6054008e97fSJason Wang 	list_del_init(&tfile->next);
6064008e97fSJason Wang 	--tun->numdisabled;
6074008e97fSJason Wang 	return tun;
6084008e97fSJason Wang }
6094008e97fSJason Wang 
6103a403076SJason Wang void tun_ptr_free(void *ptr)
611fc72d1d5SJason Wang {
612fc72d1d5SJason Wang 	if (!ptr)
613fc72d1d5SJason Wang 		return;
6141ffcbc85SJesper Dangaard Brouer 	if (tun_is_xdp_frame(ptr)) {
6151ffcbc85SJesper Dangaard Brouer 		struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
616fc72d1d5SJason Wang 
61703993094SJesper Dangaard Brouer 		xdp_return_frame(xdpf);
618fc72d1d5SJason Wang 	} else {
619fc72d1d5SJason Wang 		__skb_array_destroy_skb(ptr);
620fc72d1d5SJason Wang 	}
621fc72d1d5SJason Wang }
6223a403076SJason Wang EXPORT_SYMBOL_GPL(tun_ptr_free);
623fc72d1d5SJason Wang 
6244bfb0513SJason Wang static void tun_queue_purge(struct tun_file *tfile)
6254bfb0513SJason Wang {
626fc72d1d5SJason Wang 	void *ptr;
6271576d986SJason Wang 
628fc72d1d5SJason Wang 	while ((ptr = ptr_ring_consume(&tfile->tx_ring)) != NULL)
629fc72d1d5SJason Wang 		tun_ptr_free(ptr);
6301576d986SJason Wang 
6315503fcecSJason Wang 	skb_queue_purge(&tfile->sk.sk_write_queue);
6324bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_error_queue);
6334bfb0513SJason Wang }
6344bfb0513SJason Wang 
635c8d68e6bSJason Wang static void __tun_detach(struct tun_file *tfile, bool clean)
636c8d68e6bSJason Wang {
637c8d68e6bSJason Wang 	struct tun_file *ntfile;
638c8d68e6bSJason Wang 	struct tun_struct *tun;
639c8d68e6bSJason Wang 
640b8deabd3SJason Wang 	tun = rtnl_dereference(tfile->tun);
641b8deabd3SJason Wang 
64294317099SPetar Penkov 	if (tun && clean) {
643ff1fa208SJakub Kicinski 		if (!tfile->detached)
64406e55addSEric Dumazet 			tun_napi_disable(tfile);
64506e55addSEric Dumazet 		tun_napi_del(tfile);
64694317099SPetar Penkov 	}
64794317099SPetar Penkov 
6489e85722dSJason Wang 	if (tun && !tfile->detached) {
649c8d68e6bSJason Wang 		u16 index = tfile->queue_index;
650c8d68e6bSJason Wang 		BUG_ON(index >= tun->numqueues);
651c8d68e6bSJason Wang 
652c8d68e6bSJason Wang 		rcu_assign_pointer(tun->tfiles[index],
653c8d68e6bSJason Wang 				   tun->tfiles[tun->numqueues - 1]);
654b8deabd3SJason Wang 		ntfile = rtnl_dereference(tun->tfiles[index]);
655c8d68e6bSJason Wang 		ntfile->queue_index = index;
6569871a9e4SJason Wang 		rcu_assign_pointer(tun->tfiles[tun->numqueues - 1],
6579871a9e4SJason Wang 				   NULL);
658c8d68e6bSJason Wang 
659c8d68e6bSJason Wang 		--tun->numqueues;
6609e85722dSJason Wang 		if (clean) {
661c956674bSMonam Agarwal 			RCU_INIT_POINTER(tfile->tun, NULL);
662c8d68e6bSJason Wang 			sock_put(&tfile->sk);
663a8fc8cb5SJakub Kicinski 		} else {
6644008e97fSJason Wang 			tun_disable_queue(tun, tfile);
665a8fc8cb5SJakub Kicinski 			tun_napi_disable(tfile);
666a8fc8cb5SJakub Kicinski 		}
667c8d68e6bSJason Wang 
668c8d68e6bSJason Wang 		synchronize_net();
66996442e42SJason Wang 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
670c8d68e6bSJason Wang 		/* Drop read queue */
6714bfb0513SJason Wang 		tun_queue_purge(tfile);
672c8d68e6bSJason Wang 		tun_set_real_num_queues(tun);
673dd38bd85SJason Wang 	} else if (tfile->detached && clean) {
6744008e97fSJason Wang 		tun = tun_enable_queue(tfile);
675dd38bd85SJason Wang 		sock_put(&tfile->sk);
676dd38bd85SJason Wang 	}
677c8d68e6bSJason Wang 
678c8d68e6bSJason Wang 	if (clean) {
679af668b3cSMichael S. Tsirkin 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
680af668b3cSMichael S. Tsirkin 			netif_carrier_off(tun->dev);
681af668b3cSMichael S. Tsirkin 
68240630b82SMichael S. Tsirkin 			if (!(tun->flags & IFF_PERSIST) &&
683af668b3cSMichael S. Tsirkin 			    tun->dev->reg_state == NETREG_REGISTERED)
6844008e97fSJason Wang 				unregister_netdevice(tun->dev);
685af668b3cSMichael S. Tsirkin 		}
686b196d88aSJason Wang 		if (tun)
687b196d88aSJason Wang 			xdp_rxq_info_unreg(&tfile->xdp_rxq);
6887063efd3SJason Wang 		ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
689c8d68e6bSJason Wang 	}
690c8d68e6bSJason Wang }
691c8d68e6bSJason Wang 
692c8d68e6bSJason Wang static void tun_detach(struct tun_file *tfile, bool clean)
693c8d68e6bSJason Wang {
69483c1f36fSSabrina Dubroca 	struct tun_struct *tun;
69583c1f36fSSabrina Dubroca 	struct net_device *dev;
69683c1f36fSSabrina Dubroca 
697c8d68e6bSJason Wang 	rtnl_lock();
69883c1f36fSSabrina Dubroca 	tun = rtnl_dereference(tfile->tun);
69983c1f36fSSabrina Dubroca 	dev = tun ? tun->dev : NULL;
700c8d68e6bSJason Wang 	__tun_detach(tfile, clean);
70183c1f36fSSabrina Dubroca 	if (dev)
70283c1f36fSSabrina Dubroca 		netdev_state_change(dev);
703c8d68e6bSJason Wang 	rtnl_unlock();
7045daadc86SShigeru Yoshida 
7055daadc86SShigeru Yoshida 	if (clean)
7065daadc86SShigeru Yoshida 		sock_put(&tfile->sk);
707c8d68e6bSJason Wang }
708c8d68e6bSJason Wang 
709c8d68e6bSJason Wang static void tun_detach_all(struct net_device *dev)
710c8d68e6bSJason Wang {
711c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
7124008e97fSJason Wang 	struct tun_file *tfile, *tmp;
713c8d68e6bSJason Wang 	int i, n = tun->numqueues;
714c8d68e6bSJason Wang 
715c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
716b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
717c8d68e6bSJason Wang 		BUG_ON(!tfile);
71806e55addSEric Dumazet 		tun_napi_disable(tfile);
719addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7209e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
721c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
722c8d68e6bSJason Wang 		--tun->numqueues;
723c8d68e6bSJason Wang 	}
7249e85722dSJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
725addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7269e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
727c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
7289e85722dSJason Wang 	}
729c8d68e6bSJason Wang 	BUG_ON(tun->numqueues != 0);
730c8d68e6bSJason Wang 
731c8d68e6bSJason Wang 	synchronize_net();
732c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
733b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
73406e55addSEric Dumazet 		tun_napi_del(tfile);
735c8d68e6bSJason Wang 		/* Drop read queue */
7364bfb0513SJason Wang 		tun_queue_purge(tfile);
737b196d88aSJason Wang 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
738c8d68e6bSJason Wang 		sock_put(&tfile->sk);
739c8d68e6bSJason Wang 	}
7404008e97fSJason Wang 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
7413b9bc84dSJakub Kicinski 		tun_napi_del(tfile);
7424008e97fSJason Wang 		tun_enable_queue(tfile);
7434bfb0513SJason Wang 		tun_queue_purge(tfile);
744b196d88aSJason Wang 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
7454008e97fSJason Wang 		sock_put(&tfile->sk);
7464008e97fSJason Wang 	}
7474008e97fSJason Wang 	BUG_ON(tun->numdisabled != 0);
748dd38bd85SJason Wang 
74940630b82SMichael S. Tsirkin 	if (tun->flags & IFF_PERSIST)
750dd38bd85SJason Wang 		module_put(THIS_MODULE);
751c8d68e6bSJason Wang }
752c8d68e6bSJason Wang 
75394317099SPetar Penkov static int tun_attach(struct tun_struct *tun, struct file *file,
75477f22f92SYang Yingliang 		      bool skip_filter, bool napi, bool napi_frags,
75577f22f92SYang Yingliang 		      bool publish_tun)
756a7385ba2SEric W. Biederman {
757631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
7581576d986SJason Wang 	struct net_device *dev = tun->dev;
75938231b7aSEric W. Biederman 	int err;
760a7385ba2SEric W. Biederman 
7615dbbaf2dSPaul Moore 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
7625dbbaf2dSPaul Moore 	if (err < 0)
7635dbbaf2dSPaul Moore 		goto out;
7645dbbaf2dSPaul Moore 
76538231b7aSEric W. Biederman 	err = -EINVAL;
7669e85722dSJason Wang 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
76738231b7aSEric W. Biederman 		goto out;
76838231b7aSEric W. Biederman 
76938231b7aSEric W. Biederman 	err = -EBUSY;
77040630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
771c8d68e6bSJason Wang 		goto out;
772c8d68e6bSJason Wang 
773c8d68e6bSJason Wang 	err = -E2BIG;
7744008e97fSJason Wang 	if (!tfile->detached &&
7754008e97fSJason Wang 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
77638231b7aSEric W. Biederman 		goto out;
77738231b7aSEric W. Biederman 
77838231b7aSEric W. Biederman 	err = 0;
77954f968d6SJason Wang 
78092d4ea6eSstephen hemminger 	/* Re-attach the filter to persist device */
781849c9b6fSPavel Emelyanov 	if (!skip_filter && (tun->filter_attached == true)) {
7828ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
7838ced425eSHannes Frederic Sowa 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
7848ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
78554f968d6SJason Wang 		if (!err)
78654f968d6SJason Wang 			goto out;
78754f968d6SJason Wang 	}
7881576d986SJason Wang 
7891576d986SJason Wang 	if (!tfile->detached &&
790b196d88aSJason Wang 	    ptr_ring_resize(&tfile->tx_ring, dev->tx_queue_len,
791b196d88aSJason Wang 			    GFP_KERNEL, tun_ptr_free)) {
7921576d986SJason Wang 		err = -ENOMEM;
7931576d986SJason Wang 		goto out;
7941576d986SJason Wang 	}
7951576d986SJason Wang 
796c8d68e6bSJason Wang 	tfile->queue_index = tun->numqueues;
797addf8fc4SJason Wang 	tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
7988bf5c4eeSJesper Dangaard Brouer 
7998bf5c4eeSJesper Dangaard Brouer 	if (tfile->detached) {
8008bf5c4eeSJesper Dangaard Brouer 		/* Re-attach detached tfile, updating XDP queue_index */
8018bf5c4eeSJesper Dangaard Brouer 		WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
8028bf5c4eeSJesper Dangaard Brouer 
8038bf5c4eeSJesper Dangaard Brouer 		if (tfile->xdp_rxq.queue_index    != tfile->queue_index)
8048bf5c4eeSJesper Dangaard Brouer 			tfile->xdp_rxq.queue_index = tfile->queue_index;
8058bf5c4eeSJesper Dangaard Brouer 	} else {
8068bf5c4eeSJesper Dangaard Brouer 		/* Setup XDP RX-queue info, for new tfile getting attached */
8078bf5c4eeSJesper Dangaard Brouer 		err = xdp_rxq_info_reg(&tfile->xdp_rxq,
808b02e5a0eSBjörn Töpel 				       tun->dev, tfile->queue_index, 0);
8098bf5c4eeSJesper Dangaard Brouer 		if (err < 0)
8108bf5c4eeSJesper Dangaard Brouer 			goto out;
8118d5d8852SJesper Dangaard Brouer 		err = xdp_rxq_info_reg_mem_model(&tfile->xdp_rxq,
8128d5d8852SJesper Dangaard Brouer 						 MEM_TYPE_PAGE_SHARED, NULL);
8138d5d8852SJesper Dangaard Brouer 		if (err < 0) {
8148d5d8852SJesper Dangaard Brouer 			xdp_rxq_info_unreg(&tfile->xdp_rxq);
8158d5d8852SJesper Dangaard Brouer 			goto out;
8168d5d8852SJesper Dangaard Brouer 		}
8178bf5c4eeSJesper Dangaard Brouer 		err = 0;
8188bf5c4eeSJesper Dangaard Brouer 	}
8198bf5c4eeSJesper Dangaard Brouer 
82094317099SPetar Penkov 	if (tfile->detached) {
8214008e97fSJason Wang 		tun_enable_queue(tfile);
822a8fc8cb5SJakub Kicinski 		tun_napi_enable(tfile);
82394317099SPetar Penkov 	} else {
8244008e97fSJason Wang 		sock_hold(&tfile->sk);
825af3fb24eSEric Dumazet 		tun_napi_init(tun, tfile, napi, napi_frags);
82694317099SPetar Penkov 	}
8274008e97fSJason Wang 
828e4a2a304SJason Wang 	if (rtnl_dereference(tun->xdp_prog))
829e4a2a304SJason Wang 		sock_set_flag(&tfile->sk, SOCK_XDP);
830e4a2a304SJason Wang 
831c8d68e6bSJason Wang 	/* device is allowed to go away first, so no need to hold extra
832c8d68e6bSJason Wang 	 * refcnt.
833c8d68e6bSJason Wang 	 */
834a7385ba2SEric W. Biederman 
8350b7959b6SStanislav Fomichev 	/* Publish tfile->tun and tun->tfiles only after we've fully
8360b7959b6SStanislav Fomichev 	 * initialized tfile; otherwise we risk using half-initialized
8370b7959b6SStanislav Fomichev 	 * object.
8380b7959b6SStanislav Fomichev 	 */
83977f22f92SYang Yingliang 	if (publish_tun)
8400b7959b6SStanislav Fomichev 		rcu_assign_pointer(tfile->tun, tun);
8410b7959b6SStanislav Fomichev 	rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
8420b7959b6SStanislav Fomichev 	tun->numqueues++;
8433a03cb84SGeorge Amanakis 	tun_set_real_num_queues(tun);
84438231b7aSEric W. Biederman out:
84538231b7aSEric W. Biederman 	return err;
846a7385ba2SEric W. Biederman }
847a7385ba2SEric W. Biederman 
8489484dc74Syuan linyu static struct tun_struct *tun_get(struct tun_file *tfile)
849631ab46bSEric W. Biederman {
8506e914fc7SJason Wang 	struct tun_struct *tun;
851c70f1829SEric W. Biederman 
8526e914fc7SJason Wang 	rcu_read_lock();
8536e914fc7SJason Wang 	tun = rcu_dereference(tfile->tun);
8546e914fc7SJason Wang 	if (tun)
8556e914fc7SJason Wang 		dev_hold(tun->dev);
8566e914fc7SJason Wang 	rcu_read_unlock();
857c70f1829SEric W. Biederman 
858c70f1829SEric W. Biederman 	return tun;
859631ab46bSEric W. Biederman }
860631ab46bSEric W. Biederman 
861631ab46bSEric W. Biederman static void tun_put(struct tun_struct *tun)
862631ab46bSEric W. Biederman {
8636e914fc7SJason Wang 	dev_put(tun->dev);
864631ab46bSEric W. Biederman }
865631ab46bSEric W. Biederman 
8666b8a66eeSJoe Perches /* TAP filtering */
867f271b2ccSMax Krasnyansky static void addr_hash_set(u32 *mask, const u8 *addr)
868f271b2ccSMax Krasnyansky {
869f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
870f271b2ccSMax Krasnyansky 	mask[n >> 5] |= (1 << (n & 31));
871f271b2ccSMax Krasnyansky }
872f271b2ccSMax Krasnyansky 
873f271b2ccSMax Krasnyansky static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
874f271b2ccSMax Krasnyansky {
875f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
876f271b2ccSMax Krasnyansky 	return mask[n >> 5] & (1 << (n & 31));
877f271b2ccSMax Krasnyansky }
878f271b2ccSMax Krasnyansky 
879f271b2ccSMax Krasnyansky static int update_filter(struct tap_filter *filter, void __user *arg)
880f271b2ccSMax Krasnyansky {
881f271b2ccSMax Krasnyansky 	struct { u8 u[ETH_ALEN]; } *addr;
882f271b2ccSMax Krasnyansky 	struct tun_filter uf;
883f271b2ccSMax Krasnyansky 	int err, alen, n, nexact;
884f271b2ccSMax Krasnyansky 
885f271b2ccSMax Krasnyansky 	if (copy_from_user(&uf, arg, sizeof(uf)))
886f271b2ccSMax Krasnyansky 		return -EFAULT;
887f271b2ccSMax Krasnyansky 
888f271b2ccSMax Krasnyansky 	if (!uf.count) {
889f271b2ccSMax Krasnyansky 		/* Disabled */
890f271b2ccSMax Krasnyansky 		filter->count = 0;
891f271b2ccSMax Krasnyansky 		return 0;
892f271b2ccSMax Krasnyansky 	}
893f271b2ccSMax Krasnyansky 
894f271b2ccSMax Krasnyansky 	alen = ETH_ALEN * uf.count;
89528e8190dSMarkus Elfring 	addr = memdup_user(arg + sizeof(uf), alen);
89628e8190dSMarkus Elfring 	if (IS_ERR(addr))
89728e8190dSMarkus Elfring 		return PTR_ERR(addr);
898f271b2ccSMax Krasnyansky 
899f271b2ccSMax Krasnyansky 	/* The filter is updated without holding any locks. Which is
900f271b2ccSMax Krasnyansky 	 * perfectly safe. We disable it first and in the worst
901f271b2ccSMax Krasnyansky 	 * case we'll accept a few undesired packets. */
902f271b2ccSMax Krasnyansky 	filter->count = 0;
903f271b2ccSMax Krasnyansky 	wmb();
904f271b2ccSMax Krasnyansky 
905f271b2ccSMax Krasnyansky 	/* Use first set of addresses as an exact filter */
906f271b2ccSMax Krasnyansky 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
907f271b2ccSMax Krasnyansky 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
908f271b2ccSMax Krasnyansky 
909f271b2ccSMax Krasnyansky 	nexact = n;
910f271b2ccSMax Krasnyansky 
911cfbf84fcSAlex Williamson 	/* Remaining multicast addresses are hashed,
912cfbf84fcSAlex Williamson 	 * unicast will leave the filter disabled. */
913f271b2ccSMax Krasnyansky 	memset(filter->mask, 0, sizeof(filter->mask));
914cfbf84fcSAlex Williamson 	for (; n < uf.count; n++) {
915cfbf84fcSAlex Williamson 		if (!is_multicast_ether_addr(addr[n].u)) {
916cfbf84fcSAlex Williamson 			err = 0; /* no filter */
9173b8d2a69SMarkus Elfring 			goto free_addr;
918cfbf84fcSAlex Williamson 		}
919f271b2ccSMax Krasnyansky 		addr_hash_set(filter->mask, addr[n].u);
920cfbf84fcSAlex Williamson 	}
921f271b2ccSMax Krasnyansky 
922f271b2ccSMax Krasnyansky 	/* For ALLMULTI just set the mask to all ones.
923f271b2ccSMax Krasnyansky 	 * This overrides the mask populated above. */
924f271b2ccSMax Krasnyansky 	if ((uf.flags & TUN_FLT_ALLMULTI))
925f271b2ccSMax Krasnyansky 		memset(filter->mask, ~0, sizeof(filter->mask));
926f271b2ccSMax Krasnyansky 
927f271b2ccSMax Krasnyansky 	/* Now enable the filter */
928f271b2ccSMax Krasnyansky 	wmb();
929f271b2ccSMax Krasnyansky 	filter->count = nexact;
930f271b2ccSMax Krasnyansky 
931f271b2ccSMax Krasnyansky 	/* Return the number of exact filters */
932f271b2ccSMax Krasnyansky 	err = nexact;
9333b8d2a69SMarkus Elfring free_addr:
934f271b2ccSMax Krasnyansky 	kfree(addr);
935f271b2ccSMax Krasnyansky 	return err;
936f271b2ccSMax Krasnyansky }
937f271b2ccSMax Krasnyansky 
938f271b2ccSMax Krasnyansky /* Returns: 0 - drop, !=0 - accept */
939f271b2ccSMax Krasnyansky static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
940f271b2ccSMax Krasnyansky {
941f271b2ccSMax Krasnyansky 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
942f271b2ccSMax Krasnyansky 	 * at this point. */
943f271b2ccSMax Krasnyansky 	struct ethhdr *eh = (struct ethhdr *) skb->data;
944f271b2ccSMax Krasnyansky 	int i;
945f271b2ccSMax Krasnyansky 
946f271b2ccSMax Krasnyansky 	/* Exact match */
947f271b2ccSMax Krasnyansky 	for (i = 0; i < filter->count; i++)
9482e42e474SJoe Perches 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
949f271b2ccSMax Krasnyansky 			return 1;
950f271b2ccSMax Krasnyansky 
951f271b2ccSMax Krasnyansky 	/* Inexact match (multicast only) */
952f271b2ccSMax Krasnyansky 	if (is_multicast_ether_addr(eh->h_dest))
953f271b2ccSMax Krasnyansky 		return addr_hash_test(filter->mask, eh->h_dest);
954f271b2ccSMax Krasnyansky 
955f271b2ccSMax Krasnyansky 	return 0;
956f271b2ccSMax Krasnyansky }
957f271b2ccSMax Krasnyansky 
958f271b2ccSMax Krasnyansky /*
959f271b2ccSMax Krasnyansky  * Checks whether the packet is accepted or not.
960f271b2ccSMax Krasnyansky  * Returns: 0 - drop, !=0 - accept
961f271b2ccSMax Krasnyansky  */
962f271b2ccSMax Krasnyansky static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
963f271b2ccSMax Krasnyansky {
964f271b2ccSMax Krasnyansky 	if (!filter->count)
965f271b2ccSMax Krasnyansky 		return 1;
966f271b2ccSMax Krasnyansky 
967f271b2ccSMax Krasnyansky 	return run_filter(filter, skb);
968f271b2ccSMax Krasnyansky }
969f271b2ccSMax Krasnyansky 
9701da177e4SLinus Torvalds /* Network device part of the driver */
9711da177e4SLinus Torvalds 
9721da177e4SLinus Torvalds static const struct ethtool_ops tun_ethtool_ops;
9731da177e4SLinus Torvalds 
974158b515fSGeorge Kennedy static int tun_net_init(struct net_device *dev)
975158b515fSGeorge Kennedy {
976158b515fSGeorge Kennedy 	struct tun_struct *tun = netdev_priv(dev);
977158b515fSGeorge Kennedy 	struct ifreq *ifr = tun->ifr;
978158b515fSGeorge Kennedy 	int err;
979158b515fSGeorge Kennedy 
980158b515fSGeorge Kennedy 	dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
981158b515fSGeorge Kennedy 	if (!dev->tstats)
982158b515fSGeorge Kennedy 		return -ENOMEM;
983158b515fSGeorge Kennedy 
984158b515fSGeorge Kennedy 	spin_lock_init(&tun->lock);
985158b515fSGeorge Kennedy 
986158b515fSGeorge Kennedy 	err = security_tun_dev_alloc_security(&tun->security);
987158b515fSGeorge Kennedy 	if (err < 0) {
988158b515fSGeorge Kennedy 		free_percpu(dev->tstats);
989158b515fSGeorge Kennedy 		return err;
990158b515fSGeorge Kennedy 	}
991158b515fSGeorge Kennedy 
992158b515fSGeorge Kennedy 	tun_flow_init(tun);
993158b515fSGeorge Kennedy 
994158b515fSGeorge Kennedy 	dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
995158b515fSGeorge Kennedy 			   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
996158b515fSGeorge Kennedy 			   NETIF_F_HW_VLAN_STAG_TX;
997158b515fSGeorge Kennedy 	dev->features = dev->hw_features | NETIF_F_LLTX;
998158b515fSGeorge Kennedy 	dev->vlan_features = dev->features &
999158b515fSGeorge Kennedy 			     ~(NETIF_F_HW_VLAN_CTAG_TX |
1000158b515fSGeorge Kennedy 			       NETIF_F_HW_VLAN_STAG_TX);
1001158b515fSGeorge Kennedy 
1002158b515fSGeorge Kennedy 	tun->flags = (tun->flags & ~TUN_FEATURES) |
1003158b515fSGeorge Kennedy 		      (ifr->ifr_flags & TUN_FEATURES);
1004158b515fSGeorge Kennedy 
1005158b515fSGeorge Kennedy 	INIT_LIST_HEAD(&tun->disabled);
1006158b515fSGeorge Kennedy 	err = tun_attach(tun, tun->file, false, ifr->ifr_flags & IFF_NAPI,
1007158b515fSGeorge Kennedy 			 ifr->ifr_flags & IFF_NAPI_FRAGS, false);
1008158b515fSGeorge Kennedy 	if (err < 0) {
1009158b515fSGeorge Kennedy 		tun_flow_uninit(tun);
1010158b515fSGeorge Kennedy 		security_tun_dev_free_security(tun->security);
1011158b515fSGeorge Kennedy 		free_percpu(dev->tstats);
1012158b515fSGeorge Kennedy 		return err;
1013158b515fSGeorge Kennedy 	}
1014158b515fSGeorge Kennedy 	return 0;
1015158b515fSGeorge Kennedy }
1016158b515fSGeorge Kennedy 
1017c70f1829SEric W. Biederman /* Net device detach from fd. */
1018c70f1829SEric W. Biederman static void tun_net_uninit(struct net_device *dev)
1019c70f1829SEric W. Biederman {
1020c8d68e6bSJason Wang 	tun_detach_all(dev);
1021c70f1829SEric W. Biederman }
1022c70f1829SEric W. Biederman 
10231da177e4SLinus Torvalds /* Net device open. */
10241da177e4SLinus Torvalds static int tun_net_open(struct net_device *dev)
10251da177e4SLinus Torvalds {
1026c8d68e6bSJason Wang 	netif_tx_start_all_queues(dev);
1027b20e2d54SHannes Frederic Sowa 
10281da177e4SLinus Torvalds 	return 0;
10291da177e4SLinus Torvalds }
10301da177e4SLinus Torvalds 
10311da177e4SLinus Torvalds /* Net device close. */
10321da177e4SLinus Torvalds static int tun_net_close(struct net_device *dev)
10331da177e4SLinus Torvalds {
1034c8d68e6bSJason Wang 	netif_tx_stop_all_queues(dev);
10351da177e4SLinus Torvalds 	return 0;
10361da177e4SLinus Torvalds }
10371da177e4SLinus Torvalds 
10381da177e4SLinus Torvalds /* Net device start xmit */
103996f84061SJason Wang static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
10401da177e4SLinus Torvalds {
10413df97ba8SJason Wang #ifdef CONFIG_RPS
1042dc05360fSEric Dumazet 	if (tun->numqueues == 1 && static_branch_unlikely(&rps_needed)) {
10439bc88939STom Herbert 		/* Select queue was not called for the skbuff, so we extract the
10449bc88939STom Herbert 		 * RPS hash and save it into the flow_table here.
10459bc88939STom Herbert 		 */
10464b035271SWang Li 		struct tun_flow_entry *e;
10479bc88939STom Herbert 		__u32 rxhash;
10489bc88939STom Herbert 
1049feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
10504b035271SWang Li 		e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash);
10519bc88939STom Herbert 		if (e)
10529bc88939STom Herbert 			tun_flow_save_rps_rxhash(e, rxhash);
10539bc88939STom Herbert 	}
10543df97ba8SJason Wang #endif
105596f84061SJason Wang }
105696f84061SJason Wang 
1057aff3d70aSJason Wang static unsigned int run_ebpf_filter(struct tun_struct *tun,
1058aff3d70aSJason Wang 				    struct sk_buff *skb,
1059aff3d70aSJason Wang 				    int len)
1060aff3d70aSJason Wang {
1061aff3d70aSJason Wang 	struct tun_prog *prog = rcu_dereference(tun->filter_prog);
1062aff3d70aSJason Wang 
1063aff3d70aSJason Wang 	if (prog)
1064aff3d70aSJason Wang 		len = bpf_prog_run_clear_cb(prog->prog, skb);
1065aff3d70aSJason Wang 
1066aff3d70aSJason Wang 	return len;
1067aff3d70aSJason Wang }
1068aff3d70aSJason Wang 
106996f84061SJason Wang /* Net device start xmit */
107096f84061SJason Wang static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
107196f84061SJason Wang {
107296f84061SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
10734b4f052eSDongli Zhang 	enum skb_drop_reason drop_reason;
107496f84061SJason Wang 	int txq = skb->queue_mapping;
1075a31d27fbSNicolas Dichtel 	struct netdev_queue *queue;
107696f84061SJason Wang 	struct tun_file *tfile;
1077aff3d70aSJason Wang 	int len = skb->len;
107896f84061SJason Wang 
107996f84061SJason Wang 	rcu_read_lock();
108096f84061SJason Wang 	tfile = rcu_dereference(tun->tfiles[txq]);
108196f84061SJason Wang 
108296f84061SJason Wang 	/* Drop packet if interface is not attached */
10834b4f052eSDongli Zhang 	if (!tfile) {
10844b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_DEV_READY;
108596f84061SJason Wang 		goto drop;
10864b4f052eSDongli Zhang 	}
108796f84061SJason Wang 
108896f84061SJason Wang 	if (!rcu_dereference(tun->steering_prog))
108996f84061SJason Wang 		tun_automq_xmit(tun, skb);
10909bc88939STom Herbert 
10913424170fSMichal Kubecek 	netif_info(tun, tx_queued, tun->dev, "%s %d\n", __func__, skb->len);
10926e914fc7SJason Wang 
1093f271b2ccSMax Krasnyansky 	/* Drop if the filter does not like it.
1094f271b2ccSMax Krasnyansky 	 * This is a noop if the filter is disabled.
1095f271b2ccSMax Krasnyansky 	 * Filter can be enabled only for the TAP devices. */
10964b4f052eSDongli Zhang 	if (!check_filter(&tun->txflt, skb)) {
10974b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_TAP_TXFILTER;
1098f271b2ccSMax Krasnyansky 		goto drop;
10994b4f052eSDongli Zhang 	}
1100f271b2ccSMax Krasnyansky 
110154f968d6SJason Wang 	if (tfile->socket.sk->sk_filter &&
11024b4f052eSDongli Zhang 	    sk_filter(tfile->socket.sk, skb)) {
11034b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
110499405162SMichael S. Tsirkin 		goto drop;
11054b4f052eSDongli Zhang 	}
110699405162SMichael S. Tsirkin 
1107aff3d70aSJason Wang 	len = run_ebpf_filter(tun, skb, len);
11084b4f052eSDongli Zhang 	if (len == 0) {
11094b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_TAP_FILTER;
111045a15d89SDongli Zhang 		goto drop;
11114b4f052eSDongli Zhang 	}
111245a15d89SDongli Zhang 
11134b4f052eSDongli Zhang 	if (pskb_trim(skb, len)) {
11144b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_NOMEM;
1115aff3d70aSJason Wang 		goto drop;
11164b4f052eSDongli Zhang 	}
1117aff3d70aSJason Wang 
11184b4f052eSDongli Zhang 	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) {
11194b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_SKB_UCOPY_FAULT;
11207bf66305SJason Wang 		goto drop;
11214b4f052eSDongli Zhang 	}
11227bf66305SJason Wang 
11237b996243SSoheil Hassas Yeganeh 	skb_tx_timestamp(skb);
1124eda29772SRichard Cochran 
11250110d6f2SMichael S. Tsirkin 	/* Orphan the skb - required as we might hang on to it
11267bf66305SJason Wang 	 * for indefinite time.
11277bf66305SJason Wang 	 */
11280110d6f2SMichael S. Tsirkin 	skb_orphan(skb);
11290110d6f2SMichael S. Tsirkin 
1130895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
1131f8af75f3SEric Dumazet 
11324b4f052eSDongli Zhang 	if (ptr_ring_produce(&tfile->tx_ring, skb)) {
11334b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_FULL_RING;
11341576d986SJason Wang 		goto drop;
11354b4f052eSDongli Zhang 	}
11361da177e4SLinus Torvalds 
1137a31d27fbSNicolas Dichtel 	/* NETIF_F_LLTX requires to do our own update of trans_start */
1138a31d27fbSNicolas Dichtel 	queue = netdev_get_tx_queue(dev, txq);
1139968a1a5dSAntoine Tenart 	txq_trans_cond_update(queue);
1140a31d27fbSNicolas Dichtel 
11411da177e4SLinus Torvalds 	/* Notify and wake up reader process */
114254f968d6SJason Wang 	if (tfile->flags & TUN_FASYNC)
114354f968d6SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
11449e641bdcSXi Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
11456e914fc7SJason Wang 
11466e914fc7SJason Wang 	rcu_read_unlock();
11476ed10654SPatrick McHardy 	return NETDEV_TX_OK;
11481da177e4SLinus Torvalds 
11491da177e4SLinus Torvalds drop:
1150625788b5SEric Dumazet 	dev_core_stats_tx_dropped_inc(dev);
1151149d36f7SMichael S. Tsirkin 	skb_tx_error(skb);
11524b4f052eSDongli Zhang 	kfree_skb_reason(skb, drop_reason);
11536e914fc7SJason Wang 	rcu_read_unlock();
1154baeababbSJason Wang 	return NET_XMIT_DROP;
11551da177e4SLinus Torvalds }
11561da177e4SLinus Torvalds 
1157f271b2ccSMax Krasnyansky static void tun_net_mclist(struct net_device *dev)
11581da177e4SLinus Torvalds {
1159f271b2ccSMax Krasnyansky 	/*
1160f271b2ccSMax Krasnyansky 	 * This callback is supposed to deal with mc filter in
1161f271b2ccSMax Krasnyansky 	 * _rx_ path and has nothing to do with the _tx_ path.
1162f271b2ccSMax Krasnyansky 	 * In rx path we always accept everything userspace gives us.
1163f271b2ccSMax Krasnyansky 	 */
11641da177e4SLinus Torvalds }
11651da177e4SLinus Torvalds 
1166c8f44affSMichał Mirosław static netdev_features_t tun_net_fix_features(struct net_device *dev,
1167c8f44affSMichał Mirosław 	netdev_features_t features)
116888255375SMichał Mirosław {
116988255375SMichał Mirosław 	struct tun_struct *tun = netdev_priv(dev);
117088255375SMichał Mirosław 
117188255375SMichał Mirosław 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
117288255375SMichał Mirosław }
1173eaea34b2SPaolo Abeni 
1174eaea34b2SPaolo Abeni static void tun_set_headroom(struct net_device *dev, int new_hr)
1175eaea34b2SPaolo Abeni {
1176eaea34b2SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1177eaea34b2SPaolo Abeni 
1178eaea34b2SPaolo Abeni 	if (new_hr < NET_SKB_PAD)
1179eaea34b2SPaolo Abeni 		new_hr = NET_SKB_PAD;
1180eaea34b2SPaolo Abeni 
1181eaea34b2SPaolo Abeni 	tun->align = new_hr;
1182eaea34b2SPaolo Abeni }
1183eaea34b2SPaolo Abeni 
1184bc1f4470Sstephen hemminger static void
1185608b9977SPaolo Abeni tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1186608b9977SPaolo Abeni {
1187608b9977SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1188608b9977SPaolo Abeni 
1189497a5757SHeiner Kallweit 	dev_get_tstats64(dev, stats);
1190608b9977SPaolo Abeni 
1191497a5757SHeiner Kallweit 	stats->rx_frame_errors +=
1192497a5757SHeiner Kallweit 		(unsigned long)atomic_long_read(&tun->rx_frame_errors);
1193608b9977SPaolo Abeni }
1194608b9977SPaolo Abeni 
1195761876c8SJason Wang static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1196761876c8SJason Wang 		       struct netlink_ext_ack *extack)
1197761876c8SJason Wang {
1198761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1199e4a2a304SJason Wang 	struct tun_file *tfile;
1200761876c8SJason Wang 	struct bpf_prog *old_prog;
1201e4a2a304SJason Wang 	int i;
1202761876c8SJason Wang 
1203761876c8SJason Wang 	old_prog = rtnl_dereference(tun->xdp_prog);
1204761876c8SJason Wang 	rcu_assign_pointer(tun->xdp_prog, prog);
1205761876c8SJason Wang 	if (old_prog)
1206761876c8SJason Wang 		bpf_prog_put(old_prog);
1207761876c8SJason Wang 
1208e4a2a304SJason Wang 	for (i = 0; i < tun->numqueues; i++) {
1209e4a2a304SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1210e4a2a304SJason Wang 		if (prog)
1211e4a2a304SJason Wang 			sock_set_flag(&tfile->sk, SOCK_XDP);
1212e4a2a304SJason Wang 		else
1213e4a2a304SJason Wang 			sock_reset_flag(&tfile->sk, SOCK_XDP);
1214e4a2a304SJason Wang 	}
1215e4a2a304SJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
1216e4a2a304SJason Wang 		if (prog)
1217e4a2a304SJason Wang 			sock_set_flag(&tfile->sk, SOCK_XDP);
1218e4a2a304SJason Wang 		else
1219e4a2a304SJason Wang 			sock_reset_flag(&tfile->sk, SOCK_XDP);
1220e4a2a304SJason Wang 	}
1221e4a2a304SJason Wang 
1222761876c8SJason Wang 	return 0;
1223761876c8SJason Wang }
1224761876c8SJason Wang 
1225f4e63525SJakub Kicinski static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1226761876c8SJason Wang {
1227761876c8SJason Wang 	switch (xdp->command) {
1228761876c8SJason Wang 	case XDP_SETUP_PROG:
1229761876c8SJason Wang 		return tun_xdp_set(dev, xdp->prog, xdp->extack);
1230761876c8SJason Wang 	default:
1231761876c8SJason Wang 		return -EINVAL;
1232761876c8SJason Wang 	}
1233761876c8SJason Wang }
1234761876c8SJason Wang 
123526d31925SNicolas Dichtel static int tun_net_change_carrier(struct net_device *dev, bool new_carrier)
123626d31925SNicolas Dichtel {
123726d31925SNicolas Dichtel 	if (new_carrier) {
123826d31925SNicolas Dichtel 		struct tun_struct *tun = netdev_priv(dev);
123926d31925SNicolas Dichtel 
124026d31925SNicolas Dichtel 		if (!tun->numqueues)
124126d31925SNicolas Dichtel 			return -EPERM;
124226d31925SNicolas Dichtel 
124326d31925SNicolas Dichtel 		netif_carrier_on(dev);
124426d31925SNicolas Dichtel 	} else {
124526d31925SNicolas Dichtel 		netif_carrier_off(dev);
124626d31925SNicolas Dichtel 	}
124726d31925SNicolas Dichtel 	return 0;
124826d31925SNicolas Dichtel }
124926d31925SNicolas Dichtel 
1250758e43b7SStephen Hemminger static const struct net_device_ops tun_netdev_ops = {
1251158b515fSGeorge Kennedy 	.ndo_init		= tun_net_init,
1252c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1253758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1254758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
125500829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
125688255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1257c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
1258eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1259608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
126026d31925SNicolas Dichtel 	.ndo_change_carrier	= tun_net_change_carrier,
1261758e43b7SStephen Hemminger };
1262758e43b7SStephen Hemminger 
12630c9d917bSJesper Dangaard Brouer static void __tun_xdp_flush_tfile(struct tun_file *tfile)
12640c9d917bSJesper Dangaard Brouer {
12650c9d917bSJesper Dangaard Brouer 	/* Notify and wake up reader process */
12660c9d917bSJesper Dangaard Brouer 	if (tfile->flags & TUN_FASYNC)
12670c9d917bSJesper Dangaard Brouer 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
12680c9d917bSJesper Dangaard Brouer 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
12690c9d917bSJesper Dangaard Brouer }
12700c9d917bSJesper Dangaard Brouer 
127142b33468SJesper Dangaard Brouer static int tun_xdp_xmit(struct net_device *dev, int n,
127242b33468SJesper Dangaard Brouer 			struct xdp_frame **frames, u32 flags)
1273fc72d1d5SJason Wang {
1274fc72d1d5SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1275fc72d1d5SJason Wang 	struct tun_file *tfile;
1276fc72d1d5SJason Wang 	u32 numqueues;
1277fdc13979SLorenzo Bianconi 	int nxmit = 0;
1278735fc405SJesper Dangaard Brouer 	int i;
1279fc72d1d5SJason Wang 
12800c9d917bSJesper Dangaard Brouer 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
128142b33468SJesper Dangaard Brouer 		return -EINVAL;
128242b33468SJesper Dangaard Brouer 
1283fc72d1d5SJason Wang 	rcu_read_lock();
1284fc72d1d5SJason Wang 
12859871a9e4SJason Wang resample:
1286fc72d1d5SJason Wang 	numqueues = READ_ONCE(tun->numqueues);
1287fc72d1d5SJason Wang 	if (!numqueues) {
1288735fc405SJesper Dangaard Brouer 		rcu_read_unlock();
1289735fc405SJesper Dangaard Brouer 		return -ENXIO; /* Caller will free/return all frames */
1290fc72d1d5SJason Wang 	}
1291fc72d1d5SJason Wang 
1292fc72d1d5SJason Wang 	tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1293fc72d1d5SJason Wang 					    numqueues]);
12949871a9e4SJason Wang 	if (unlikely(!tfile))
12959871a9e4SJason Wang 		goto resample;
1296735fc405SJesper Dangaard Brouer 
1297735fc405SJesper Dangaard Brouer 	spin_lock(&tfile->tx_ring.producer_lock);
1298735fc405SJesper Dangaard Brouer 	for (i = 0; i < n; i++) {
1299735fc405SJesper Dangaard Brouer 		struct xdp_frame *xdp = frames[i];
1300fc72d1d5SJason Wang 		/* Encode the XDP flag into lowest bit for consumer to differ
1301fc72d1d5SJason Wang 		 * XDP buffer from sk_buff.
1302fc72d1d5SJason Wang 		 */
1303735fc405SJesper Dangaard Brouer 		void *frame = tun_xdp_to_ptr(xdp);
1304fc72d1d5SJason Wang 
1305735fc405SJesper Dangaard Brouer 		if (__ptr_ring_produce(&tfile->tx_ring, frame)) {
1306625788b5SEric Dumazet 			dev_core_stats_tx_dropped_inc(dev);
1307fdc13979SLorenzo Bianconi 			break;
1308735fc405SJesper Dangaard Brouer 		}
1309fdc13979SLorenzo Bianconi 		nxmit++;
1310735fc405SJesper Dangaard Brouer 	}
1311735fc405SJesper Dangaard Brouer 	spin_unlock(&tfile->tx_ring.producer_lock);
1312735fc405SJesper Dangaard Brouer 
13130c9d917bSJesper Dangaard Brouer 	if (flags & XDP_XMIT_FLUSH)
13140c9d917bSJesper Dangaard Brouer 		__tun_xdp_flush_tfile(tfile);
13150c9d917bSJesper Dangaard Brouer 
1316fc72d1d5SJason Wang 	rcu_read_unlock();
1317fdc13979SLorenzo Bianconi 	return nxmit;
1318fc72d1d5SJason Wang }
1319fc72d1d5SJason Wang 
132044fa2dbdSJesper Dangaard Brouer static int tun_xdp_tx(struct net_device *dev, struct xdp_buff *xdp)
132144fa2dbdSJesper Dangaard Brouer {
13221b698fa5SLorenzo Bianconi 	struct xdp_frame *frame = xdp_convert_buff_to_frame(xdp);
1323fdc13979SLorenzo Bianconi 	int nxmit;
132444fa2dbdSJesper Dangaard Brouer 
132544fa2dbdSJesper Dangaard Brouer 	if (unlikely(!frame))
132644fa2dbdSJesper Dangaard Brouer 		return -EOVERFLOW;
132744fa2dbdSJesper Dangaard Brouer 
1328fdc13979SLorenzo Bianconi 	nxmit = tun_xdp_xmit(dev, 1, &frame, XDP_XMIT_FLUSH);
1329fdc13979SLorenzo Bianconi 	if (!nxmit)
1330fdc13979SLorenzo Bianconi 		xdp_return_frame_rx_napi(frame);
1331fdc13979SLorenzo Bianconi 	return nxmit;
1332fc72d1d5SJason Wang }
1333fc72d1d5SJason Wang 
1334758e43b7SStephen Hemminger static const struct net_device_ops tap_netdev_ops = {
1335158b515fSGeorge Kennedy 	.ndo_init		= tun_net_init,
1336c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1337758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1338758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
133900829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
134088255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1341afc4b13dSJiri Pirko 	.ndo_set_rx_mode	= tun_net_mclist,
1342758e43b7SStephen Hemminger 	.ndo_set_mac_address	= eth_mac_addr,
1343758e43b7SStephen Hemminger 	.ndo_validate_addr	= eth_validate_addr,
1344c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
13455e52796aSToshiaki Makita 	.ndo_features_check	= passthru_features_check,
1346eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1347497a5757SHeiner Kallweit 	.ndo_get_stats64	= dev_get_tstats64,
1348f4e63525SJakub Kicinski 	.ndo_bpf		= tun_xdp,
1349fc72d1d5SJason Wang 	.ndo_xdp_xmit		= tun_xdp_xmit,
135026d31925SNicolas Dichtel 	.ndo_change_carrier	= tun_net_change_carrier,
1351758e43b7SStephen Hemminger };
1352758e43b7SStephen Hemminger 
1353944a1376SPavel Emelyanov static void tun_flow_init(struct tun_struct *tun)
135496442e42SJason Wang {
135596442e42SJason Wang 	int i;
135696442e42SJason Wang 
135796442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
135896442e42SJason Wang 		INIT_HLIST_HEAD(&tun->flows[i]);
135996442e42SJason Wang 
136096442e42SJason Wang 	tun->ageing_time = TUN_FLOW_EXPIRE;
1361e99e88a9SKees Cook 	timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1362e99e88a9SKees Cook 	mod_timer(&tun->flow_gc_timer,
1363e99e88a9SKees Cook 		  round_jiffies_up(jiffies + tun->ageing_time));
136496442e42SJason Wang }
136596442e42SJason Wang 
136696442e42SJason Wang static void tun_flow_uninit(struct tun_struct *tun)
136796442e42SJason Wang {
136896442e42SJason Wang 	del_timer_sync(&tun->flow_gc_timer);
136996442e42SJason Wang 	tun_flow_flush(tun);
137096442e42SJason Wang }
137196442e42SJason Wang 
137291572088SJarod Wilson #define MIN_MTU 68
137391572088SJarod Wilson #define MAX_MTU 65535
137491572088SJarod Wilson 
13751da177e4SLinus Torvalds /* Initialize net device. */
1376158b515fSGeorge Kennedy static void tun_net_initialize(struct net_device *dev)
13771da177e4SLinus Torvalds {
13781da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
13791da177e4SLinus Torvalds 
13801da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
138140630b82SMichael S. Tsirkin 	case IFF_TUN:
1382758e43b7SStephen Hemminger 		dev->netdev_ops = &tun_netdev_ops;
1383b9815eb1SJason A. Donenfeld 		dev->header_ops = &ip_tunnel_header_ops;
1384758e43b7SStephen Hemminger 
13851da177e4SLinus Torvalds 		/* Point-to-Point TUN Device */
13861da177e4SLinus Torvalds 		dev->hard_header_len = 0;
13871da177e4SLinus Torvalds 		dev->addr_len = 0;
13881da177e4SLinus Torvalds 		dev->mtu = 1500;
13891da177e4SLinus Torvalds 
13901da177e4SLinus Torvalds 		/* Zero header length */
13911da177e4SLinus Torvalds 		dev->type = ARPHRD_NONE;
13921da177e4SLinus Torvalds 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
13931da177e4SLinus Torvalds 		break;
13941da177e4SLinus Torvalds 
139540630b82SMichael S. Tsirkin 	case IFF_TAP:
13967a0a9608SKusanagi Kouichi 		dev->netdev_ops = &tap_netdev_ops;
13971da177e4SLinus Torvalds 		/* Ethernet TAP Device */
13981da177e4SLinus Torvalds 		ether_setup(dev);
1399550fd08cSNeil Horman 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1400a676847bSstephen hemminger 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
140136226a8dSBrian Braunstein 
1402f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
140336226a8dSBrian Braunstein 
140466c0e13aSMarek Majtyka 		/* Currently tun does not support XDP, only tap does. */
140566c0e13aSMarek Majtyka 		dev->xdp_features = NETDEV_XDP_ACT_BASIC |
140666c0e13aSMarek Majtyka 				    NETDEV_XDP_ACT_REDIRECT |
140766c0e13aSMarek Majtyka 				    NETDEV_XDP_ACT_NDO_XMIT;
140866c0e13aSMarek Majtyka 
14091da177e4SLinus Torvalds 		break;
14101da177e4SLinus Torvalds 	}
141191572088SJarod Wilson 
141291572088SJarod Wilson 	dev->min_mtu = MIN_MTU;
141391572088SJarod Wilson 	dev->max_mtu = MAX_MTU - dev->hard_header_len;
14141da177e4SLinus Torvalds }
14151da177e4SLinus Torvalds 
14162f3ab622SJason Wang static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
14172f3ab622SJason Wang {
14182f3ab622SJason Wang 	struct sock *sk = tfile->socket.sk;
14192f3ab622SJason Wang 
14202f3ab622SJason Wang 	return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
14212f3ab622SJason Wang }
14222f3ab622SJason Wang 
14231da177e4SLinus Torvalds /* Character device part */
14241da177e4SLinus Torvalds 
14251da177e4SLinus Torvalds /* Poll */
1426afc9a42bSAl Viro static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
14271da177e4SLinus Torvalds {
1428b2430de3SEric W. Biederman 	struct tun_file *tfile = file->private_data;
14299484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
14303c8a9c63SMariusz Kozlowski 	struct sock *sk;
1431afc9a42bSAl Viro 	__poll_t mask = 0;
14321da177e4SLinus Torvalds 
14331da177e4SLinus Torvalds 	if (!tun)
1434a9a08845SLinus Torvalds 		return EPOLLERR;
14351da177e4SLinus Torvalds 
143654f968d6SJason Wang 	sk = tfile->socket.sk;
14373c8a9c63SMariusz Kozlowski 
14389e641bdcSXi Wang 	poll_wait(file, sk_sleep(sk), wait);
14391da177e4SLinus Torvalds 
14405990a305SJason Wang 	if (!ptr_ring_empty(&tfile->tx_ring))
1441a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
14421da177e4SLinus Torvalds 
14432f3ab622SJason Wang 	/* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
14442f3ab622SJason Wang 	 * guarantee EPOLLOUT to be raised by either here or
14452f3ab622SJason Wang 	 * tun_sock_write_space(). Then process could get notification
14462f3ab622SJason Wang 	 * after it writes to a down device and meets -EIO.
14472f3ab622SJason Wang 	 */
14482f3ab622SJason Wang 	if (tun_sock_writeable(tun, tfile) ||
14499cd3e072SEric Dumazet 	    (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
14502f3ab622SJason Wang 	     tun_sock_writeable(tun, tfile)))
1451a9a08845SLinus Torvalds 		mask |= EPOLLOUT | EPOLLWRNORM;
145233dccbb0SHerbert Xu 
1453c70f1829SEric W. Biederman 	if (tun->dev->reg_state != NETREG_REGISTERED)
1454a9a08845SLinus Torvalds 		mask = EPOLLERR;
1455c70f1829SEric W. Biederman 
1456631ab46bSEric W. Biederman 	tun_put(tun);
14571da177e4SLinus Torvalds 	return mask;
14581da177e4SLinus Torvalds }
14591da177e4SLinus Torvalds 
146090e33d45SPetar Penkov static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
146190e33d45SPetar Penkov 					    size_t len,
146290e33d45SPetar Penkov 					    const struct iov_iter *it)
146390e33d45SPetar Penkov {
146490e33d45SPetar Penkov 	struct sk_buff *skb;
146590e33d45SPetar Penkov 	size_t linear;
146690e33d45SPetar Penkov 	int err;
146790e33d45SPetar Penkov 	int i;
146890e33d45SPetar Penkov 
1469363a5328SZiyang Xuan 	if (it->nr_segs > MAX_SKB_FRAGS + 1 ||
1470363a5328SZiyang Xuan 	    len > (ETH_MAX_MTU - NET_SKB_PAD - NET_IP_ALIGN))
1471950271d7SYunjian Wang 		return ERR_PTR(-EMSGSIZE);
147290e33d45SPetar Penkov 
147390e33d45SPetar Penkov 	local_bh_disable();
147490e33d45SPetar Penkov 	skb = napi_get_frags(&tfile->napi);
147590e33d45SPetar Penkov 	local_bh_enable();
147690e33d45SPetar Penkov 	if (!skb)
147790e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
147890e33d45SPetar Penkov 
147990e33d45SPetar Penkov 	linear = iov_iter_single_seg_count(it);
148090e33d45SPetar Penkov 	err = __skb_grow(skb, linear);
148190e33d45SPetar Penkov 	if (err)
148290e33d45SPetar Penkov 		goto free;
148390e33d45SPetar Penkov 
148490e33d45SPetar Penkov 	skb->len = len;
148590e33d45SPetar Penkov 	skb->data_len = len - linear;
148690e33d45SPetar Penkov 	skb->truesize += skb->data_len;
148790e33d45SPetar Penkov 
148890e33d45SPetar Penkov 	for (i = 1; i < it->nr_segs; i++) {
1489de4f5fedSJens Axboe 		const struct iovec *iov = iter_iov(it);
1490de4f5fedSJens Axboe 		size_t fragsz = iov->iov_len;
1491aa6daacaSEric Dumazet 		struct page *page;
1492aa6daacaSEric Dumazet 		void *frag;
149390e33d45SPetar Penkov 
149490e33d45SPetar Penkov 		if (fragsz == 0 || fragsz > PAGE_SIZE) {
149590e33d45SPetar Penkov 			err = -EINVAL;
149690e33d45SPetar Penkov 			goto free;
149790e33d45SPetar Penkov 		}
1498aa6daacaSEric Dumazet 		frag = netdev_alloc_frag(fragsz);
1499aa6daacaSEric Dumazet 		if (!frag) {
150090e33d45SPetar Penkov 			err = -ENOMEM;
150190e33d45SPetar Penkov 			goto free;
150290e33d45SPetar Penkov 		}
1503aa6daacaSEric Dumazet 		page = virt_to_head_page(frag);
1504aa6daacaSEric Dumazet 		skb_fill_page_desc(skb, i - 1, page,
1505aa6daacaSEric Dumazet 				   frag - page_address(page), fragsz);
150690e33d45SPetar Penkov 	}
150790e33d45SPetar Penkov 
150890e33d45SPetar Penkov 	return skb;
150990e33d45SPetar Penkov free:
151090e33d45SPetar Penkov 	/* frees skb and all frags allocated with napi_alloc_frag() */
151190e33d45SPetar Penkov 	napi_free_frags(&tfile->napi);
151290e33d45SPetar Penkov 	return ERR_PTR(err);
151390e33d45SPetar Penkov }
151490e33d45SPetar Penkov 
1515f42157cbSRusty Russell /* prepad is the amount to reserve at front.  len is length after that.
1516f42157cbSRusty Russell  * linear is a hint as to how much to copy (usually headers). */
151754f968d6SJason Wang static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
151833dccbb0SHerbert Xu 				     size_t prepad, size_t len,
151933dccbb0SHerbert Xu 				     size_t linear, int noblock)
1520f42157cbSRusty Russell {
152154f968d6SJason Wang 	struct sock *sk = tfile->socket.sk;
1522f42157cbSRusty Russell 	struct sk_buff *skb;
152333dccbb0SHerbert Xu 	int err;
1524f42157cbSRusty Russell 
1525f42157cbSRusty Russell 	/* Under a page?  Don't bother with paged skb. */
15260eca93bcSHerbert Xu 	if (prepad + len < PAGE_SIZE || !linear)
152733dccbb0SHerbert Xu 		linear = len;
1528f42157cbSRusty Russell 
152933dccbb0SHerbert Xu 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
153028d64271SEric Dumazet 				   &err, 0);
1531f42157cbSRusty Russell 	if (!skb)
153233dccbb0SHerbert Xu 		return ERR_PTR(err);
1533f42157cbSRusty Russell 
1534f42157cbSRusty Russell 	skb_reserve(skb, prepad);
1535f42157cbSRusty Russell 	skb_put(skb, linear);
153633dccbb0SHerbert Xu 	skb->data_len = len - linear;
153733dccbb0SHerbert Xu 	skb->len += len - linear;
1538f42157cbSRusty Russell 
1539f42157cbSRusty Russell 	return skb;
1540f42157cbSRusty Russell }
1541f42157cbSRusty Russell 
15425503fcecSJason Wang static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
15435503fcecSJason Wang 			   struct sk_buff *skb, int more)
15445503fcecSJason Wang {
15455503fcecSJason Wang 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
15465503fcecSJason Wang 	struct sk_buff_head process_queue;
15475503fcecSJason Wang 	u32 rx_batched = tun->rx_batched;
15485503fcecSJason Wang 	bool rcv = false;
15495503fcecSJason Wang 
15505503fcecSJason Wang 	if (!rx_batched || (!more && skb_queue_empty(queue))) {
15515503fcecSJason Wang 		local_bh_disable();
15528ebebcbaSMatthew Cover 		skb_record_rx_queue(skb, tfile->queue_index);
15535503fcecSJason Wang 		netif_receive_skb(skb);
15545503fcecSJason Wang 		local_bh_enable();
15555503fcecSJason Wang 		return;
15565503fcecSJason Wang 	}
15575503fcecSJason Wang 
15585503fcecSJason Wang 	spin_lock(&queue->lock);
15595503fcecSJason Wang 	if (!more || skb_queue_len(queue) == rx_batched) {
15605503fcecSJason Wang 		__skb_queue_head_init(&process_queue);
15615503fcecSJason Wang 		skb_queue_splice_tail_init(queue, &process_queue);
15625503fcecSJason Wang 		rcv = true;
15635503fcecSJason Wang 	} else {
15645503fcecSJason Wang 		__skb_queue_tail(queue, skb);
15655503fcecSJason Wang 	}
15665503fcecSJason Wang 	spin_unlock(&queue->lock);
15675503fcecSJason Wang 
15685503fcecSJason Wang 	if (rcv) {
15695503fcecSJason Wang 		struct sk_buff *nskb;
15705503fcecSJason Wang 
15715503fcecSJason Wang 		local_bh_disable();
15728ebebcbaSMatthew Cover 		while ((nskb = __skb_dequeue(&process_queue))) {
15738ebebcbaSMatthew Cover 			skb_record_rx_queue(nskb, tfile->queue_index);
15745503fcecSJason Wang 			netif_receive_skb(nskb);
15758ebebcbaSMatthew Cover 		}
15768ebebcbaSMatthew Cover 		skb_record_rx_queue(skb, tfile->queue_index);
15775503fcecSJason Wang 		netif_receive_skb(skb);
15785503fcecSJason Wang 		local_bh_enable();
15795503fcecSJason Wang 	}
15805503fcecSJason Wang }
15815503fcecSJason Wang 
158266ccbc9cSJason Wang static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
158366ccbc9cSJason Wang 			      int len, int noblock, bool zerocopy)
158466ccbc9cSJason Wang {
158566ccbc9cSJason Wang 	if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
158666ccbc9cSJason Wang 		return false;
158766ccbc9cSJason Wang 
158866ccbc9cSJason Wang 	if (tfile->socket.sk->sk_sndbuf != INT_MAX)
158966ccbc9cSJason Wang 		return false;
159066ccbc9cSJason Wang 
159166ccbc9cSJason Wang 	if (!noblock)
159266ccbc9cSJason Wang 		return false;
159366ccbc9cSJason Wang 
159466ccbc9cSJason Wang 	if (zerocopy)
159566ccbc9cSJason Wang 		return false;
159666ccbc9cSJason Wang 
159766ccbc9cSJason Wang 	if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
159866ccbc9cSJason Wang 	    SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
159966ccbc9cSJason Wang 		return false;
160066ccbc9cSJason Wang 
160166ccbc9cSJason Wang 	return true;
160266ccbc9cSJason Wang }
160366ccbc9cSJason Wang 
16044b663366SAlexis Bauvin static struct sk_buff *__tun_build_skb(struct tun_file *tfile,
16054b663366SAlexis Bauvin 				       struct page_frag *alloc_frag, char *buf,
16068ae1aff0SJason Wang 				       int buflen, int len, int pad)
1607ac1f1f6cSJason Wang {
1608ac1f1f6cSJason Wang 	struct sk_buff *skb = build_skb(buf, buflen);
1609ac1f1f6cSJason Wang 
1610ac1f1f6cSJason Wang 	if (!skb)
1611ac1f1f6cSJason Wang 		return ERR_PTR(-ENOMEM);
1612ac1f1f6cSJason Wang 
16138ae1aff0SJason Wang 	skb_reserve(skb, pad);
1614ac1f1f6cSJason Wang 	skb_put(skb, len);
16154b663366SAlexis Bauvin 	skb_set_owner_w(skb, tfile->socket.sk);
1616ac1f1f6cSJason Wang 
1617ac1f1f6cSJason Wang 	get_page(alloc_frag->page);
1618ac1f1f6cSJason Wang 	alloc_frag->offset += buflen;
1619ac1f1f6cSJason Wang 
1620ac1f1f6cSJason Wang 	return skb;
1621ac1f1f6cSJason Wang }
1622ac1f1f6cSJason Wang 
16238ae1aff0SJason Wang static int tun_xdp_act(struct tun_struct *tun, struct bpf_prog *xdp_prog,
16248ae1aff0SJason Wang 		       struct xdp_buff *xdp, u32 act)
16258ae1aff0SJason Wang {
16268ae1aff0SJason Wang 	int err;
16278ae1aff0SJason Wang 
16288ae1aff0SJason Wang 	switch (act) {
16298ae1aff0SJason Wang 	case XDP_REDIRECT:
16308ae1aff0SJason Wang 		err = xdp_do_redirect(tun->dev, xdp, xdp_prog);
16318ae1aff0SJason Wang 		if (err)
16328ae1aff0SJason Wang 			return err;
16338ae1aff0SJason Wang 		break;
16348ae1aff0SJason Wang 	case XDP_TX:
16358ae1aff0SJason Wang 		err = tun_xdp_tx(tun->dev, xdp);
16368ae1aff0SJason Wang 		if (err < 0)
16378ae1aff0SJason Wang 			return err;
16388ae1aff0SJason Wang 		break;
16398ae1aff0SJason Wang 	case XDP_PASS:
16408ae1aff0SJason Wang 		break;
16418ae1aff0SJason Wang 	default:
1642c8064e5bSPaolo Abeni 		bpf_warn_invalid_xdp_action(tun->dev, xdp_prog, act);
1643df561f66SGustavo A. R. Silva 		fallthrough;
16448ae1aff0SJason Wang 	case XDP_ABORTED:
16458ae1aff0SJason Wang 		trace_xdp_exception(tun->dev, xdp_prog, act);
1646df561f66SGustavo A. R. Silva 		fallthrough;
16478ae1aff0SJason Wang 	case XDP_DROP:
1648625788b5SEric Dumazet 		dev_core_stats_rx_dropped_inc(tun->dev);
16498ae1aff0SJason Wang 		break;
16508ae1aff0SJason Wang 	}
16518ae1aff0SJason Wang 
16528ae1aff0SJason Wang 	return act;
16538ae1aff0SJason Wang }
16548ae1aff0SJason Wang 
1655761876c8SJason Wang static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1656761876c8SJason Wang 				     struct tun_file *tfile,
165766ccbc9cSJason Wang 				     struct iov_iter *from,
1658761876c8SJason Wang 				     struct virtio_net_hdr *hdr,
16591cfe6e93SJason Wang 				     int len, int *skb_xdp)
166066ccbc9cSJason Wang {
16610bbd7dadSEric Dumazet 	struct page_frag *alloc_frag = &current->task_frag;
1662761876c8SJason Wang 	struct bpf_prog *xdp_prog;
16637df13219SJason Wang 	int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
166466ccbc9cSJason Wang 	char *buf;
166566ccbc9cSJason Wang 	size_t copied;
16668ae1aff0SJason Wang 	int pad = TUN_RX_PAD;
16678ae1aff0SJason Wang 	int err = 0;
16687df13219SJason Wang 
16697df13219SJason Wang 	rcu_read_lock();
16707df13219SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
16717df13219SJason Wang 	if (xdp_prog)
16724f23aff8SJason Wang 		pad += XDP_PACKET_HEADROOM;
16737df13219SJason Wang 	buflen += SKB_DATA_ALIGN(len + pad);
16747df13219SJason Wang 	rcu_read_unlock();
167566ccbc9cSJason Wang 
167663b9ab65SJason Wang 	alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
167766ccbc9cSJason Wang 	if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
167866ccbc9cSJason Wang 		return ERR_PTR(-ENOMEM);
167966ccbc9cSJason Wang 
168066ccbc9cSJason Wang 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
168166ccbc9cSJason Wang 	copied = copy_page_from_iter(alloc_frag->page,
16827df13219SJason Wang 				     alloc_frag->offset + pad,
168366ccbc9cSJason Wang 				     len, from);
168466ccbc9cSJason Wang 	if (copied != len)
168566ccbc9cSJason Wang 		return ERR_PTR(-EFAULT);
168666ccbc9cSJason Wang 
16877df13219SJason Wang 	/* There's a small window that XDP may be set after the check
16887df13219SJason Wang 	 * of xdp_prog above, this should be rare and for simplicity
16897df13219SJason Wang 	 * we do XDP on skb in case the headroom is not enough.
16907df13219SJason Wang 	 */
1691ac1f1f6cSJason Wang 	if (hdr->gso_type || !xdp_prog) {
16921cfe6e93SJason Wang 		*skb_xdp = 1;
16934b663366SAlexis Bauvin 		return __tun_build_skb(tfile, alloc_frag, buf, buflen, len,
16944b663366SAlexis Bauvin 				       pad);
1695ac1f1f6cSJason Wang 	}
1696ac1f1f6cSJason Wang 
16971cfe6e93SJason Wang 	*skb_xdp = 0;
169866ccbc9cSJason Wang 
16996547e387SToshiaki Makita 	local_bh_disable();
1700761876c8SJason Wang 	rcu_read_lock();
1701761876c8SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
17028ae1aff0SJason Wang 	if (xdp_prog) {
1703761876c8SJason Wang 		struct xdp_buff xdp;
1704761876c8SJason Wang 		u32 act;
1705761876c8SJason Wang 
170643b5169dSLorenzo Bianconi 		xdp_init_buff(&xdp, buflen, &tfile->xdp_rxq);
1707be9df4afSLorenzo Bianconi 		xdp_prepare_buff(&xdp, buf, pad, len, false);
1708761876c8SJason Wang 
17098ae1aff0SJason Wang 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
17108ae1aff0SJason Wang 		if (act == XDP_REDIRECT || act == XDP_TX) {
1711761876c8SJason Wang 			get_page(alloc_frag->page);
1712761876c8SJason Wang 			alloc_frag->offset += buflen;
1713761876c8SJason Wang 		}
17148ae1aff0SJason Wang 		err = tun_xdp_act(tun, xdp_prog, &xdp, act);
1715bee34890SWill Deacon 		if (err < 0) {
1716bee34890SWill Deacon 			if (act == XDP_REDIRECT || act == XDP_TX)
1717bee34890SWill Deacon 				put_page(alloc_frag->page);
1718bee34890SWill Deacon 			goto out;
1719bee34890SWill Deacon 		}
1720bee34890SWill Deacon 
17211a097910SJason Wang 		if (err == XDP_REDIRECT)
17221d233886SToke Høiland-Jørgensen 			xdp_do_flush();
17238ae1aff0SJason Wang 		if (err != XDP_PASS)
17248ae1aff0SJason Wang 			goto out;
17258ae1aff0SJason Wang 
17268ae1aff0SJason Wang 		pad = xdp.data - xdp.data_hard_start;
17278ae1aff0SJason Wang 		len = xdp.data_end - xdp.data;
1728761876c8SJason Wang 	}
1729761876c8SJason Wang 	rcu_read_unlock();
17306547e387SToshiaki Makita 	local_bh_enable();
1731291aeb2bSJason Wang 
17324b663366SAlexis Bauvin 	return __tun_build_skb(tfile, alloc_frag, buf, buflen, len, pad);
1733761876c8SJason Wang 
1734f7053b6cSJason Wang out:
1735761876c8SJason Wang 	rcu_read_unlock();
17366547e387SToshiaki Makita 	local_bh_enable();
1737761876c8SJason Wang 	return NULL;
173866ccbc9cSJason Wang }
173966ccbc9cSJason Wang 
17401da177e4SLinus Torvalds /* Get packet from user space buffer */
174154f968d6SJason Wang static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1742f5ff53b4SAl Viro 			    void *msg_control, struct iov_iter *from,
17435503fcecSJason Wang 			    int noblock, bool more)
17441da177e4SLinus Torvalds {
174509640e63SHarvey Harrison 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
17461da177e4SLinus Torvalds 	struct sk_buff *skb;
1747f5ff53b4SAl Viro 	size_t total_len = iov_iter_count(from);
1748eaea34b2SPaolo Abeni 	size_t len = total_len, align = tun->align, linear;
1749f43798c2SRusty Russell 	struct virtio_net_hdr gso = { 0 };
175096f8d9ecSJason Wang 	int good_linear;
17510690899bSMichael S. Tsirkin 	int copylen;
17520690899bSMichael S. Tsirkin 	bool zerocopy = false;
17530690899bSMichael S. Tsirkin 	int err;
175496f84061SJason Wang 	u32 rxhash = 0;
17551cfe6e93SJason Wang 	int skb_xdp = 1;
1756af3fb24eSEric Dumazet 	bool frags = tun_napi_frags_enabled(tfile);
1757ab00af85SChuang Wang 	enum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
17581da177e4SLinus Torvalds 
175940630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
176015718ea0SDan Carpenter 		if (len < sizeof(pi))
17611da177e4SLinus Torvalds 			return -EINVAL;
176215718ea0SDan Carpenter 		len -= sizeof(pi);
17631da177e4SLinus Torvalds 
1764cbbd26b8SAl Viro 		if (!copy_from_iter_full(&pi, sizeof(pi), from))
17651da177e4SLinus Torvalds 			return -EFAULT;
17661da177e4SLinus Torvalds 	}
17671da177e4SLinus Torvalds 
176840630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR) {
1769e1edab87SWillem de Bruijn 		int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1770e1edab87SWillem de Bruijn 
1771e1edab87SWillem de Bruijn 		if (len < vnet_hdr_sz)
1772f43798c2SRusty Russell 			return -EINVAL;
1773e1edab87SWillem de Bruijn 		len -= vnet_hdr_sz;
1774f43798c2SRusty Russell 
1775cbbd26b8SAl Viro 		if (!copy_from_iter_full(&gso, sizeof(gso), from))
1776f43798c2SRusty Russell 			return -EFAULT;
1777f43798c2SRusty Russell 
17784909122fSHerbert Xu 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
177956f0dcc5SMichael S. Tsirkin 		    tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
178056f0dcc5SMichael S. Tsirkin 			gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
17814909122fSHerbert Xu 
178256f0dcc5SMichael S. Tsirkin 		if (tun16_to_cpu(tun, gso.hdr_len) > len)
1783f43798c2SRusty Russell 			return -EINVAL;
1784e1edab87SWillem de Bruijn 		iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1785f43798c2SRusty Russell 	}
1786f43798c2SRusty Russell 
178740630b82SMichael S. Tsirkin 	if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1788a504b86eSstephen hemminger 		align += NET_IP_ALIGN;
17890eca93bcSHerbert Xu 		if (unlikely(len < ETH_HLEN ||
179056f0dcc5SMichael S. Tsirkin 			     (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1791e01bf1c8SRusty Russell 			return -EINVAL;
1792e01bf1c8SRusty Russell 	}
17931da177e4SLinus Torvalds 
179496f8d9ecSJason Wang 	good_linear = SKB_MAX_HEAD(align);
179596f8d9ecSJason Wang 
179688529176SJason Wang 	if (msg_control) {
1797f5ff53b4SAl Viro 		struct iov_iter i = *from;
1798f5ff53b4SAl Viro 
179988529176SJason Wang 		/* There are 256 bytes to be copied in skb, so there is
180088529176SJason Wang 		 * enough room for skb expand head in case it is used.
18010690899bSMichael S. Tsirkin 		 * The rest of the buffer is mapped from userspace.
18020690899bSMichael S. Tsirkin 		 */
180356f0dcc5SMichael S. Tsirkin 		copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
180496f8d9ecSJason Wang 		if (copylen > good_linear)
180596f8d9ecSJason Wang 			copylen = good_linear;
18063dd5c330SJason Wang 		linear = copylen;
1807f5ff53b4SAl Viro 		iov_iter_advance(&i, copylen);
1808f5ff53b4SAl Viro 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
180988529176SJason Wang 			zerocopy = true;
181088529176SJason Wang 	}
181188529176SJason Wang 
181290e33d45SPetar Penkov 	if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
18131cfe6e93SJason Wang 		/* For the packet that is not easy to be processed
18141cfe6e93SJason Wang 		 * (e.g gso or jumbo packet), we will do it at after
18151cfe6e93SJason Wang 		 * skb was created with generic XDP routine.
18161cfe6e93SJason Wang 		 */
18171cfe6e93SJason Wang 		skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
1818ab00af85SChuang Wang 		err = PTR_ERR_OR_ZERO(skb);
1819ab00af85SChuang Wang 		if (err)
1820ab00af85SChuang Wang 			goto drop;
1821761876c8SJason Wang 		if (!skb)
1822761876c8SJason Wang 			return total_len;
182366ccbc9cSJason Wang 	} else {
182488529176SJason Wang 		if (!zerocopy) {
18250690899bSMichael S. Tsirkin 			copylen = len;
182656f0dcc5SMichael S. Tsirkin 			if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
182796f8d9ecSJason Wang 				linear = good_linear;
182896f8d9ecSJason Wang 			else
182956f0dcc5SMichael S. Tsirkin 				linear = tun16_to_cpu(tun, gso.hdr_len);
18303dd5c330SJason Wang 		}
18310690899bSMichael S. Tsirkin 
183290e33d45SPetar Penkov 		if (frags) {
183390e33d45SPetar Penkov 			mutex_lock(&tfile->napi_mutex);
183490e33d45SPetar Penkov 			skb = tun_napi_alloc_frags(tfile, copylen, from);
183590e33d45SPetar Penkov 			/* tun_napi_alloc_frags() enforces a layout for the skb.
183690e33d45SPetar Penkov 			 * If zerocopy is enabled, then this layout will be
183790e33d45SPetar Penkov 			 * overwritten by zerocopy_sg_from_iter().
183890e33d45SPetar Penkov 			 */
183990e33d45SPetar Penkov 			zerocopy = false;
184090e33d45SPetar Penkov 		} else {
184190e33d45SPetar Penkov 			skb = tun_alloc_skb(tfile, align, copylen, linear,
184290e33d45SPetar Penkov 					    noblock);
184390e33d45SPetar Penkov 		}
184490e33d45SPetar Penkov 
1845ab00af85SChuang Wang 		err = PTR_ERR_OR_ZERO(skb);
1846ab00af85SChuang Wang 		if (err)
1847ab00af85SChuang Wang 			goto drop;
18481da177e4SLinus Torvalds 
18490690899bSMichael S. Tsirkin 		if (zerocopy)
1850f5ff53b4SAl Viro 			err = zerocopy_sg_from_iter(skb, from);
1851af1cc7a2SJason Wang 		else
1852f5ff53b4SAl Viro 			err = skb_copy_datagram_from_iter(skb, 0, from, len);
18530690899bSMichael S. Tsirkin 
18540690899bSMichael S. Tsirkin 		if (err) {
18554477138fSEric Dumazet 			err = -EFAULT;
18564b4f052eSDongli Zhang 			drop_reason = SKB_DROP_REASON_SKB_UCOPY_FAULT;
1857ab00af85SChuang Wang 			goto drop;
18588f22757eSDave Jones 		}
185966ccbc9cSJason Wang 	}
18601da177e4SLinus Torvalds 
18613e9e40e7SJarno Rajahalme 	if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1862497a5757SHeiner Kallweit 		atomic_long_inc(&tun->rx_frame_errors);
1863ab00af85SChuang Wang 		err = -EINVAL;
1864ab00af85SChuang Wang 		goto free_skb;
1865df10db98SPaolo Abeni 	}
1866df10db98SPaolo Abeni 
18671da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
186840630b82SMichael S. Tsirkin 	case IFF_TUN:
186940630b82SMichael S. Tsirkin 		if (tun->flags & IFF_NO_PI) {
18702580c4c1SAlexander Potapenko 			u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
18712580c4c1SAlexander Potapenko 
18722580c4c1SAlexander Potapenko 			switch (ip_version) {
18732580c4c1SAlexander Potapenko 			case 4:
1874f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IP);
1875f09f7ee2SAng Way Chuang 				break;
18762580c4c1SAlexander Potapenko 			case 6:
1877f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IPV6);
1878f09f7ee2SAng Way Chuang 				break;
1879f09f7ee2SAng Way Chuang 			default:
1880ab00af85SChuang Wang 				err = -EINVAL;
1881ab00af85SChuang Wang 				goto drop;
1882f09f7ee2SAng Way Chuang 			}
1883f09f7ee2SAng Way Chuang 		}
1884f09f7ee2SAng Way Chuang 
1885459a98edSArnaldo Carvalho de Melo 		skb_reset_mac_header(skb);
18861da177e4SLinus Torvalds 		skb->protocol = pi.proto;
18874c13eb66SArnaldo Carvalho de Melo 		skb->dev = tun->dev;
18881da177e4SLinus Torvalds 		break;
188940630b82SMichael S. Tsirkin 	case IFF_TAP:
189096aa1b22SWillem de Bruijn 		if (frags && !pskb_may_pull(skb, ETH_HLEN)) {
189196aa1b22SWillem de Bruijn 			err = -ENOMEM;
18924b4f052eSDongli Zhang 			drop_reason = SKB_DROP_REASON_HDR_TRUNC;
189396aa1b22SWillem de Bruijn 			goto drop;
189496aa1b22SWillem de Bruijn 		}
18951da177e4SLinus Torvalds 		skb->protocol = eth_type_trans(skb, tun->dev);
18961da177e4SLinus Torvalds 		break;
18976403eab1SJoe Perches 	}
18981da177e4SLinus Torvalds 
18990690899bSMichael S. Tsirkin 	/* copy skb_ubuf_info for callback when skb has no error */
19000690899bSMichael S. Tsirkin 	if (zerocopy) {
19019ee5e5adSJonathan Lemon 		skb_zcopy_init(skb, msg_control);
1902af1cc7a2SJason Wang 	} else if (msg_control) {
1903af1cc7a2SJason Wang 		struct ubuf_info *uarg = msg_control;
190436177832SJonathan Lemon 		uarg->callback(NULL, uarg, false);
19050690899bSMichael S. Tsirkin 	}
19060690899bSMichael S. Tsirkin 
190772f65107SVlad Yasevich 	skb_reset_network_header(skb);
1908d2aa125dSMaxim Mikityanskiy 	skb_probe_transport_header(skb);
19093fe260e0SGilberto Bertin 	skb_record_rx_queue(skb, tfile->queue_index);
191038502af7SJason Wang 
19111cfe6e93SJason Wang 	if (skb_xdp) {
1912761876c8SJason Wang 		struct bpf_prog *xdp_prog;
1913761876c8SJason Wang 		int ret;
1914761876c8SJason Wang 
19156547e387SToshiaki Makita 		local_bh_disable();
1916761876c8SJason Wang 		rcu_read_lock();
1917761876c8SJason Wang 		xdp_prog = rcu_dereference(tun->xdp_prog);
1918761876c8SJason Wang 		if (xdp_prog) {
1919761876c8SJason Wang 			ret = do_xdp_generic(xdp_prog, skb);
1920761876c8SJason Wang 			if (ret != XDP_PASS) {
1921761876c8SJason Wang 				rcu_read_unlock();
19226547e387SToshiaki Makita 				local_bh_enable();
1923ab00af85SChuang Wang 				goto unlock_frags;
1924761876c8SJason Wang 			}
1925761876c8SJason Wang 		}
1926761876c8SJason Wang 		rcu_read_unlock();
19276547e387SToshiaki Makita 		local_bh_enable();
1928761876c8SJason Wang 	}
1929761876c8SJason Wang 
1930cf1a1e07SPaolo Abeni 	/* Compute the costly rx hash only if needed for flow updates.
1931cf1a1e07SPaolo Abeni 	 * We may get a very small possibility of OOO during switching, not
1932cf1a1e07SPaolo Abeni 	 * worth to optimize.
1933cf1a1e07SPaolo Abeni 	 */
1934cf1a1e07SPaolo Abeni 	if (!rcu_access_pointer(tun->steering_prog) && tun->numqueues > 1 &&
1935cf1a1e07SPaolo Abeni 	    !tfile->detached)
1936feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
193794317099SPetar Penkov 
19384477138fSEric Dumazet 	rcu_read_lock();
19394477138fSEric Dumazet 	if (unlikely(!(tun->dev->flags & IFF_UP))) {
19404477138fSEric Dumazet 		err = -EIO;
19419180bb4fSEric Dumazet 		rcu_read_unlock();
19424b4f052eSDongli Zhang 		drop_reason = SKB_DROP_REASON_DEV_READY;
19434477138fSEric Dumazet 		goto drop;
19444477138fSEric Dumazet 	}
19454477138fSEric Dumazet 
194690e33d45SPetar Penkov 	if (frags) {
194796aa1b22SWillem de Bruijn 		u32 headlen;
194896aa1b22SWillem de Bruijn 
194990e33d45SPetar Penkov 		/* Exercise flow dissector code path. */
195096aa1b22SWillem de Bruijn 		skb_push(skb, ETH_HLEN);
195196aa1b22SWillem de Bruijn 		headlen = eth_get_headlen(tun->dev, skb->data,
1952c43f1255SStanislav Fomichev 					  skb_headlen(skb));
195390e33d45SPetar Penkov 
1954010f245bSEric Dumazet 		if (unlikely(headlen > skb_headlen(skb))) {
195507d120aaSEric Dumazet 			WARN_ON_ONCE(1);
195607d120aaSEric Dumazet 			err = -ENOMEM;
1957625788b5SEric Dumazet 			dev_core_stats_rx_dropped_inc(tun->dev);
195807d120aaSEric Dumazet napi_busy:
195990e33d45SPetar Penkov 			napi_free_frags(&tfile->napi);
19604477138fSEric Dumazet 			rcu_read_unlock();
196190e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
196207d120aaSEric Dumazet 			return err;
196390e33d45SPetar Penkov 		}
196490e33d45SPetar Penkov 
196507d120aaSEric Dumazet 		if (likely(napi_schedule_prep(&tfile->napi))) {
196690e33d45SPetar Penkov 			local_bh_disable();
196790e33d45SPetar Penkov 			napi_gro_frags(&tfile->napi);
19681118b204SWang Yufen 			napi_complete(&tfile->napi);
196990e33d45SPetar Penkov 			local_bh_enable();
197007d120aaSEric Dumazet 		} else {
197107d120aaSEric Dumazet 			err = -EBUSY;
197207d120aaSEric Dumazet 			goto napi_busy;
197307d120aaSEric Dumazet 		}
197490e33d45SPetar Penkov 		mutex_unlock(&tfile->napi_mutex);
1975aec72f33SEric Dumazet 	} else if (tfile->napi_enabled) {
197694317099SPetar Penkov 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
197794317099SPetar Penkov 		int queue_len;
197894317099SPetar Penkov 
197994317099SPetar Penkov 		spin_lock_bh(&queue->lock);
198082b2bc27SKuniyuki Iwashima 
198182b2bc27SKuniyuki Iwashima 		if (unlikely(tfile->detached)) {
198282b2bc27SKuniyuki Iwashima 			spin_unlock_bh(&queue->lock);
198382b2bc27SKuniyuki Iwashima 			rcu_read_unlock();
198482b2bc27SKuniyuki Iwashima 			err = -EBUSY;
198582b2bc27SKuniyuki Iwashima 			goto free_skb;
198682b2bc27SKuniyuki Iwashima 		}
198782b2bc27SKuniyuki Iwashima 
198894317099SPetar Penkov 		__skb_queue_tail(queue, skb);
198994317099SPetar Penkov 		queue_len = skb_queue_len(queue);
199094317099SPetar Penkov 		spin_unlock(&queue->lock);
199194317099SPetar Penkov 
199294317099SPetar Penkov 		if (!more || queue_len > NAPI_POLL_WEIGHT)
199394317099SPetar Penkov 			napi_schedule(&tfile->napi);
199494317099SPetar Penkov 
199594317099SPetar Penkov 		local_bh_enable();
199694317099SPetar Penkov 	} else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
19975503fcecSJason Wang 		tun_rx_batched(tun, tfile, skb, more);
199894317099SPetar Penkov 	} else {
19993d391f65SSebastian Andrzej Siewior 		netif_rx(skb);
200094317099SPetar Penkov 	}
20014477138fSEric Dumazet 	rcu_read_unlock();
20021da177e4SLinus Torvalds 
2003497a5757SHeiner Kallweit 	preempt_disable();
2004497a5757SHeiner Kallweit 	dev_sw_netstats_rx_add(tun->dev, len);
2005497a5757SHeiner Kallweit 	preempt_enable();
20061da177e4SLinus Torvalds 
200796f84061SJason Wang 	if (rxhash)
20089e85722dSJason Wang 		tun_flow_update(tun, rxhash, tfile);
200996f84061SJason Wang 
20100690899bSMichael S. Tsirkin 	return total_len;
2011ab00af85SChuang Wang 
2012ab00af85SChuang Wang drop:
2013ab00af85SChuang Wang 	if (err != -EAGAIN)
2014ab00af85SChuang Wang 		dev_core_stats_rx_dropped_inc(tun->dev);
2015ab00af85SChuang Wang 
2016ab00af85SChuang Wang free_skb:
2017ab00af85SChuang Wang 	if (!IS_ERR_OR_NULL(skb))
2018ab00af85SChuang Wang 		kfree_skb_reason(skb, drop_reason);
2019ab00af85SChuang Wang 
2020ab00af85SChuang Wang unlock_frags:
2021ab00af85SChuang Wang 	if (frags) {
2022ab00af85SChuang Wang 		tfile->napi.skb = NULL;
2023ab00af85SChuang Wang 		mutex_unlock(&tfile->napi_mutex);
2024ab00af85SChuang Wang 	}
2025ab00af85SChuang Wang 
2026ab00af85SChuang Wang 	return err ?: total_len;
20271da177e4SLinus Torvalds }
20281da177e4SLinus Torvalds 
2029f5ff53b4SAl Viro static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
20301da177e4SLinus Torvalds {
203133dccbb0SHerbert Xu 	struct file *file = iocb->ki_filp;
203254f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
20339484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2034631ab46bSEric W. Biederman 	ssize_t result;
20355aac0390SJens Axboe 	int noblock = 0;
20361da177e4SLinus Torvalds 
20371da177e4SLinus Torvalds 	if (!tun)
20381da177e4SLinus Torvalds 		return -EBADFD;
20391da177e4SLinus Torvalds 
20405aac0390SJens Axboe 	if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
20415aac0390SJens Axboe 		noblock = 1;
20425aac0390SJens Axboe 
20435aac0390SJens Axboe 	result = tun_get_user(tun, tfile, NULL, from, noblock, false);
2044631ab46bSEric W. Biederman 
2045631ab46bSEric W. Biederman 	tun_put(tun);
2046631ab46bSEric W. Biederman 	return result;
20471da177e4SLinus Torvalds }
20481da177e4SLinus Torvalds 
2049fc72d1d5SJason Wang static ssize_t tun_put_user_xdp(struct tun_struct *tun,
2050fc72d1d5SJason Wang 				struct tun_file *tfile,
20511ffcbc85SJesper Dangaard Brouer 				struct xdp_frame *xdp_frame,
2052fc72d1d5SJason Wang 				struct iov_iter *iter)
2053fc72d1d5SJason Wang {
2054fc72d1d5SJason Wang 	int vnet_hdr_sz = 0;
20551ffcbc85SJesper Dangaard Brouer 	size_t size = xdp_frame->len;
2056fc72d1d5SJason Wang 	size_t ret;
2057fc72d1d5SJason Wang 
2058fc72d1d5SJason Wang 	if (tun->flags & IFF_VNET_HDR) {
2059fc72d1d5SJason Wang 		struct virtio_net_hdr gso = { 0 };
2060fc72d1d5SJason Wang 
2061fc72d1d5SJason Wang 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2062fc72d1d5SJason Wang 		if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
2063fc72d1d5SJason Wang 			return -EINVAL;
2064fc72d1d5SJason Wang 		if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
2065fc72d1d5SJason Wang 			     sizeof(gso)))
2066fc72d1d5SJason Wang 			return -EFAULT;
2067fc72d1d5SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2068fc72d1d5SJason Wang 	}
2069fc72d1d5SJason Wang 
20701ffcbc85SJesper Dangaard Brouer 	ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
2071fc72d1d5SJason Wang 
2072497a5757SHeiner Kallweit 	preempt_disable();
2073497a5757SHeiner Kallweit 	dev_sw_netstats_tx_add(tun->dev, 1, ret);
2074497a5757SHeiner Kallweit 	preempt_enable();
2075fc72d1d5SJason Wang 
2076fc72d1d5SJason Wang 	return ret;
2077fc72d1d5SJason Wang }
2078fc72d1d5SJason Wang 
20791da177e4SLinus Torvalds /* Put packet to the user space buffer */
20806f7c156cSstephen hemminger static ssize_t tun_put_user(struct tun_struct *tun,
208154f968d6SJason Wang 			    struct tun_file *tfile,
20821da177e4SLinus Torvalds 			    struct sk_buff *skb,
2083e0b46d0eSHerbert Xu 			    struct iov_iter *iter)
20841da177e4SLinus Torvalds {
20851da177e4SLinus Torvalds 	struct tun_pi pi = { 0, skb->protocol };
2086e0b46d0eSHerbert Xu 	ssize_t total;
20878c847d25SJason Wang 	int vlan_offset = 0;
2088a8f9bfdfSHerbert Xu 	int vlan_hlen = 0;
20892eb783c4SHerbert Xu 	int vnet_hdr_sz = 0;
2090a8f9bfdfSHerbert Xu 
2091df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb))
2092a8f9bfdfSHerbert Xu 		vlan_hlen = VLAN_HLEN;
20931da177e4SLinus Torvalds 
209440630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR)
2095e1edab87SWillem de Bruijn 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
20961da177e4SLinus Torvalds 
2097e0b46d0eSHerbert Xu 	total = skb->len + vlan_hlen + vnet_hdr_sz;
2098e0b46d0eSHerbert Xu 
209940630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
2100e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < sizeof(pi))
21011da177e4SLinus Torvalds 			return -EINVAL;
21021da177e4SLinus Torvalds 
2103e0b46d0eSHerbert Xu 		total += sizeof(pi);
2104e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < total) {
21051da177e4SLinus Torvalds 			/* Packet will be striped */
21061da177e4SLinus Torvalds 			pi.flags |= TUN_PKT_STRIP;
21071da177e4SLinus Torvalds 		}
21081da177e4SLinus Torvalds 
2109e0b46d0eSHerbert Xu 		if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
21101da177e4SLinus Torvalds 			return -EFAULT;
21111da177e4SLinus Torvalds 	}
21121da177e4SLinus Torvalds 
21132eb783c4SHerbert Xu 	if (vnet_hdr_sz) {
21149403cd7cSJarno Rajahalme 		struct virtio_net_hdr gso;
211534166093SMike Rapoport 
2116e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < vnet_hdr_sz)
2117f43798c2SRusty Russell 			return -EINVAL;
2118f43798c2SRusty Russell 
21193e9e40e7SJarno Rajahalme 		if (virtio_net_hdr_from_skb(skb, &gso,
2120fd3a8862SWillem de Bruijn 					    tun_is_little_endian(tun), true,
2121fd3a8862SWillem de Bruijn 					    vlan_hlen)) {
2122f43798c2SRusty Russell 			struct skb_shared_info *sinfo = skb_shinfo(skb);
21236b8a66eeSJoe Perches 			pr_err("unexpected GSO type: "
2124ef3db4a5SMichael S. Tsirkin 			       "0x%x, gso_size %d, hdr_len %d\n",
212556f0dcc5SMichael S. Tsirkin 			       sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
212656f0dcc5SMichael S. Tsirkin 			       tun16_to_cpu(tun, gso.hdr_len));
2127ef3db4a5SMichael S. Tsirkin 			print_hex_dump(KERN_ERR, "tun: ",
2128ef3db4a5SMichael S. Tsirkin 				       DUMP_PREFIX_NONE,
2129ef3db4a5SMichael S. Tsirkin 				       16, 1, skb->head,
213056f0dcc5SMichael S. Tsirkin 				       min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
2131ef3db4a5SMichael S. Tsirkin 			WARN_ON_ONCE(1);
2132ef3db4a5SMichael S. Tsirkin 			return -EINVAL;
2133ef3db4a5SMichael S. Tsirkin 		}
2134f43798c2SRusty Russell 
2135e0b46d0eSHerbert Xu 		if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
2136f43798c2SRusty Russell 			return -EFAULT;
21378c847d25SJason Wang 
21388c847d25SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2139f43798c2SRusty Russell 	}
2140f43798c2SRusty Russell 
2141a8f9bfdfSHerbert Xu 	if (vlan_hlen) {
2142e0b46d0eSHerbert Xu 		int ret;
2143aff3d70aSJason Wang 		struct veth veth;
21441da177e4SLinus Torvalds 
21456680ec68SJason Wang 		veth.h_vlan_proto = skb->vlan_proto;
2146df8a39deSJiri Pirko 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
21471da177e4SLinus Torvalds 
21486680ec68SJason Wang 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
21496680ec68SJason Wang 
2150e0b46d0eSHerbert Xu 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
2151e0b46d0eSHerbert Xu 		if (ret || !iov_iter_count(iter))
21526680ec68SJason Wang 			goto done;
21536680ec68SJason Wang 
2154e0b46d0eSHerbert Xu 		ret = copy_to_iter(&veth, sizeof(veth), iter);
2155e0b46d0eSHerbert Xu 		if (ret != sizeof(veth) || !iov_iter_count(iter))
21566680ec68SJason Wang 			goto done;
21576680ec68SJason Wang 	}
21586680ec68SJason Wang 
2159e0b46d0eSHerbert Xu 	skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
21606680ec68SJason Wang 
21616680ec68SJason Wang done:
2162608b9977SPaolo Abeni 	/* caller is in process context, */
2163497a5757SHeiner Kallweit 	preempt_disable();
2164497a5757SHeiner Kallweit 	dev_sw_netstats_tx_add(tun->dev, 1, skb->len + vlan_hlen);
2165497a5757SHeiner Kallweit 	preempt_enable();
21661da177e4SLinus Torvalds 
21671da177e4SLinus Torvalds 	return total;
21681da177e4SLinus Torvalds }
21691da177e4SLinus Torvalds 
2170fc72d1d5SJason Wang static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
21711576d986SJason Wang {
21721576d986SJason Wang 	DECLARE_WAITQUEUE(wait, current);
2173fc72d1d5SJason Wang 	void *ptr = NULL;
2174f48cc6b2SJason Wang 	int error = 0;
21751576d986SJason Wang 
2176fc72d1d5SJason Wang 	ptr = ptr_ring_consume(&tfile->tx_ring);
2177fc72d1d5SJason Wang 	if (ptr)
21781576d986SJason Wang 		goto out;
21791576d986SJason Wang 	if (noblock) {
2180f48cc6b2SJason Wang 		error = -EAGAIN;
21811576d986SJason Wang 		goto out;
21821576d986SJason Wang 	}
21831576d986SJason Wang 
2184333f7909SAl Viro 	add_wait_queue(&tfile->socket.wq.wait, &wait);
21851576d986SJason Wang 
21861576d986SJason Wang 	while (1) {
218771828b22STimur Celik 		set_current_state(TASK_INTERRUPTIBLE);
2188fc72d1d5SJason Wang 		ptr = ptr_ring_consume(&tfile->tx_ring);
2189fc72d1d5SJason Wang 		if (ptr)
21901576d986SJason Wang 			break;
21911576d986SJason Wang 		if (signal_pending(current)) {
2192f48cc6b2SJason Wang 			error = -ERESTARTSYS;
21931576d986SJason Wang 			break;
21941576d986SJason Wang 		}
21951576d986SJason Wang 		if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
2196f48cc6b2SJason Wang 			error = -EFAULT;
21971576d986SJason Wang 			break;
21981576d986SJason Wang 		}
21991576d986SJason Wang 
22001576d986SJason Wang 		schedule();
22011576d986SJason Wang 	}
22021576d986SJason Wang 
2203ecef67cbSTimur Celik 	__set_current_state(TASK_RUNNING);
2204333f7909SAl Viro 	remove_wait_queue(&tfile->socket.wq.wait, &wait);
22051576d986SJason Wang 
22061576d986SJason Wang out:
2207f48cc6b2SJason Wang 	*err = error;
2208fc72d1d5SJason Wang 	return ptr;
22091576d986SJason Wang }
22101576d986SJason Wang 
221154f968d6SJason Wang static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
22129b067034SAl Viro 			   struct iov_iter *to,
2213fc72d1d5SJason Wang 			   int noblock, void *ptr)
22141da177e4SLinus Torvalds {
22159b067034SAl Viro 	ssize_t ret;
22161576d986SJason Wang 	int err;
22171da177e4SLinus Torvalds 
2218c33ee15bSWei Xu 	if (!iov_iter_count(to)) {
2219fc72d1d5SJason Wang 		tun_ptr_free(ptr);
22209b067034SAl Viro 		return 0;
2221c33ee15bSWei Xu 	}
22221da177e4SLinus Torvalds 
2223fc72d1d5SJason Wang 	if (!ptr) {
22241576d986SJason Wang 		/* Read frames from ring */
2225fc72d1d5SJason Wang 		ptr = tun_ring_recv(tfile, noblock, &err);
2226fc72d1d5SJason Wang 		if (!ptr)
2227957f094fSAlex Gartrell 			return err;
2228ac77cfd4SJason Wang 	}
2229e0b46d0eSHerbert Xu 
22301ffcbc85SJesper Dangaard Brouer 	if (tun_is_xdp_frame(ptr)) {
22311ffcbc85SJesper Dangaard Brouer 		struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2232fc72d1d5SJason Wang 
22331ffcbc85SJesper Dangaard Brouer 		ret = tun_put_user_xdp(tun, tfile, xdpf, to);
223403993094SJesper Dangaard Brouer 		xdp_return_frame(xdpf);
2235fc72d1d5SJason Wang 	} else {
2236fc72d1d5SJason Wang 		struct sk_buff *skb = ptr;
2237fc72d1d5SJason Wang 
22389b067034SAl Viro 		ret = tun_put_user(tun, tfile, skb, to);
2239f51a5e82SJason Wang 		if (unlikely(ret < 0))
22401da177e4SLinus Torvalds 			kfree_skb(skb);
2241f51a5e82SJason Wang 		else
2242f51a5e82SJason Wang 			consume_skb(skb);
2243fc72d1d5SJason Wang 	}
22441da177e4SLinus Torvalds 
224505c2828cSMichael S. Tsirkin 	return ret;
224605c2828cSMichael S. Tsirkin }
224705c2828cSMichael S. Tsirkin 
22489b067034SAl Viro static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
224905c2828cSMichael S. Tsirkin {
225005c2828cSMichael S. Tsirkin 	struct file *file = iocb->ki_filp;
225105c2828cSMichael S. Tsirkin 	struct tun_file *tfile = file->private_data;
22529484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
22539b067034SAl Viro 	ssize_t len = iov_iter_count(to), ret;
22545aac0390SJens Axboe 	int noblock = 0;
225505c2828cSMichael S. Tsirkin 
225605c2828cSMichael S. Tsirkin 	if (!tun)
225705c2828cSMichael S. Tsirkin 		return -EBADFD;
22585aac0390SJens Axboe 
22595aac0390SJens Axboe 	if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
22605aac0390SJens Axboe 		noblock = 1;
22615aac0390SJens Axboe 
22625aac0390SJens Axboe 	ret = tun_do_read(tun, tfile, to, noblock, NULL);
226342404c09SDavid S. Miller 	ret = min_t(ssize_t, ret, len);
2264d0b7da8aSZhi Yong Wu 	if (ret > 0)
2265d0b7da8aSZhi Yong Wu 		iocb->ki_pos = ret;
2266631ab46bSEric W. Biederman 	tun_put(tun);
22671da177e4SLinus Torvalds 	return ret;
22681da177e4SLinus Torvalds }
22691da177e4SLinus Torvalds 
2270cd5681d7SJason Wang static void tun_prog_free(struct rcu_head *rcu)
227196f84061SJason Wang {
2272cd5681d7SJason Wang 	struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
227396f84061SJason Wang 
227496f84061SJason Wang 	bpf_prog_destroy(prog->prog);
227596f84061SJason Wang 	kfree(prog);
227696f84061SJason Wang }
227796f84061SJason Wang 
22789d6474e4SJason Wang static int __tun_set_ebpf(struct tun_struct *tun,
22799d6474e4SJason Wang 			  struct tun_prog __rcu **prog_p,
228096f84061SJason Wang 			  struct bpf_prog *prog)
228196f84061SJason Wang {
2282cd5681d7SJason Wang 	struct tun_prog *old, *new = NULL;
228396f84061SJason Wang 
228496f84061SJason Wang 	if (prog) {
228596f84061SJason Wang 		new = kmalloc(sizeof(*new), GFP_KERNEL);
228696f84061SJason Wang 		if (!new)
228796f84061SJason Wang 			return -ENOMEM;
228896f84061SJason Wang 		new->prog = prog;
228996f84061SJason Wang 	}
229096f84061SJason Wang 
2291124da8f6SJason Wang 	spin_lock_bh(&tun->lock);
2292cd5681d7SJason Wang 	old = rcu_dereference_protected(*prog_p,
2293124da8f6SJason Wang 					lockdep_is_held(&tun->lock));
2294cd5681d7SJason Wang 	rcu_assign_pointer(*prog_p, new);
2295124da8f6SJason Wang 	spin_unlock_bh(&tun->lock);
229696f84061SJason Wang 
229796f84061SJason Wang 	if (old)
2298cd5681d7SJason Wang 		call_rcu(&old->rcu, tun_prog_free);
229996f84061SJason Wang 
230096f84061SJason Wang 	return 0;
230196f84061SJason Wang }
230296f84061SJason Wang 
230396442e42SJason Wang static void tun_free_netdev(struct net_device *dev)
230496442e42SJason Wang {
230596442e42SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
230696442e42SJason Wang 
23074008e97fSJason Wang 	BUG_ON(!(list_empty(&tun->disabled)));
230811fc7d5aSEric Dumazet 
2309497a5757SHeiner Kallweit 	free_percpu(dev->tstats);
231096442e42SJason Wang 	tun_flow_uninit(tun);
23115dbbaf2dSPaul Moore 	security_tun_dev_free_security(tun->security);
2312cd5681d7SJason Wang 	__tun_set_ebpf(tun, &tun->steering_prog, NULL);
2313aff3d70aSJason Wang 	__tun_set_ebpf(tun, &tun->filter_prog, NULL);
231496442e42SJason Wang }
231596442e42SJason Wang 
23161da177e4SLinus Torvalds static void tun_setup(struct net_device *dev)
23171da177e4SLinus Torvalds {
23181da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
23191da177e4SLinus Torvalds 
23200625c883SEric W. Biederman 	tun->owner = INVALID_UID;
23210625c883SEric W. Biederman 	tun->group = INVALID_GID;
23224e24f2ddSChas Williams 	tun_default_link_ksettings(dev, &tun->link_ksettings);
23231da177e4SLinus Torvalds 
23241da177e4SLinus Torvalds 	dev->ethtool_ops = &tun_ethtool_ops;
2325cf124db5SDavid S. Miller 	dev->needs_free_netdev = true;
2326cf124db5SDavid S. Miller 	dev->priv_destructor = tun_free_netdev;
2327016adb72SJason Wang 	/* We prefer our own queue length */
2328016adb72SJason Wang 	dev->tx_queue_len = TUN_READQ_SIZE;
23291da177e4SLinus Torvalds }
23301da177e4SLinus Torvalds 
2331f019a7a5SEric W. Biederman /* Trivial set of netlink ops to allow deleting tun or tap
2332f019a7a5SEric W. Biederman  * device with netlink.
2333f019a7a5SEric W. Biederman  */
2334a8b8a889SMatthias Schiffer static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2335a8b8a889SMatthias Schiffer 			struct netlink_ext_ack *extack)
2336f019a7a5SEric W. Biederman {
233735b827b6SNicolas Dichtel 	NL_SET_ERR_MSG(extack,
233835b827b6SNicolas Dichtel 		       "tun/tap creation via rtnetlink is not supported.");
233935b827b6SNicolas Dichtel 	return -EOPNOTSUPP;
2340f019a7a5SEric W. Biederman }
2341f019a7a5SEric W. Biederman 
23421ec010e7SSabrina Dubroca static size_t tun_get_size(const struct net_device *dev)
23431ec010e7SSabrina Dubroca {
23441ec010e7SSabrina Dubroca 	BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
23451ec010e7SSabrina Dubroca 	BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
23461ec010e7SSabrina Dubroca 
23471ec010e7SSabrina Dubroca 	return nla_total_size(sizeof(uid_t)) + /* OWNER */
23481ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(gid_t)) + /* GROUP */
23491ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* TYPE */
23501ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* PI */
23511ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* VNET_HDR */
23521ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* PERSIST */
23531ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
23541ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
23551ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
23561ec010e7SSabrina Dubroca 	       0;
23571ec010e7SSabrina Dubroca }
23581ec010e7SSabrina Dubroca 
23591ec010e7SSabrina Dubroca static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
23601ec010e7SSabrina Dubroca {
23611ec010e7SSabrina Dubroca 	struct tun_struct *tun = netdev_priv(dev);
23621ec010e7SSabrina Dubroca 
23631ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
23641ec010e7SSabrina Dubroca 		goto nla_put_failure;
23651ec010e7SSabrina Dubroca 	if (uid_valid(tun->owner) &&
23661ec010e7SSabrina Dubroca 	    nla_put_u32(skb, IFLA_TUN_OWNER,
23671ec010e7SSabrina Dubroca 			from_kuid_munged(current_user_ns(), tun->owner)))
23681ec010e7SSabrina Dubroca 		goto nla_put_failure;
23691ec010e7SSabrina Dubroca 	if (gid_valid(tun->group) &&
23701ec010e7SSabrina Dubroca 	    nla_put_u32(skb, IFLA_TUN_GROUP,
23711ec010e7SSabrina Dubroca 			from_kgid_munged(current_user_ns(), tun->group)))
23721ec010e7SSabrina Dubroca 		goto nla_put_failure;
23731ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
23741ec010e7SSabrina Dubroca 		goto nla_put_failure;
23751ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
23761ec010e7SSabrina Dubroca 		goto nla_put_failure;
23771ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
23781ec010e7SSabrina Dubroca 		goto nla_put_failure;
23791ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
23801ec010e7SSabrina Dubroca 		       !!(tun->flags & IFF_MULTI_QUEUE)))
23811ec010e7SSabrina Dubroca 		goto nla_put_failure;
23821ec010e7SSabrina Dubroca 	if (tun->flags & IFF_MULTI_QUEUE) {
23831ec010e7SSabrina Dubroca 		if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
23841ec010e7SSabrina Dubroca 			goto nla_put_failure;
23851ec010e7SSabrina Dubroca 		if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
23861ec010e7SSabrina Dubroca 				tun->numdisabled))
23871ec010e7SSabrina Dubroca 			goto nla_put_failure;
23881ec010e7SSabrina Dubroca 	}
23891ec010e7SSabrina Dubroca 
23901ec010e7SSabrina Dubroca 	return 0;
23911ec010e7SSabrina Dubroca 
23921ec010e7SSabrina Dubroca nla_put_failure:
23931ec010e7SSabrina Dubroca 	return -EMSGSIZE;
23941ec010e7SSabrina Dubroca }
23951ec010e7SSabrina Dubroca 
2396f019a7a5SEric W. Biederman static struct rtnl_link_ops tun_link_ops __read_mostly = {
2397f019a7a5SEric W. Biederman 	.kind		= DRV_NAME,
2398f019a7a5SEric W. Biederman 	.priv_size	= sizeof(struct tun_struct),
2399f019a7a5SEric W. Biederman 	.setup		= tun_setup,
2400f019a7a5SEric W. Biederman 	.validate	= tun_validate,
24011ec010e7SSabrina Dubroca 	.get_size       = tun_get_size,
24021ec010e7SSabrina Dubroca 	.fill_info      = tun_fill_info,
2403f019a7a5SEric W. Biederman };
2404f019a7a5SEric W. Biederman 
240533dccbb0SHerbert Xu static void tun_sock_write_space(struct sock *sk)
240633dccbb0SHerbert Xu {
240754f968d6SJason Wang 	struct tun_file *tfile;
240843815482SEric Dumazet 	wait_queue_head_t *wqueue;
240933dccbb0SHerbert Xu 
241033dccbb0SHerbert Xu 	if (!sock_writeable(sk))
241133dccbb0SHerbert Xu 		return;
241233dccbb0SHerbert Xu 
24139cd3e072SEric Dumazet 	if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
241433dccbb0SHerbert Xu 		return;
241533dccbb0SHerbert Xu 
241643815482SEric Dumazet 	wqueue = sk_sleep(sk);
241743815482SEric Dumazet 	if (wqueue && waitqueue_active(wqueue))
2418a9a08845SLinus Torvalds 		wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
2419a9a08845SLinus Torvalds 						EPOLLWRNORM | EPOLLWRBAND);
2420c722c625SHerbert Xu 
242154f968d6SJason Wang 	tfile = container_of(sk, struct tun_file, sk);
242254f968d6SJason Wang 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
242333dccbb0SHerbert Xu }
242433dccbb0SHerbert Xu 
2425f9e06c45SJason Wang static void tun_put_page(struct tun_page *tpage)
2426f9e06c45SJason Wang {
2427f9e06c45SJason Wang 	if (tpage->page)
2428f9e06c45SJason Wang 		__page_frag_cache_drain(tpage->page, tpage->count);
2429f9e06c45SJason Wang }
2430f9e06c45SJason Wang 
2431043d222fSJason Wang static int tun_xdp_one(struct tun_struct *tun,
2432043d222fSJason Wang 		       struct tun_file *tfile,
2433f9e06c45SJason Wang 		       struct xdp_buff *xdp, int *flush,
2434f9e06c45SJason Wang 		       struct tun_page *tpage)
2435043d222fSJason Wang {
24364e4b08e5SPrashant Bhole 	unsigned int datasize = xdp->data_end - xdp->data;
2437043d222fSJason Wang 	struct tun_xdp_hdr *hdr = xdp->data_hard_start;
2438043d222fSJason Wang 	struct virtio_net_hdr *gso = &hdr->gso;
2439043d222fSJason Wang 	struct bpf_prog *xdp_prog;
2440043d222fSJason Wang 	struct sk_buff *skb = NULL;
2441fb3f9037SHarold Huang 	struct sk_buff_head *queue;
2442043d222fSJason Wang 	u32 rxhash = 0, act;
2443043d222fSJason Wang 	int buflen = hdr->buflen;
2444fb3f9037SHarold Huang 	int ret = 0;
2445043d222fSJason Wang 	bool skb_xdp = false;
2446f9e06c45SJason Wang 	struct page *page;
2447043d222fSJason Wang 
2448043d222fSJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
2449043d222fSJason Wang 	if (xdp_prog) {
2450043d222fSJason Wang 		if (gso->gso_type) {
2451043d222fSJason Wang 			skb_xdp = true;
2452043d222fSJason Wang 			goto build;
2453043d222fSJason Wang 		}
245443b5169dSLorenzo Bianconi 
245543b5169dSLorenzo Bianconi 		xdp_init_buff(xdp, buflen, &tfile->xdp_rxq);
2456043d222fSJason Wang 		xdp_set_data_meta_invalid(xdp);
2457043d222fSJason Wang 
2458043d222fSJason Wang 		act = bpf_prog_run_xdp(xdp_prog, xdp);
2459fb3f9037SHarold Huang 		ret = tun_xdp_act(tun, xdp_prog, xdp, act);
2460fb3f9037SHarold Huang 		if (ret < 0) {
2461043d222fSJason Wang 			put_page(virt_to_head_page(xdp->data));
2462fb3f9037SHarold Huang 			return ret;
2463043d222fSJason Wang 		}
2464043d222fSJason Wang 
2465fb3f9037SHarold Huang 		switch (ret) {
2466043d222fSJason Wang 		case XDP_REDIRECT:
2467043d222fSJason Wang 			*flush = true;
2468df561f66SGustavo A. R. Silva 			fallthrough;
2469043d222fSJason Wang 		case XDP_TX:
2470043d222fSJason Wang 			return 0;
2471043d222fSJason Wang 		case XDP_PASS:
2472043d222fSJason Wang 			break;
2473043d222fSJason Wang 		default:
2474f9e06c45SJason Wang 			page = virt_to_head_page(xdp->data);
2475f9e06c45SJason Wang 			if (tpage->page == page) {
2476f9e06c45SJason Wang 				++tpage->count;
2477f9e06c45SJason Wang 			} else {
2478f9e06c45SJason Wang 				tun_put_page(tpage);
2479f9e06c45SJason Wang 				tpage->page = page;
2480f9e06c45SJason Wang 				tpage->count = 1;
2481f9e06c45SJason Wang 			}
2482043d222fSJason Wang 			return 0;
2483043d222fSJason Wang 		}
2484043d222fSJason Wang 	}
2485043d222fSJason Wang 
2486043d222fSJason Wang build:
2487043d222fSJason Wang 	skb = build_skb(xdp->data_hard_start, buflen);
2488043d222fSJason Wang 	if (!skb) {
2489fb3f9037SHarold Huang 		ret = -ENOMEM;
2490043d222fSJason Wang 		goto out;
2491043d222fSJason Wang 	}
2492043d222fSJason Wang 
2493043d222fSJason Wang 	skb_reserve(skb, xdp->data - xdp->data_hard_start);
2494043d222fSJason Wang 	skb_put(skb, xdp->data_end - xdp->data);
2495043d222fSJason Wang 
2496043d222fSJason Wang 	if (virtio_net_hdr_to_skb(skb, gso, tun_is_little_endian(tun))) {
2497497a5757SHeiner Kallweit 		atomic_long_inc(&tun->rx_frame_errors);
2498043d222fSJason Wang 		kfree_skb(skb);
2499fb3f9037SHarold Huang 		ret = -EINVAL;
2500043d222fSJason Wang 		goto out;
2501043d222fSJason Wang 	}
2502043d222fSJason Wang 
2503043d222fSJason Wang 	skb->protocol = eth_type_trans(skb, tun->dev);
2504043d222fSJason Wang 	skb_reset_network_header(skb);
2505d2aa125dSMaxim Mikityanskiy 	skb_probe_transport_header(skb);
25063fe260e0SGilberto Bertin 	skb_record_rx_queue(skb, tfile->queue_index);
2507043d222fSJason Wang 
2508043d222fSJason Wang 	if (skb_xdp) {
2509fb3f9037SHarold Huang 		ret = do_xdp_generic(xdp_prog, skb);
2510fb3f9037SHarold Huang 		if (ret != XDP_PASS) {
2511fb3f9037SHarold Huang 			ret = 0;
2512043d222fSJason Wang 			goto out;
2513043d222fSJason Wang 		}
2514fb3f9037SHarold Huang 	}
2515043d222fSJason Wang 
2516f29eb2a9SPaolo Abeni 	if (!rcu_dereference(tun->steering_prog) && tun->numqueues > 1 &&
2517f29eb2a9SPaolo Abeni 	    !tfile->detached)
2518043d222fSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
2519043d222fSJason Wang 
2520fb3f9037SHarold Huang 	if (tfile->napi_enabled) {
2521fb3f9037SHarold Huang 		queue = &tfile->sk.sk_write_queue;
2522fb3f9037SHarold Huang 		spin_lock(&queue->lock);
252382b2bc27SKuniyuki Iwashima 
252482b2bc27SKuniyuki Iwashima 		if (unlikely(tfile->detached)) {
252582b2bc27SKuniyuki Iwashima 			spin_unlock(&queue->lock);
252682b2bc27SKuniyuki Iwashima 			kfree_skb(skb);
252782b2bc27SKuniyuki Iwashima 			return -EBUSY;
252882b2bc27SKuniyuki Iwashima 		}
252982b2bc27SKuniyuki Iwashima 
2530fb3f9037SHarold Huang 		__skb_queue_tail(queue, skb);
2531fb3f9037SHarold Huang 		spin_unlock(&queue->lock);
2532fb3f9037SHarold Huang 		ret = 1;
2533fb3f9037SHarold Huang 	} else {
2534043d222fSJason Wang 		netif_receive_skb(skb);
2535fb3f9037SHarold Huang 		ret = 0;
2536fb3f9037SHarold Huang 	}
2537043d222fSJason Wang 
2538497a5757SHeiner Kallweit 	/* No need to disable preemption here since this function is
25396342ca64SPrashant Bhole 	 * always called with bh disabled
25406342ca64SPrashant Bhole 	 */
2541497a5757SHeiner Kallweit 	dev_sw_netstats_rx_add(tun->dev, datasize);
2542043d222fSJason Wang 
2543043d222fSJason Wang 	if (rxhash)
2544043d222fSJason Wang 		tun_flow_update(tun, rxhash, tfile);
2545043d222fSJason Wang 
2546043d222fSJason Wang out:
2547fb3f9037SHarold Huang 	return ret;
2548043d222fSJason Wang }
2549043d222fSJason Wang 
25501b784140SYing Xue static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
255105c2828cSMichael S. Tsirkin {
2552043d222fSJason Wang 	int ret, i;
255354f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
25549484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2555fe8dd45bSJason Wang 	struct tun_msg_ctl *ctl = m->msg_control;
2556043d222fSJason Wang 	struct xdp_buff *xdp;
255754f968d6SJason Wang 
255854f968d6SJason Wang 	if (!tun)
255954f968d6SJason Wang 		return -EBADFD;
2560f5ff53b4SAl Viro 
256174a335a0SHarold Huang 	if (m->msg_controllen == sizeof(struct tun_msg_ctl) &&
256274a335a0SHarold Huang 	    ctl && ctl->type == TUN_MSG_PTR) {
25636f0271d9SDavid S. Miller 		struct tun_page tpage;
2564043d222fSJason Wang 		int n = ctl->num;
2565fb3f9037SHarold Huang 		int flush = 0, queued = 0;
2566043d222fSJason Wang 
25676f0271d9SDavid S. Miller 		memset(&tpage, 0, sizeof(tpage));
25686f0271d9SDavid S. Miller 
2569043d222fSJason Wang 		local_bh_disable();
2570043d222fSJason Wang 		rcu_read_lock();
2571043d222fSJason Wang 
2572043d222fSJason Wang 		for (i = 0; i < n; i++) {
2573043d222fSJason Wang 			xdp = &((struct xdp_buff *)ctl->ptr)[i];
2574fb3f9037SHarold Huang 			ret = tun_xdp_one(tun, tfile, xdp, &flush, &tpage);
2575fb3f9037SHarold Huang 			if (ret > 0)
2576fb3f9037SHarold Huang 				queued += ret;
2577043d222fSJason Wang 		}
2578043d222fSJason Wang 
2579043d222fSJason Wang 		if (flush)
25801d233886SToke Høiland-Jørgensen 			xdp_do_flush();
2581043d222fSJason Wang 
2582fb3f9037SHarold Huang 		if (tfile->napi_enabled && queued > 0)
2583fb3f9037SHarold Huang 			napi_schedule(&tfile->napi);
2584fb3f9037SHarold Huang 
2585043d222fSJason Wang 		rcu_read_unlock();
2586043d222fSJason Wang 		local_bh_enable();
2587043d222fSJason Wang 
2588f9e06c45SJason Wang 		tun_put_page(&tpage);
2589f9e06c45SJason Wang 
2590043d222fSJason Wang 		ret = total_len;
2591043d222fSJason Wang 		goto out;
2592043d222fSJason Wang 	}
2593fe8dd45bSJason Wang 
2594fe8dd45bSJason Wang 	ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
25955503fcecSJason Wang 			   m->msg_flags & MSG_DONTWAIT,
25965503fcecSJason Wang 			   m->msg_flags & MSG_MORE);
2597043d222fSJason Wang out:
259854f968d6SJason Wang 	tun_put(tun);
259954f968d6SJason Wang 	return ret;
260005c2828cSMichael S. Tsirkin }
260105c2828cSMichael S. Tsirkin 
26021b784140SYing Xue static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
260305c2828cSMichael S. Tsirkin 		       int flags)
260405c2828cSMichael S. Tsirkin {
260554f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
26069484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2607fc72d1d5SJason Wang 	void *ptr = m->msg_control;
260805c2828cSMichael S. Tsirkin 	int ret;
260954f968d6SJason Wang 
2610c33ee15bSWei Xu 	if (!tun) {
2611c33ee15bSWei Xu 		ret = -EBADFD;
2612fc72d1d5SJason Wang 		goto out_free;
2613c33ee15bSWei Xu 	}
261454f968d6SJason Wang 
2615eda29772SRichard Cochran 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
26163811ae76SGao feng 		ret = -EINVAL;
2617c33ee15bSWei Xu 		goto out_put_tun;
26183811ae76SGao feng 	}
2619eda29772SRichard Cochran 	if (flags & MSG_ERRQUEUE) {
2620eda29772SRichard Cochran 		ret = sock_recv_errqueue(sock->sk, m, total_len,
2621eda29772SRichard Cochran 					 SOL_PACKET, TUN_TX_TIMESTAMP);
2622eda29772SRichard Cochran 		goto out;
2623eda29772SRichard Cochran 	}
2624fc72d1d5SJason Wang 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
262587897931SAlex Gartrell 	if (ret > (ssize_t)total_len) {
262642404c09SDavid S. Miller 		m->msg_flags |= MSG_TRUNC;
262742404c09SDavid S. Miller 		ret = flags & MSG_TRUNC ? ret : total_len;
262842404c09SDavid S. Miller 	}
26293811ae76SGao feng out:
263054f968d6SJason Wang 	tun_put(tun);
263105c2828cSMichael S. Tsirkin 	return ret;
2632c33ee15bSWei Xu 
2633c33ee15bSWei Xu out_put_tun:
2634c33ee15bSWei Xu 	tun_put(tun);
2635fc72d1d5SJason Wang out_free:
2636fc72d1d5SJason Wang 	tun_ptr_free(ptr);
2637c33ee15bSWei Xu 	return ret;
263805c2828cSMichael S. Tsirkin }
263905c2828cSMichael S. Tsirkin 
2640fc72d1d5SJason Wang static int tun_ptr_peek_len(void *ptr)
2641fc72d1d5SJason Wang {
2642fc72d1d5SJason Wang 	if (likely(ptr)) {
26431ffcbc85SJesper Dangaard Brouer 		if (tun_is_xdp_frame(ptr)) {
26441ffcbc85SJesper Dangaard Brouer 			struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2645fc72d1d5SJason Wang 
26461ffcbc85SJesper Dangaard Brouer 			return xdpf->len;
2647fc72d1d5SJason Wang 		}
2648fc72d1d5SJason Wang 		return __skb_array_len_with_tag(ptr);
2649fc72d1d5SJason Wang 	} else {
2650fc72d1d5SJason Wang 		return 0;
2651fc72d1d5SJason Wang 	}
2652fc72d1d5SJason Wang }
2653fc72d1d5SJason Wang 
26541576d986SJason Wang static int tun_peek_len(struct socket *sock)
26551576d986SJason Wang {
26561576d986SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
26571576d986SJason Wang 	struct tun_struct *tun;
26581576d986SJason Wang 	int ret = 0;
26591576d986SJason Wang 
26609484dc74Syuan linyu 	tun = tun_get(tfile);
26611576d986SJason Wang 	if (!tun)
26621576d986SJason Wang 		return 0;
26631576d986SJason Wang 
2664fc72d1d5SJason Wang 	ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
26651576d986SJason Wang 	tun_put(tun);
26661576d986SJason Wang 
26671576d986SJason Wang 	return ret;
26681576d986SJason Wang }
26691576d986SJason Wang 
267005c2828cSMichael S. Tsirkin /* Ops structure to mimic raw sockets with tun */
267105c2828cSMichael S. Tsirkin static const struct proto_ops tun_socket_ops = {
26721576d986SJason Wang 	.peek_len = tun_peek_len,
267305c2828cSMichael S. Tsirkin 	.sendmsg = tun_sendmsg,
267405c2828cSMichael S. Tsirkin 	.recvmsg = tun_recvmsg,
267505c2828cSMichael S. Tsirkin };
267605c2828cSMichael S. Tsirkin 
267733dccbb0SHerbert Xu static struct proto tun_proto = {
267833dccbb0SHerbert Xu 	.name		= "tun",
267933dccbb0SHerbert Xu 	.owner		= THIS_MODULE,
268054f968d6SJason Wang 	.obj_size	= sizeof(struct tun_file),
268133dccbb0SHerbert Xu };
2682f019a7a5SEric W. Biederman 
2683980c9e8cSDavid Woodhouse static int tun_flags(struct tun_struct *tun)
2684980c9e8cSDavid Woodhouse {
2685031f5e03SMichael S. Tsirkin 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2686980c9e8cSDavid Woodhouse }
2687980c9e8cSDavid Woodhouse 
2688bc6d076dSYueHaibing static ssize_t tun_flags_show(struct device *dev, struct device_attribute *attr,
2689980c9e8cSDavid Woodhouse 			      char *buf)
2690980c9e8cSDavid Woodhouse {
2691980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2692aff30699SWang Yufen 	return sysfs_emit(buf, "0x%x\n", tun_flags(tun));
2693980c9e8cSDavid Woodhouse }
2694980c9e8cSDavid Woodhouse 
2695bc6d076dSYueHaibing static ssize_t owner_show(struct device *dev, struct device_attribute *attr,
2696980c9e8cSDavid Woodhouse 			  char *buf)
2697980c9e8cSDavid Woodhouse {
2698980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
26990625c883SEric W. Biederman 	return uid_valid(tun->owner)?
2700aff30699SWang Yufen 		sysfs_emit(buf, "%u\n",
27010625c883SEric W. Biederman 			   from_kuid_munged(current_user_ns(), tun->owner)) :
2702aff30699SWang Yufen 		sysfs_emit(buf, "-1\n");
2703980c9e8cSDavid Woodhouse }
2704980c9e8cSDavid Woodhouse 
2705bc6d076dSYueHaibing static ssize_t group_show(struct device *dev, struct device_attribute *attr,
2706980c9e8cSDavid Woodhouse 			  char *buf)
2707980c9e8cSDavid Woodhouse {
2708980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
27090625c883SEric W. Biederman 	return gid_valid(tun->group) ?
2710aff30699SWang Yufen 		sysfs_emit(buf, "%u\n",
27110625c883SEric W. Biederman 			   from_kgid_munged(current_user_ns(), tun->group)) :
2712aff30699SWang Yufen 		sysfs_emit(buf, "-1\n");
2713980c9e8cSDavid Woodhouse }
2714980c9e8cSDavid Woodhouse 
2715bc6d076dSYueHaibing static DEVICE_ATTR_RO(tun_flags);
2716bc6d076dSYueHaibing static DEVICE_ATTR_RO(owner);
2717bc6d076dSYueHaibing static DEVICE_ATTR_RO(group);
2718980c9e8cSDavid Woodhouse 
2719c4d33e24STakashi Iwai static struct attribute *tun_dev_attrs[] = {
2720c4d33e24STakashi Iwai 	&dev_attr_tun_flags.attr,
2721c4d33e24STakashi Iwai 	&dev_attr_owner.attr,
2722c4d33e24STakashi Iwai 	&dev_attr_group.attr,
2723c4d33e24STakashi Iwai 	NULL
2724c4d33e24STakashi Iwai };
2725c4d33e24STakashi Iwai 
2726c4d33e24STakashi Iwai static const struct attribute_group tun_attr_group = {
2727c4d33e24STakashi Iwai 	.attrs = tun_dev_attrs
2728c4d33e24STakashi Iwai };
2729c4d33e24STakashi Iwai 
2730d647a591SPavel Emelyanov static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
27311da177e4SLinus Torvalds {
27321da177e4SLinus Torvalds 	struct tun_struct *tun;
273354f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
27341da177e4SLinus Torvalds 	struct net_device *dev;
27351da177e4SLinus Torvalds 	int err;
27361da177e4SLinus Torvalds 
27377c0c3b1aSJason Wang 	if (tfile->detached)
27387c0c3b1aSJason Wang 		return -EINVAL;
27397c0c3b1aSJason Wang 
274090e33d45SPetar Penkov 	if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
274190e33d45SPetar Penkov 		if (!capable(CAP_NET_ADMIN))
274290e33d45SPetar Penkov 			return -EPERM;
274390e33d45SPetar Penkov 
274490e33d45SPetar Penkov 		if (!(ifr->ifr_flags & IFF_NAPI) ||
274590e33d45SPetar Penkov 		    (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
274690e33d45SPetar Penkov 			return -EINVAL;
274790e33d45SPetar Penkov 	}
274890e33d45SPetar Penkov 
274974a3e5a7SEric W. Biederman 	dev = __dev_get_by_name(net, ifr->ifr_name);
275074a3e5a7SEric W. Biederman 	if (dev) {
2751f85ba780SDavid Woodhouse 		if (ifr->ifr_flags & IFF_TUN_EXCL)
2752f85ba780SDavid Woodhouse 			return -EBUSY;
275374a3e5a7SEric W. Biederman 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
275474a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
275574a3e5a7SEric W. Biederman 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
275674a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
275774a3e5a7SEric W. Biederman 		else
275874a3e5a7SEric W. Biederman 			return -EINVAL;
275974a3e5a7SEric W. Biederman 
27608e6d91aeSJason Wang 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
276140630b82SMichael S. Tsirkin 		    !!(tun->flags & IFF_MULTI_QUEUE))
27628e6d91aeSJason Wang 			return -EINVAL;
27638e6d91aeSJason Wang 
2764cde8b15fSJason Wang 		if (tun_not_capable(tun))
27652b980dbdSPaul Moore 			return -EPERM;
27665dbbaf2dSPaul Moore 		err = security_tun_dev_open(tun->security);
27672b980dbdSPaul Moore 		if (err < 0)
27682b980dbdSPaul Moore 			return err;
27692b980dbdSPaul Moore 
277094317099SPetar Penkov 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
2771af3fb24eSEric Dumazet 				 ifr->ifr_flags & IFF_NAPI,
277277f22f92SYang Yingliang 				 ifr->ifr_flags & IFF_NAPI_FRAGS, true);
2773a7385ba2SEric W. Biederman 		if (err < 0)
2774a7385ba2SEric W. Biederman 			return err;
27754008e97fSJason Wang 
277640630b82SMichael S. Tsirkin 		if (tun->flags & IFF_MULTI_QUEUE &&
2777e8dbad66SJason Wang 		    (tun->numqueues + tun->numdisabled > 1)) {
2778e8dbad66SJason Wang 			/* One or more queue has already been attached, no need
2779e8dbad66SJason Wang 			 * to initialize the device again.
2780e8dbad66SJason Wang 			 */
278183c1f36fSSabrina Dubroca 			netdev_state_change(dev);
2782e8dbad66SJason Wang 			return 0;
2783e8dbad66SJason Wang 		}
27849fffc5c6SSabrina Dubroca 
27859fffc5c6SSabrina Dubroca 		tun->flags = (tun->flags & ~TUN_FEATURES) |
27869fffc5c6SSabrina Dubroca 			      (ifr->ifr_flags & TUN_FEATURES);
278783c1f36fSSabrina Dubroca 
278883c1f36fSSabrina Dubroca 		netdev_state_change(dev);
278983c1f36fSSabrina Dubroca 	} else {
27901da177e4SLinus Torvalds 		char *name;
27911da177e4SLinus Torvalds 		unsigned long flags = 0;
2792edfb6a14SJason Wang 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2793edfb6a14SJason Wang 			     MAX_TAP_QUEUES : 1;
27941da177e4SLinus Torvalds 
2795c260b772SEric W. Biederman 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2796ca6bb5d7SDavid Woodhouse 			return -EPERM;
27972b980dbdSPaul Moore 		err = security_tun_dev_create();
27982b980dbdSPaul Moore 		if (err < 0)
27992b980dbdSPaul Moore 			return err;
2800ca6bb5d7SDavid Woodhouse 
28011da177e4SLinus Torvalds 		/* Set dev type */
28021da177e4SLinus Torvalds 		if (ifr->ifr_flags & IFF_TUN) {
28031da177e4SLinus Torvalds 			/* TUN device */
280440630b82SMichael S. Tsirkin 			flags |= IFF_TUN;
28051da177e4SLinus Torvalds 			name = "tun%d";
28061da177e4SLinus Torvalds 		} else if (ifr->ifr_flags & IFF_TAP) {
28071da177e4SLinus Torvalds 			/* TAP device */
280840630b82SMichael S. Tsirkin 			flags |= IFF_TAP;
28091da177e4SLinus Torvalds 			name = "tap%d";
28101da177e4SLinus Torvalds 		} else
281136989b90SKusanagi Kouichi 			return -EINVAL;
28121da177e4SLinus Torvalds 
28131da177e4SLinus Torvalds 		if (*ifr->ifr_name)
28141da177e4SLinus Torvalds 			name = ifr->ifr_name;
28151da177e4SLinus Torvalds 
2816c8d68e6bSJason Wang 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2817c835a677STom Gundersen 				       NET_NAME_UNKNOWN, tun_setup, queues,
2818c835a677STom Gundersen 				       queues);
2819edfb6a14SJason Wang 
28201da177e4SLinus Torvalds 		if (!dev)
28211da177e4SLinus Torvalds 			return -ENOMEM;
28221da177e4SLinus Torvalds 
2823fc54c658SPavel Emelyanov 		dev_net_set(dev, net);
2824f019a7a5SEric W. Biederman 		dev->rtnl_link_ops = &tun_link_ops;
2825fb7589a1SPavel Emelyanov 		dev->ifindex = tfile->ifindex;
2826c4d33e24STakashi Iwai 		dev->sysfs_groups[0] = &tun_attr_group;
2827758e43b7SStephen Hemminger 
28281da177e4SLinus Torvalds 		tun = netdev_priv(dev);
28291da177e4SLinus Torvalds 		tun->dev = dev;
28301da177e4SLinus Torvalds 		tun->flags = flags;
2831f271b2ccSMax Krasnyansky 		tun->txflt.count = 0;
2832d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
28331da177e4SLinus Torvalds 
2834eaea34b2SPaolo Abeni 		tun->align = NET_SKB_PAD;
283554f968d6SJason Wang 		tun->filter_attached = false;
283654f968d6SJason Wang 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
28375503fcecSJason Wang 		tun->rx_batched = 0;
283896f84061SJason Wang 		RCU_INIT_POINTER(tun->steering_prog, NULL);
283933dccbb0SHerbert Xu 
2840158b515fSGeorge Kennedy 		tun->ifr = ifr;
2841158b515fSGeorge Kennedy 		tun->file = file;
2842608b9977SPaolo Abeni 
2843158b515fSGeorge Kennedy 		tun_net_initialize(dev);
2844eb0fb363SJason Wang 
28451da177e4SLinus Torvalds 		err = register_netdevice(tun->dev);
2846158b515fSGeorge Kennedy 		if (err < 0) {
2847158b515fSGeorge Kennedy 			free_netdev(dev);
2848158b515fSGeorge Kennedy 			return err;
2849158b515fSGeorge Kennedy 		}
2850c2e315b8SMenglong Dong 		/* free_netdev() won't check refcnt, to avoid race
285177f22f92SYang Yingliang 		 * with dev_put() we need publish tun after registration.
285277f22f92SYang Yingliang 		 */
285377f22f92SYang Yingliang 		rcu_assign_pointer(tfile->tun, tun);
2854af668b3cSMichael S. Tsirkin 	}
2855980c9e8cSDavid Woodhouse 
2856195624d9SPatrick Rohr 	if (ifr->ifr_flags & IFF_NO_CARRIER)
2857195624d9SPatrick Rohr 		netif_carrier_off(tun->dev);
2858195624d9SPatrick Rohr 	else
2859eb0fb363SJason Wang 		netif_carrier_on(tun->dev);
28601da177e4SLinus Torvalds 
2861e35259a9SMax Krasnyansky 	/* Make sure persistent devices do not get stuck in
2862e35259a9SMax Krasnyansky 	 * xoff state.
2863e35259a9SMax Krasnyansky 	 */
2864e35259a9SMax Krasnyansky 	if (netif_running(tun->dev))
2865c8d68e6bSJason Wang 		netif_tx_wake_all_queues(tun->dev);
2866e35259a9SMax Krasnyansky 
28671da177e4SLinus Torvalds 	strcpy(ifr->ifr_name, tun->dev->name);
28681da177e4SLinus Torvalds 	return 0;
28691da177e4SLinus Torvalds }
28701da177e4SLinus Torvalds 
287112132768SKirill Tkhai static void tun_get_iff(struct tun_struct *tun, struct ifreq *ifr)
2872e3b99556SMark McLoughlin {
2873e3b99556SMark McLoughlin 	strcpy(ifr->ifr_name, tun->dev->name);
2874e3b99556SMark McLoughlin 
2875980c9e8cSDavid Woodhouse 	ifr->ifr_flags = tun_flags(tun);
2876e3b99556SMark McLoughlin 
2877e3b99556SMark McLoughlin }
2878e3b99556SMark McLoughlin 
28795228ddc9SRusty Russell /* This is like a cut-down ethtool ops, except done via tun fd so no
28805228ddc9SRusty Russell  * privs required. */
288188255375SMichał Mirosław static int set_offload(struct tun_struct *tun, unsigned long arg)
28825228ddc9SRusty Russell {
2883c8f44affSMichał Mirosław 	netdev_features_t features = 0;
28845228ddc9SRusty Russell 
28855228ddc9SRusty Russell 	if (arg & TUN_F_CSUM) {
288688255375SMichał Mirosław 		features |= NETIF_F_HW_CSUM;
28875228ddc9SRusty Russell 		arg &= ~TUN_F_CSUM;
28885228ddc9SRusty Russell 
28895228ddc9SRusty Russell 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
28905228ddc9SRusty Russell 			if (arg & TUN_F_TSO_ECN) {
28915228ddc9SRusty Russell 				features |= NETIF_F_TSO_ECN;
28925228ddc9SRusty Russell 				arg &= ~TUN_F_TSO_ECN;
28935228ddc9SRusty Russell 			}
28945228ddc9SRusty Russell 			if (arg & TUN_F_TSO4)
28955228ddc9SRusty Russell 				features |= NETIF_F_TSO;
28965228ddc9SRusty Russell 			if (arg & TUN_F_TSO6)
28975228ddc9SRusty Russell 				features |= NETIF_F_TSO6;
28985228ddc9SRusty Russell 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
28995228ddc9SRusty Russell 		}
29000c19f846SWillem de Bruijn 
29010c19f846SWillem de Bruijn 		arg &= ~TUN_F_UFO;
2902399e0827SAndrew Melnychenko 
2903399e0827SAndrew Melnychenko 		/* TODO: for now USO4 and USO6 should work simultaneously */
2904399e0827SAndrew Melnychenko 		if (arg & TUN_F_USO4 && arg & TUN_F_USO6) {
2905399e0827SAndrew Melnychenko 			features |= NETIF_F_GSO_UDP_L4;
2906399e0827SAndrew Melnychenko 			arg &= ~(TUN_F_USO4 | TUN_F_USO6);
2907399e0827SAndrew Melnychenko 		}
29085228ddc9SRusty Russell 	}
29095228ddc9SRusty Russell 
29105228ddc9SRusty Russell 	/* This gives the user a way to test for new features in future by
29115228ddc9SRusty Russell 	 * trying to set them. */
29125228ddc9SRusty Russell 	if (arg)
29135228ddc9SRusty Russell 		return -EINVAL;
29145228ddc9SRusty Russell 
291588255375SMichał Mirosław 	tun->set_features = features;
291609050957SYaroslav Isakov 	tun->dev->wanted_features &= ~TUN_USER_FEATURES;
291709050957SYaroslav Isakov 	tun->dev->wanted_features |= features;
291888255375SMichał Mirosław 	netdev_update_features(tun->dev);
29195228ddc9SRusty Russell 
29205228ddc9SRusty Russell 	return 0;
29215228ddc9SRusty Russell }
29225228ddc9SRusty Russell 
2923c8d68e6bSJason Wang static void tun_detach_filter(struct tun_struct *tun, int n)
2924c8d68e6bSJason Wang {
2925c8d68e6bSJason Wang 	int i;
2926c8d68e6bSJason Wang 	struct tun_file *tfile;
2927c8d68e6bSJason Wang 
2928c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
2929b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
29308ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
29318ced425eSHannes Frederic Sowa 		sk_detach_filter(tfile->socket.sk);
29328ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2933c8d68e6bSJason Wang 	}
2934c8d68e6bSJason Wang 
2935c8d68e6bSJason Wang 	tun->filter_attached = false;
2936c8d68e6bSJason Wang }
2937c8d68e6bSJason Wang 
2938c8d68e6bSJason Wang static int tun_attach_filter(struct tun_struct *tun)
2939c8d68e6bSJason Wang {
2940c8d68e6bSJason Wang 	int i, ret = 0;
2941c8d68e6bSJason Wang 	struct tun_file *tfile;
2942c8d68e6bSJason Wang 
2943c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2944b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
29458ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
29468ced425eSHannes Frederic Sowa 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
29478ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2948c8d68e6bSJason Wang 		if (ret) {
2949c8d68e6bSJason Wang 			tun_detach_filter(tun, i);
2950c8d68e6bSJason Wang 			return ret;
2951c8d68e6bSJason Wang 		}
2952c8d68e6bSJason Wang 	}
2953c8d68e6bSJason Wang 
2954c8d68e6bSJason Wang 	tun->filter_attached = true;
2955c8d68e6bSJason Wang 	return ret;
2956c8d68e6bSJason Wang }
2957c8d68e6bSJason Wang 
2958c8d68e6bSJason Wang static void tun_set_sndbuf(struct tun_struct *tun)
2959c8d68e6bSJason Wang {
2960c8d68e6bSJason Wang 	struct tun_file *tfile;
2961c8d68e6bSJason Wang 	int i;
2962c8d68e6bSJason Wang 
2963c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2964b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
2965c8d68e6bSJason Wang 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2966c8d68e6bSJason Wang 	}
2967c8d68e6bSJason Wang }
2968c8d68e6bSJason Wang 
2969cde8b15fSJason Wang static int tun_set_queue(struct file *file, struct ifreq *ifr)
2970cde8b15fSJason Wang {
2971cde8b15fSJason Wang 	struct tun_file *tfile = file->private_data;
2972cde8b15fSJason Wang 	struct tun_struct *tun;
2973cde8b15fSJason Wang 	int ret = 0;
2974cde8b15fSJason Wang 
2975cde8b15fSJason Wang 	rtnl_lock();
2976cde8b15fSJason Wang 
2977cde8b15fSJason Wang 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
29784008e97fSJason Wang 		tun = tfile->detached;
29795dbbaf2dSPaul Moore 		if (!tun) {
2980cde8b15fSJason Wang 			ret = -EINVAL;
29815dbbaf2dSPaul Moore 			goto unlock;
29825dbbaf2dSPaul Moore 		}
29835dbbaf2dSPaul Moore 		ret = security_tun_dev_attach_queue(tun->security);
29845dbbaf2dSPaul Moore 		if (ret < 0)
29855dbbaf2dSPaul Moore 			goto unlock;
2986af3fb24eSEric Dumazet 		ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
298777f22f92SYang Yingliang 				 tun->flags & IFF_NAPI_FRAGS, true);
29884008e97fSJason Wang 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2989b8deabd3SJason Wang 		tun = rtnl_dereference(tfile->tun);
299040630b82SMichael S. Tsirkin 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
29914008e97fSJason Wang 			ret = -EINVAL;
2992cde8b15fSJason Wang 		else
29934008e97fSJason Wang 			__tun_detach(tfile, false);
29944008e97fSJason Wang 	} else
2995cde8b15fSJason Wang 		ret = -EINVAL;
2996cde8b15fSJason Wang 
299783c1f36fSSabrina Dubroca 	if (ret >= 0)
299883c1f36fSSabrina Dubroca 		netdev_state_change(tun->dev);
299983c1f36fSSabrina Dubroca 
30005dbbaf2dSPaul Moore unlock:
3001cde8b15fSJason Wang 	rtnl_unlock();
3002cde8b15fSJason Wang 	return ret;
3003cde8b15fSJason Wang }
3004cde8b15fSJason Wang 
30058f3f330dSJason Wang static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog __rcu **prog_p,
3006cd5681d7SJason Wang 			void __user *data)
300796f84061SJason Wang {
300896f84061SJason Wang 	struct bpf_prog *prog;
300996f84061SJason Wang 	int fd;
301096f84061SJason Wang 
301196f84061SJason Wang 	if (copy_from_user(&fd, data, sizeof(fd)))
301296f84061SJason Wang 		return -EFAULT;
301396f84061SJason Wang 
301496f84061SJason Wang 	if (fd == -1) {
301596f84061SJason Wang 		prog = NULL;
301696f84061SJason Wang 	} else {
301796f84061SJason Wang 		prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
301896f84061SJason Wang 		if (IS_ERR(prog))
301996f84061SJason Wang 			return PTR_ERR(prog);
302096f84061SJason Wang 	}
302196f84061SJason Wang 
3022cd5681d7SJason Wang 	return __tun_set_ebpf(tun, prog_p, prog);
302396f84061SJason Wang }
302496f84061SJason Wang 
3025cca8ea3bSPhillip Potter /* Return correct value for tun->dev->addr_len based on tun->dev->type. */
3026cca8ea3bSPhillip Potter static unsigned char tun_get_addr_len(unsigned short type)
3027cca8ea3bSPhillip Potter {
3028cca8ea3bSPhillip Potter 	switch (type) {
3029cca8ea3bSPhillip Potter 	case ARPHRD_IP6GRE:
3030cca8ea3bSPhillip Potter 	case ARPHRD_TUNNEL6:
3031cca8ea3bSPhillip Potter 		return sizeof(struct in6_addr);
3032cca8ea3bSPhillip Potter 	case ARPHRD_IPGRE:
3033cca8ea3bSPhillip Potter 	case ARPHRD_TUNNEL:
3034cca8ea3bSPhillip Potter 	case ARPHRD_SIT:
3035cca8ea3bSPhillip Potter 		return 4;
3036cca8ea3bSPhillip Potter 	case ARPHRD_ETHER:
3037cca8ea3bSPhillip Potter 		return ETH_ALEN;
3038cca8ea3bSPhillip Potter 	case ARPHRD_IEEE802154:
3039cca8ea3bSPhillip Potter 	case ARPHRD_IEEE802154_MONITOR:
3040cca8ea3bSPhillip Potter 		return IEEE802154_EXTENDED_ADDR_LEN;
3041cca8ea3bSPhillip Potter 	case ARPHRD_PHONET_PIPE:
3042cca8ea3bSPhillip Potter 	case ARPHRD_PPP:
3043cca8ea3bSPhillip Potter 	case ARPHRD_NONE:
3044cca8ea3bSPhillip Potter 		return 0;
3045cca8ea3bSPhillip Potter 	case ARPHRD_6LOWPAN:
3046cca8ea3bSPhillip Potter 		return EUI64_ADDR_LEN;
3047cca8ea3bSPhillip Potter 	case ARPHRD_FDDI:
3048cca8ea3bSPhillip Potter 		return FDDI_K_ALEN;
3049cca8ea3bSPhillip Potter 	case ARPHRD_HIPPI:
3050cca8ea3bSPhillip Potter 		return HIPPI_ALEN;
3051cca8ea3bSPhillip Potter 	case ARPHRD_IEEE802:
3052cca8ea3bSPhillip Potter 		return FC_ALEN;
3053cca8ea3bSPhillip Potter 	case ARPHRD_ROSE:
3054cca8ea3bSPhillip Potter 		return ROSE_ADDR_LEN;
3055cca8ea3bSPhillip Potter 	case ARPHRD_NETROM:
3056cca8ea3bSPhillip Potter 		return AX25_ADDR_LEN;
3057cca8ea3bSPhillip Potter 	case ARPHRD_LOCALTLK:
3058cca8ea3bSPhillip Potter 		return LTALK_ALEN;
3059cca8ea3bSPhillip Potter 	default:
3060cca8ea3bSPhillip Potter 		return 0;
3061cca8ea3bSPhillip Potter 	}
3062cca8ea3bSPhillip Potter }
3063cca8ea3bSPhillip Potter 
306450857e2aSArnd Bergmann static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
306550857e2aSArnd Bergmann 			    unsigned long arg, int ifreq_len)
30661da177e4SLinus Torvalds {
306736b50babSEric W. Biederman 	struct tun_file *tfile = file->private_data;
3068f663706aSKirill Tkhai 	struct net *net = sock_net(&tfile->sk);
3069631ab46bSEric W. Biederman 	struct tun_struct *tun;
30701da177e4SLinus Torvalds 	void __user* argp = (void __user*)arg;
307126d31925SNicolas Dichtel 	unsigned int ifindex, carrier;
30721da177e4SLinus Torvalds 	struct ifreq ifr;
30730625c883SEric W. Biederman 	kuid_t owner;
30740625c883SEric W. Biederman 	kgid_t group;
307533dccbb0SHerbert Xu 	int sndbuf;
3076d9d52b51SMichael S. Tsirkin 	int vnet_hdr_sz;
30771cf8e410SMichael S. Tsirkin 	int le;
3078f271b2ccSMax Krasnyansky 	int ret;
307983c1f36fSSabrina Dubroca 	bool do_notify = false;
30801da177e4SLinus Torvalds 
3081f2780d6dSKirill Tkhai 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
3082f2780d6dSKirill Tkhai 	    (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
308350857e2aSArnd Bergmann 		if (copy_from_user(&ifr, argp, ifreq_len))
30841da177e4SLinus Torvalds 			return -EFAULT;
30858bbb1813SDavid S. Miller 	} else {
3086a117dacdSMathias Krause 		memset(&ifr, 0, sizeof(ifr));
30878bbb1813SDavid S. Miller 	}
3088631ab46bSEric W. Biederman 	if (cmd == TUNGETFEATURES) {
3089631ab46bSEric W. Biederman 		/* Currently this just means: "what IFF flags are valid?".
3090631ab46bSEric W. Biederman 		 * This is needed because we never checked for invalid flags on
3091031f5e03SMichael S. Tsirkin 		 * TUNSETIFF.
3092031f5e03SMichael S. Tsirkin 		 */
3093195624d9SPatrick Rohr 		return put_user(IFF_TUN | IFF_TAP | IFF_NO_CARRIER |
3094195624d9SPatrick Rohr 				TUN_FEATURES, (unsigned int __user*)argp);
3095f663706aSKirill Tkhai 	} else if (cmd == TUNSETQUEUE) {
3096cde8b15fSJason Wang 		return tun_set_queue(file, &ifr);
3097f663706aSKirill Tkhai 	} else if (cmd == SIOCGSKNS) {
3098f663706aSKirill Tkhai 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3099f663706aSKirill Tkhai 			return -EPERM;
3100f663706aSKirill Tkhai 		return open_related_ns(&net->ns, get_net_ns);
3101f663706aSKirill Tkhai 	}
3102631ab46bSEric W. Biederman 
3103876bfd4dSHerbert Xu 	rtnl_lock();
3104876bfd4dSHerbert Xu 
31059484dc74Syuan linyu 	tun = tun_get(tfile);
31060f16bc13SGao Feng 	if (cmd == TUNSETIFF) {
31070f16bc13SGao Feng 		ret = -EEXIST;
31080f16bc13SGao Feng 		if (tun)
31090f16bc13SGao Feng 			goto unlock;
31100f16bc13SGao Feng 
31111da177e4SLinus Torvalds 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
31121da177e4SLinus Torvalds 
3113f2780d6dSKirill Tkhai 		ret = tun_set_iff(net, file, &ifr);
31141da177e4SLinus Torvalds 
3115876bfd4dSHerbert Xu 		if (ret)
3116876bfd4dSHerbert Xu 			goto unlock;
31171da177e4SLinus Torvalds 
311850857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3119876bfd4dSHerbert Xu 			ret = -EFAULT;
3120876bfd4dSHerbert Xu 		goto unlock;
31211da177e4SLinus Torvalds 	}
3122fb7589a1SPavel Emelyanov 	if (cmd == TUNSETIFINDEX) {
3123fb7589a1SPavel Emelyanov 		ret = -EPERM;
3124fb7589a1SPavel Emelyanov 		if (tun)
3125fb7589a1SPavel Emelyanov 			goto unlock;
3126fb7589a1SPavel Emelyanov 
3127fb7589a1SPavel Emelyanov 		ret = -EFAULT;
3128fb7589a1SPavel Emelyanov 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
3129fb7589a1SPavel Emelyanov 			goto unlock;
3130fb7589a1SPavel Emelyanov 
3131fb7589a1SPavel Emelyanov 		ret = 0;
3132fb7589a1SPavel Emelyanov 		tfile->ifindex = ifindex;
3133fb7589a1SPavel Emelyanov 		goto unlock;
3134fb7589a1SPavel Emelyanov 	}
31351da177e4SLinus Torvalds 
3136876bfd4dSHerbert Xu 	ret = -EBADFD;
31371da177e4SLinus Torvalds 	if (!tun)
3138876bfd4dSHerbert Xu 		goto unlock;
31391da177e4SLinus Torvalds 
31403424170fSMichal Kubecek 	netif_info(tun, drv, tun->dev, "tun_chr_ioctl cmd %u\n", cmd);
31411da177e4SLinus Torvalds 
31420c3e0e3bSKirill Tkhai 	net = dev_net(tun->dev);
3143631ab46bSEric W. Biederman 	ret = 0;
31441da177e4SLinus Torvalds 	switch (cmd) {
3145e3b99556SMark McLoughlin 	case TUNGETIFF:
314612132768SKirill Tkhai 		tun_get_iff(tun, &ifr);
3147e3b99556SMark McLoughlin 
31483d407a80SPavel Emelyanov 		if (tfile->detached)
31493d407a80SPavel Emelyanov 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
3150849c9b6fSPavel Emelyanov 		if (!tfile->socket.sk->sk_filter)
3151849c9b6fSPavel Emelyanov 			ifr.ifr_flags |= IFF_NOFILTER;
31523d407a80SPavel Emelyanov 
315350857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3154631ab46bSEric W. Biederman 			ret = -EFAULT;
3155e3b99556SMark McLoughlin 		break;
3156e3b99556SMark McLoughlin 
31571da177e4SLinus Torvalds 	case TUNSETNOCSUM:
31581da177e4SLinus Torvalds 		/* Disable/Enable checksum */
31591da177e4SLinus Torvalds 
316088255375SMichał Mirosław 		/* [unimplemented] */
31613424170fSMichal Kubecek 		netif_info(tun, drv, tun->dev, "ignored: set checksum %s\n",
31626b8a66eeSJoe Perches 			   arg ? "disabled" : "enabled");
31631da177e4SLinus Torvalds 		break;
31641da177e4SLinus Torvalds 
31651da177e4SLinus Torvalds 	case TUNSETPERSIST:
316654f968d6SJason Wang 		/* Disable/Enable persist mode. Keep an extra reference to the
316754f968d6SJason Wang 		 * module to prevent the module being unprobed.
316854f968d6SJason Wang 		 */
316940630b82SMichael S. Tsirkin 		if (arg && !(tun->flags & IFF_PERSIST)) {
317040630b82SMichael S. Tsirkin 			tun->flags |= IFF_PERSIST;
317154f968d6SJason Wang 			__module_get(THIS_MODULE);
317283c1f36fSSabrina Dubroca 			do_notify = true;
3173dd38bd85SJason Wang 		}
317440630b82SMichael S. Tsirkin 		if (!arg && (tun->flags & IFF_PERSIST)) {
317540630b82SMichael S. Tsirkin 			tun->flags &= ~IFF_PERSIST;
317654f968d6SJason Wang 			module_put(THIS_MODULE);
317783c1f36fSSabrina Dubroca 			do_notify = true;
317854f968d6SJason Wang 		}
31791da177e4SLinus Torvalds 
31803424170fSMichal Kubecek 		netif_info(tun, drv, tun->dev, "persist %s\n",
31816b8a66eeSJoe Perches 			   arg ? "enabled" : "disabled");
31821da177e4SLinus Torvalds 		break;
31831da177e4SLinus Torvalds 
31841da177e4SLinus Torvalds 	case TUNSETOWNER:
31851da177e4SLinus Torvalds 		/* Set owner of the device */
31860625c883SEric W. Biederman 		owner = make_kuid(current_user_ns(), arg);
31870625c883SEric W. Biederman 		if (!uid_valid(owner)) {
31880625c883SEric W. Biederman 			ret = -EINVAL;
31890625c883SEric W. Biederman 			break;
31900625c883SEric W. Biederman 		}
31910625c883SEric W. Biederman 		tun->owner = owner;
319283c1f36fSSabrina Dubroca 		do_notify = true;
31933424170fSMichal Kubecek 		netif_info(tun, drv, tun->dev, "owner set to %u\n",
31940625c883SEric W. Biederman 			   from_kuid(&init_user_ns, tun->owner));
31951da177e4SLinus Torvalds 		break;
31961da177e4SLinus Torvalds 
31978c644623SGuido Guenther 	case TUNSETGROUP:
31988c644623SGuido Guenther 		/* Set group of the device */
31990625c883SEric W. Biederman 		group = make_kgid(current_user_ns(), arg);
32000625c883SEric W. Biederman 		if (!gid_valid(group)) {
32010625c883SEric W. Biederman 			ret = -EINVAL;
32020625c883SEric W. Biederman 			break;
32030625c883SEric W. Biederman 		}
32040625c883SEric W. Biederman 		tun->group = group;
320583c1f36fSSabrina Dubroca 		do_notify = true;
32063424170fSMichal Kubecek 		netif_info(tun, drv, tun->dev, "group set to %u\n",
32070625c883SEric W. Biederman 			   from_kgid(&init_user_ns, tun->group));
32088c644623SGuido Guenther 		break;
32098c644623SGuido Guenther 
3210ff4cc3acSMike Kershaw 	case TUNSETLINK:
3211ff4cc3acSMike Kershaw 		/* Only allow setting the type when the interface is down */
3212ff4cc3acSMike Kershaw 		if (tun->dev->flags & IFF_UP) {
32133424170fSMichal Kubecek 			netif_info(tun, drv, tun->dev,
32146b8a66eeSJoe Perches 				   "Linktype set failed because interface is up\n");
321548abfe05SDavid S. Miller 			ret = -EBUSY;
3216ff4cc3acSMike Kershaw 		} else {
32178e1e33ffSMartin Schiller 			ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE,
32188e1e33ffSMartin Schiller 						       tun->dev);
32198e1e33ffSMartin Schiller 			ret = notifier_to_errno(ret);
32208e1e33ffSMartin Schiller 			if (ret) {
32218e1e33ffSMartin Schiller 				netif_info(tun, drv, tun->dev,
32228e1e33ffSMartin Schiller 					   "Refused to change device type\n");
32238e1e33ffSMartin Schiller 				break;
32248e1e33ffSMartin Schiller 			}
3225ff4cc3acSMike Kershaw 			tun->dev->type = (int) arg;
3226cca8ea3bSPhillip Potter 			tun->dev->addr_len = tun_get_addr_len(tun->dev->type);
32273424170fSMichal Kubecek 			netif_info(tun, drv, tun->dev, "linktype set to %d\n",
32286b8a66eeSJoe Perches 				   tun->dev->type);
32298e1e33ffSMartin Schiller 			call_netdevice_notifiers(NETDEV_POST_TYPE_CHANGE,
32308e1e33ffSMartin Schiller 						 tun->dev);
3231ff4cc3acSMike Kershaw 		}
3232631ab46bSEric W. Biederman 		break;
3233ff4cc3acSMike Kershaw 
32341da177e4SLinus Torvalds 	case TUNSETDEBUG:
32353424170fSMichal Kubecek 		tun->msg_enable = (u32)arg;
32361da177e4SLinus Torvalds 		break;
32373424170fSMichal Kubecek 
32385228ddc9SRusty Russell 	case TUNSETOFFLOAD:
323988255375SMichał Mirosław 		ret = set_offload(tun, arg);
3240631ab46bSEric W. Biederman 		break;
32415228ddc9SRusty Russell 
3242f271b2ccSMax Krasnyansky 	case TUNSETTXFILTER:
3243f271b2ccSMax Krasnyansky 		/* Can be set only for TAPs */
3244631ab46bSEric W. Biederman 		ret = -EINVAL;
324540630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3246631ab46bSEric W. Biederman 			break;
3247c0e5a8c2SHarvey Harrison 		ret = update_filter(&tun->txflt, (void __user *)arg);
3248631ab46bSEric W. Biederman 		break;
32491da177e4SLinus Torvalds 
32501da177e4SLinus Torvalds 	case SIOCGIFHWADDR:
3251b595076aSUwe Kleine-König 		/* Get hw address */
32523b23a32aSCong Wang 		dev_get_mac_address(&ifr.ifr_hwaddr, net, tun->dev->name);
325350857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3254631ab46bSEric W. Biederman 			ret = -EFAULT;
3255631ab46bSEric W. Biederman 		break;
32561da177e4SLinus Torvalds 
32571da177e4SLinus Torvalds 	case SIOCSIFHWADDR:
3258f271b2ccSMax Krasnyansky 		/* Set hw address */
32593b23a32aSCong Wang 		ret = dev_set_mac_address_user(tun->dev, &ifr.ifr_hwaddr, NULL);
3260631ab46bSEric W. Biederman 		break;
326133dccbb0SHerbert Xu 
326233dccbb0SHerbert Xu 	case TUNGETSNDBUF:
326354f968d6SJason Wang 		sndbuf = tfile->socket.sk->sk_sndbuf;
326433dccbb0SHerbert Xu 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
326533dccbb0SHerbert Xu 			ret = -EFAULT;
326633dccbb0SHerbert Xu 		break;
326733dccbb0SHerbert Xu 
326833dccbb0SHerbert Xu 	case TUNSETSNDBUF:
326933dccbb0SHerbert Xu 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
327033dccbb0SHerbert Xu 			ret = -EFAULT;
327133dccbb0SHerbert Xu 			break;
327233dccbb0SHerbert Xu 		}
327393161922SCraig Gallek 		if (sndbuf <= 0) {
327493161922SCraig Gallek 			ret = -EINVAL;
327593161922SCraig Gallek 			break;
327693161922SCraig Gallek 		}
327733dccbb0SHerbert Xu 
3278c8d68e6bSJason Wang 		tun->sndbuf = sndbuf;
3279c8d68e6bSJason Wang 		tun_set_sndbuf(tun);
328033dccbb0SHerbert Xu 		break;
328133dccbb0SHerbert Xu 
3282d9d52b51SMichael S. Tsirkin 	case TUNGETVNETHDRSZ:
3283d9d52b51SMichael S. Tsirkin 		vnet_hdr_sz = tun->vnet_hdr_sz;
3284d9d52b51SMichael S. Tsirkin 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
3285d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
3286d9d52b51SMichael S. Tsirkin 		break;
3287d9d52b51SMichael S. Tsirkin 
3288d9d52b51SMichael S. Tsirkin 	case TUNSETVNETHDRSZ:
3289d9d52b51SMichael S. Tsirkin 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
3290d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
3291d9d52b51SMichael S. Tsirkin 			break;
3292d9d52b51SMichael S. Tsirkin 		}
3293d9d52b51SMichael S. Tsirkin 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
3294d9d52b51SMichael S. Tsirkin 			ret = -EINVAL;
3295d9d52b51SMichael S. Tsirkin 			break;
3296d9d52b51SMichael S. Tsirkin 		}
3297d9d52b51SMichael S. Tsirkin 
3298d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = vnet_hdr_sz;
3299d9d52b51SMichael S. Tsirkin 		break;
3300d9d52b51SMichael S. Tsirkin 
33011cf8e410SMichael S. Tsirkin 	case TUNGETVNETLE:
33021cf8e410SMichael S. Tsirkin 		le = !!(tun->flags & TUN_VNET_LE);
33031cf8e410SMichael S. Tsirkin 		if (put_user(le, (int __user *)argp))
33041cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
33051cf8e410SMichael S. Tsirkin 		break;
33061cf8e410SMichael S. Tsirkin 
33071cf8e410SMichael S. Tsirkin 	case TUNSETVNETLE:
33081cf8e410SMichael S. Tsirkin 		if (get_user(le, (int __user *)argp)) {
33091cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
33101cf8e410SMichael S. Tsirkin 			break;
33111cf8e410SMichael S. Tsirkin 		}
33121cf8e410SMichael S. Tsirkin 		if (le)
33131cf8e410SMichael S. Tsirkin 			tun->flags |= TUN_VNET_LE;
33141cf8e410SMichael S. Tsirkin 		else
33151cf8e410SMichael S. Tsirkin 			tun->flags &= ~TUN_VNET_LE;
33161cf8e410SMichael S. Tsirkin 		break;
33171cf8e410SMichael S. Tsirkin 
33188b8e658bSGreg Kurz 	case TUNGETVNETBE:
33198b8e658bSGreg Kurz 		ret = tun_get_vnet_be(tun, argp);
33208b8e658bSGreg Kurz 		break;
33218b8e658bSGreg Kurz 
33228b8e658bSGreg Kurz 	case TUNSETVNETBE:
33238b8e658bSGreg Kurz 		ret = tun_set_vnet_be(tun, argp);
33248b8e658bSGreg Kurz 		break;
33258b8e658bSGreg Kurz 
332699405162SMichael S. Tsirkin 	case TUNATTACHFILTER:
332799405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
332899405162SMichael S. Tsirkin 		ret = -EINVAL;
332940630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
333099405162SMichael S. Tsirkin 			break;
333199405162SMichael S. Tsirkin 		ret = -EFAULT;
333254f968d6SJason Wang 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
333399405162SMichael S. Tsirkin 			break;
333499405162SMichael S. Tsirkin 
3335c8d68e6bSJason Wang 		ret = tun_attach_filter(tun);
333699405162SMichael S. Tsirkin 		break;
333799405162SMichael S. Tsirkin 
333899405162SMichael S. Tsirkin 	case TUNDETACHFILTER:
333999405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
334099405162SMichael S. Tsirkin 		ret = -EINVAL;
334140630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
334299405162SMichael S. Tsirkin 			break;
3343c8d68e6bSJason Wang 		ret = 0;
3344c8d68e6bSJason Wang 		tun_detach_filter(tun, tun->numqueues);
334599405162SMichael S. Tsirkin 		break;
334699405162SMichael S. Tsirkin 
334776975e9cSPavel Emelyanov 	case TUNGETFILTER:
334876975e9cSPavel Emelyanov 		ret = -EINVAL;
334940630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
335076975e9cSPavel Emelyanov 			break;
335176975e9cSPavel Emelyanov 		ret = -EFAULT;
335276975e9cSPavel Emelyanov 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
335376975e9cSPavel Emelyanov 			break;
335476975e9cSPavel Emelyanov 		ret = 0;
335576975e9cSPavel Emelyanov 		break;
335676975e9cSPavel Emelyanov 
335796f84061SJason Wang 	case TUNSETSTEERINGEBPF:
3358cd5681d7SJason Wang 		ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
335996f84061SJason Wang 		break;
336096f84061SJason Wang 
3361aff3d70aSJason Wang 	case TUNSETFILTEREBPF:
3362aff3d70aSJason Wang 		ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3363aff3d70aSJason Wang 		break;
3364aff3d70aSJason Wang 
336526d31925SNicolas Dichtel 	case TUNSETCARRIER:
336626d31925SNicolas Dichtel 		ret = -EFAULT;
336726d31925SNicolas Dichtel 		if (copy_from_user(&carrier, argp, sizeof(carrier)))
336826d31925SNicolas Dichtel 			goto unlock;
336926d31925SNicolas Dichtel 
337026d31925SNicolas Dichtel 		ret = tun_net_change_carrier(tun->dev, (bool)carrier);
337126d31925SNicolas Dichtel 		break;
337226d31925SNicolas Dichtel 
33730c3e0e3bSKirill Tkhai 	case TUNGETDEVNETNS:
33740c3e0e3bSKirill Tkhai 		ret = -EPERM;
33750c3e0e3bSKirill Tkhai 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
33760c3e0e3bSKirill Tkhai 			goto unlock;
33770c3e0e3bSKirill Tkhai 		ret = open_related_ns(&net->ns, get_net_ns);
33780c3e0e3bSKirill Tkhai 		break;
33790c3e0e3bSKirill Tkhai 
33801da177e4SLinus Torvalds 	default:
3381631ab46bSEric W. Biederman 		ret = -EINVAL;
3382631ab46bSEric W. Biederman 		break;
3383ee289b64SJoe Perches 	}
33841da177e4SLinus Torvalds 
338583c1f36fSSabrina Dubroca 	if (do_notify)
338683c1f36fSSabrina Dubroca 		netdev_state_change(tun->dev);
338783c1f36fSSabrina Dubroca 
3388876bfd4dSHerbert Xu unlock:
3389876bfd4dSHerbert Xu 	rtnl_unlock();
3390876bfd4dSHerbert Xu 	if (tun)
3391631ab46bSEric W. Biederman 		tun_put(tun);
3392631ab46bSEric W. Biederman 	return ret;
33931da177e4SLinus Torvalds }
33941da177e4SLinus Torvalds 
339550857e2aSArnd Bergmann static long tun_chr_ioctl(struct file *file,
339650857e2aSArnd Bergmann 			  unsigned int cmd, unsigned long arg)
339750857e2aSArnd Bergmann {
339850857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
339950857e2aSArnd Bergmann }
340050857e2aSArnd Bergmann 
340150857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
340250857e2aSArnd Bergmann static long tun_chr_compat_ioctl(struct file *file,
340350857e2aSArnd Bergmann 			 unsigned int cmd, unsigned long arg)
340450857e2aSArnd Bergmann {
340550857e2aSArnd Bergmann 	switch (cmd) {
340650857e2aSArnd Bergmann 	case TUNSETIFF:
340750857e2aSArnd Bergmann 	case TUNGETIFF:
340850857e2aSArnd Bergmann 	case TUNSETTXFILTER:
340950857e2aSArnd Bergmann 	case TUNGETSNDBUF:
341050857e2aSArnd Bergmann 	case TUNSETSNDBUF:
341150857e2aSArnd Bergmann 	case SIOCGIFHWADDR:
341250857e2aSArnd Bergmann 	case SIOCSIFHWADDR:
341350857e2aSArnd Bergmann 		arg = (unsigned long)compat_ptr(arg);
341450857e2aSArnd Bergmann 		break;
341550857e2aSArnd Bergmann 	default:
341650857e2aSArnd Bergmann 		arg = (compat_ulong_t)arg;
341750857e2aSArnd Bergmann 		break;
341850857e2aSArnd Bergmann 	}
341950857e2aSArnd Bergmann 
342050857e2aSArnd Bergmann 	/*
342150857e2aSArnd Bergmann 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
342250857e2aSArnd Bergmann 	 * the end of that structure. All fields that are used in this
342350857e2aSArnd Bergmann 	 * driver are compatible though, we don't need to convert the
342450857e2aSArnd Bergmann 	 * contents.
342550857e2aSArnd Bergmann 	 */
342650857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
342750857e2aSArnd Bergmann }
342850857e2aSArnd Bergmann #endif /* CONFIG_COMPAT */
342950857e2aSArnd Bergmann 
34301da177e4SLinus Torvalds static int tun_chr_fasync(int fd, struct file *file, int on)
34311da177e4SLinus Torvalds {
343254f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
34331da177e4SLinus Torvalds 	int ret;
34341da177e4SLinus Torvalds 
343554f968d6SJason Wang 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
34369d319522SJonathan Corbet 		goto out;
34371da177e4SLinus Torvalds 
34381da177e4SLinus Torvalds 	if (on) {
343901919134SEric W. Biederman 		__f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
344054f968d6SJason Wang 		tfile->flags |= TUN_FASYNC;
34411da177e4SLinus Torvalds 	} else
344254f968d6SJason Wang 		tfile->flags &= ~TUN_FASYNC;
34439d319522SJonathan Corbet 	ret = 0;
34449d319522SJonathan Corbet out:
34459d319522SJonathan Corbet 	return ret;
34461da177e4SLinus Torvalds }
34471da177e4SLinus Torvalds 
34481da177e4SLinus Torvalds static int tun_chr_open(struct inode *inode, struct file * file)
34491da177e4SLinus Torvalds {
3450140e807dSEric W. Biederman 	struct net *net = current->nsproxy->net_ns;
3451631ab46bSEric W. Biederman 	struct tun_file *tfile;
3452deed49fbSThomas Gleixner 
3453140e807dSEric W. Biederman 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
345411aa9c28SEric W. Biederman 					    &tun_proto, 0);
3455631ab46bSEric W. Biederman 	if (!tfile)
3456631ab46bSEric W. Biederman 		return -ENOMEM;
3457b196d88aSJason Wang 	if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
3458b196d88aSJason Wang 		sk_free(&tfile->sk);
3459b196d88aSJason Wang 		return -ENOMEM;
3460b196d88aSJason Wang 	}
3461b196d88aSJason Wang 
3462c7256f57SEric Dumazet 	mutex_init(&tfile->napi_mutex);
3463c956674bSMonam Agarwal 	RCU_INIT_POINTER(tfile->tun, NULL);
346454f968d6SJason Wang 	tfile->flags = 0;
3465fb7589a1SPavel Emelyanov 	tfile->ifindex = 0;
346654f968d6SJason Wang 
3467333f7909SAl Viro 	init_waitqueue_head(&tfile->socket.wq.wait);
346854f968d6SJason Wang 
346954f968d6SJason Wang 	tfile->socket.file = file;
347054f968d6SJason Wang 	tfile->socket.ops = &tun_socket_ops;
347154f968d6SJason Wang 
3472*9bc30473SLaszlo Ersek 	sock_init_data_uid(&tfile->socket, &tfile->sk, current_fsuid());
347354f968d6SJason Wang 
347454f968d6SJason Wang 	tfile->sk.sk_write_space = tun_sock_write_space;
347554f968d6SJason Wang 	tfile->sk.sk_sndbuf = INT_MAX;
347654f968d6SJason Wang 
3477631ab46bSEric W. Biederman 	file->private_data = tfile;
34784008e97fSJason Wang 	INIT_LIST_HEAD(&tfile->next);
347954f968d6SJason Wang 
348019a6afb2SJason Wang 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
348119a6afb2SJason Wang 
3482438b4060SJens Axboe 	/* tun groks IOCB_NOWAIT just fine, mark it as such */
3483438b4060SJens Axboe 	file->f_mode |= FMODE_NOWAIT;
34841da177e4SLinus Torvalds 	return 0;
34851da177e4SLinus Torvalds }
34861da177e4SLinus Torvalds 
34871da177e4SLinus Torvalds static int tun_chr_close(struct inode *inode, struct file *file)
34881da177e4SLinus Torvalds {
3489631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
34901da177e4SLinus Torvalds 
3491c8d68e6bSJason Wang 	tun_detach(tfile, true);
34921da177e4SLinus Torvalds 
34931da177e4SLinus Torvalds 	return 0;
34941da177e4SLinus Torvalds }
34951da177e4SLinus Torvalds 
349693e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
34979484dc74Syuan linyu static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
349893e14b6dSMasatake YAMATO {
34999484dc74Syuan linyu 	struct tun_file *tfile = file->private_data;
350093e14b6dSMasatake YAMATO 	struct tun_struct *tun;
350193e14b6dSMasatake YAMATO 	struct ifreq ifr;
350293e14b6dSMasatake YAMATO 
350393e14b6dSMasatake YAMATO 	memset(&ifr, 0, sizeof(ifr));
350493e14b6dSMasatake YAMATO 
350593e14b6dSMasatake YAMATO 	rtnl_lock();
35069484dc74Syuan linyu 	tun = tun_get(tfile);
350793e14b6dSMasatake YAMATO 	if (tun)
350812132768SKirill Tkhai 		tun_get_iff(tun, &ifr);
350993e14b6dSMasatake YAMATO 	rtnl_unlock();
351093e14b6dSMasatake YAMATO 
351193e14b6dSMasatake YAMATO 	if (tun)
351293e14b6dSMasatake YAMATO 		tun_put(tun);
351393e14b6dSMasatake YAMATO 
3514a3816ab0SJoe Perches 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
351593e14b6dSMasatake YAMATO }
351693e14b6dSMasatake YAMATO #endif
351793e14b6dSMasatake YAMATO 
3518d54b1fdbSArjan van de Ven static const struct file_operations tun_fops = {
35191da177e4SLinus Torvalds 	.owner	= THIS_MODULE,
35201da177e4SLinus Torvalds 	.llseek = no_llseek,
35219b067034SAl Viro 	.read_iter  = tun_chr_read_iter,
3522f5ff53b4SAl Viro 	.write_iter = tun_chr_write_iter,
35231da177e4SLinus Torvalds 	.poll	= tun_chr_poll,
3524876bfd4dSHerbert Xu 	.unlocked_ioctl	= tun_chr_ioctl,
352550857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
352650857e2aSArnd Bergmann 	.compat_ioctl = tun_chr_compat_ioctl,
352750857e2aSArnd Bergmann #endif
35281da177e4SLinus Torvalds 	.open	= tun_chr_open,
35291da177e4SLinus Torvalds 	.release = tun_chr_close,
353093e14b6dSMasatake YAMATO 	.fasync = tun_chr_fasync,
353193e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
353293e14b6dSMasatake YAMATO 	.show_fdinfo = tun_chr_show_fdinfo,
353393e14b6dSMasatake YAMATO #endif
35341da177e4SLinus Torvalds };
35351da177e4SLinus Torvalds 
35361da177e4SLinus Torvalds static struct miscdevice tun_miscdev = {
35371da177e4SLinus Torvalds 	.minor = TUN_MINOR,
35381da177e4SLinus Torvalds 	.name = "tun",
3539e454cea2SKay Sievers 	.nodename = "net/tun",
35401da177e4SLinus Torvalds 	.fops = &tun_fops,
35411da177e4SLinus Torvalds };
35421da177e4SLinus Torvalds 
35431da177e4SLinus Torvalds /* ethtool interface */
35441da177e4SLinus Torvalds 
35454e24f2ddSChas Williams static void tun_default_link_ksettings(struct net_device *dev,
354629ccc49dSPhilippe Reynes 				       struct ethtool_link_ksettings *cmd)
35471da177e4SLinus Torvalds {
354829ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
354929ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
3550598d2982SIlya Maximets 	cmd->base.speed		= SPEED_10000;
355129ccc49dSPhilippe Reynes 	cmd->base.duplex	= DUPLEX_FULL;
355229ccc49dSPhilippe Reynes 	cmd->base.port		= PORT_TP;
355329ccc49dSPhilippe Reynes 	cmd->base.phy_address	= 0;
355429ccc49dSPhilippe Reynes 	cmd->base.autoneg	= AUTONEG_DISABLE;
35554e24f2ddSChas Williams }
35564e24f2ddSChas Williams 
35574e24f2ddSChas Williams static int tun_get_link_ksettings(struct net_device *dev,
35584e24f2ddSChas Williams 				  struct ethtool_link_ksettings *cmd)
35594e24f2ddSChas Williams {
35604e24f2ddSChas Williams 	struct tun_struct *tun = netdev_priv(dev);
35614e24f2ddSChas Williams 
35624e24f2ddSChas Williams 	memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
35634e24f2ddSChas Williams 	return 0;
35644e24f2ddSChas Williams }
35654e24f2ddSChas Williams 
35664e24f2ddSChas Williams static int tun_set_link_ksettings(struct net_device *dev,
35674e24f2ddSChas Williams 				  const struct ethtool_link_ksettings *cmd)
35684e24f2ddSChas Williams {
35694e24f2ddSChas Williams 	struct tun_struct *tun = netdev_priv(dev);
35704e24f2ddSChas Williams 
35714e24f2ddSChas Williams 	memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
35721da177e4SLinus Torvalds 	return 0;
35731da177e4SLinus Torvalds }
35741da177e4SLinus Torvalds 
35751da177e4SLinus Torvalds static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
35761da177e4SLinus Torvalds {
35771da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
35781da177e4SLinus Torvalds 
3579fb3ceec1SWolfram Sang 	strscpy(info->driver, DRV_NAME, sizeof(info->driver));
3580fb3ceec1SWolfram Sang 	strscpy(info->version, DRV_VERSION, sizeof(info->version));
35811da177e4SLinus Torvalds 
35821da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
358340630b82SMichael S. Tsirkin 	case IFF_TUN:
3584fb3ceec1SWolfram Sang 		strscpy(info->bus_info, "tun", sizeof(info->bus_info));
35851da177e4SLinus Torvalds 		break;
358640630b82SMichael S. Tsirkin 	case IFF_TAP:
3587fb3ceec1SWolfram Sang 		strscpy(info->bus_info, "tap", sizeof(info->bus_info));
35881da177e4SLinus Torvalds 		break;
35891da177e4SLinus Torvalds 	}
35901da177e4SLinus Torvalds }
35911da177e4SLinus Torvalds 
35921da177e4SLinus Torvalds static u32 tun_get_msglevel(struct net_device *dev)
35931da177e4SLinus Torvalds {
35941da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
35953424170fSMichal Kubecek 
35963424170fSMichal Kubecek 	return tun->msg_enable;
35971da177e4SLinus Torvalds }
35981da177e4SLinus Torvalds 
35991da177e4SLinus Torvalds static void tun_set_msglevel(struct net_device *dev, u32 value)
36001da177e4SLinus Torvalds {
36011da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
36023424170fSMichal Kubecek 
36033424170fSMichal Kubecek 	tun->msg_enable = value;
36041da177e4SLinus Torvalds }
36051da177e4SLinus Torvalds 
36065503fcecSJason Wang static int tun_get_coalesce(struct net_device *dev,
3607f3ccfda1SYufeng Mo 			    struct ethtool_coalesce *ec,
3608f3ccfda1SYufeng Mo 			    struct kernel_ethtool_coalesce *kernel_coal,
3609f3ccfda1SYufeng Mo 			    struct netlink_ext_ack *extack)
36105503fcecSJason Wang {
36115503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
36125503fcecSJason Wang 
36135503fcecSJason Wang 	ec->rx_max_coalesced_frames = tun->rx_batched;
36145503fcecSJason Wang 
36155503fcecSJason Wang 	return 0;
36165503fcecSJason Wang }
36175503fcecSJason Wang 
36185503fcecSJason Wang static int tun_set_coalesce(struct net_device *dev,
3619f3ccfda1SYufeng Mo 			    struct ethtool_coalesce *ec,
3620f3ccfda1SYufeng Mo 			    struct kernel_ethtool_coalesce *kernel_coal,
3621f3ccfda1SYufeng Mo 			    struct netlink_ext_ack *extack)
36225503fcecSJason Wang {
36235503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
36245503fcecSJason Wang 
36255503fcecSJason Wang 	if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
36265503fcecSJason Wang 		tun->rx_batched = NAPI_POLL_WEIGHT;
36275503fcecSJason Wang 	else
36285503fcecSJason Wang 		tun->rx_batched = ec->rx_max_coalesced_frames;
36295503fcecSJason Wang 
36305503fcecSJason Wang 	return 0;
36315503fcecSJason Wang }
36325503fcecSJason Wang 
36337282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops = {
3634e5ad00b3SJakub Kicinski 	.supported_coalesce_params = ETHTOOL_COALESCE_RX_MAX_FRAMES,
36351da177e4SLinus Torvalds 	.get_drvinfo	= tun_get_drvinfo,
36361da177e4SLinus Torvalds 	.get_msglevel	= tun_get_msglevel,
36371da177e4SLinus Torvalds 	.set_msglevel	= tun_set_msglevel,
3638bee31369SNolan Leake 	.get_link	= ethtool_op_get_link,
3639eda29772SRichard Cochran 	.get_ts_info	= ethtool_op_get_ts_info,
36405503fcecSJason Wang 	.get_coalesce   = tun_get_coalesce,
36415503fcecSJason Wang 	.set_coalesce   = tun_set_coalesce,
364229ccc49dSPhilippe Reynes 	.get_link_ksettings = tun_get_link_ksettings,
36434e24f2ddSChas Williams 	.set_link_ksettings = tun_set_link_ksettings,
36441da177e4SLinus Torvalds };
36451da177e4SLinus Torvalds 
36461576d986SJason Wang static int tun_queue_resize(struct tun_struct *tun)
36471576d986SJason Wang {
36481576d986SJason Wang 	struct net_device *dev = tun->dev;
36491576d986SJason Wang 	struct tun_file *tfile;
36505990a305SJason Wang 	struct ptr_ring **rings;
36511576d986SJason Wang 	int n = tun->numqueues + tun->numdisabled;
36521576d986SJason Wang 	int ret, i;
36531576d986SJason Wang 
36545990a305SJason Wang 	rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
36555990a305SJason Wang 	if (!rings)
36561576d986SJason Wang 		return -ENOMEM;
36571576d986SJason Wang 
36581576d986SJason Wang 	for (i = 0; i < tun->numqueues; i++) {
36591576d986SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
36605990a305SJason Wang 		rings[i] = &tfile->tx_ring;
36611576d986SJason Wang 	}
36621576d986SJason Wang 	list_for_each_entry(tfile, &tun->disabled, next)
36635990a305SJason Wang 		rings[i++] = &tfile->tx_ring;
36641576d986SJason Wang 
36655990a305SJason Wang 	ret = ptr_ring_resize_multiple(rings, n,
36665990a305SJason Wang 				       dev->tx_queue_len, GFP_KERNEL,
3667fc72d1d5SJason Wang 				       tun_ptr_free);
36681576d986SJason Wang 
36695990a305SJason Wang 	kfree(rings);
36701576d986SJason Wang 	return ret;
36711576d986SJason Wang }
36721576d986SJason Wang 
36731576d986SJason Wang static int tun_device_event(struct notifier_block *unused,
36741576d986SJason Wang 			    unsigned long event, void *ptr)
36751576d986SJason Wang {
36761576d986SJason Wang 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
36771576d986SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
367872b319dcSFei Li 	int i;
36791576d986SJason Wang 
368086dfb4acSCraig Gallek 	if (dev->rtnl_link_ops != &tun_link_ops)
368186dfb4acSCraig Gallek 		return NOTIFY_DONE;
368286dfb4acSCraig Gallek 
36831576d986SJason Wang 	switch (event) {
36841576d986SJason Wang 	case NETDEV_CHANGE_TX_QUEUE_LEN:
36851576d986SJason Wang 		if (tun_queue_resize(tun))
36861576d986SJason Wang 			return NOTIFY_BAD;
36871576d986SJason Wang 		break;
368872b319dcSFei Li 	case NETDEV_UP:
368972b319dcSFei Li 		for (i = 0; i < tun->numqueues; i++) {
369072b319dcSFei Li 			struct tun_file *tfile;
369172b319dcSFei Li 
369272b319dcSFei Li 			tfile = rtnl_dereference(tun->tfiles[i]);
369372b319dcSFei Li 			tfile->socket.sk->sk_write_space(tfile->socket.sk);
369472b319dcSFei Li 		}
369572b319dcSFei Li 		break;
36961576d986SJason Wang 	default:
36971576d986SJason Wang 		break;
36981576d986SJason Wang 	}
36991576d986SJason Wang 
37001576d986SJason Wang 	return NOTIFY_DONE;
37011576d986SJason Wang }
37021576d986SJason Wang 
37031576d986SJason Wang static struct notifier_block tun_notifier_block __read_mostly = {
37041576d986SJason Wang 	.notifier_call	= tun_device_event,
37051576d986SJason Wang };
370679d17604SPavel Emelyanov 
37071da177e4SLinus Torvalds static int __init tun_init(void)
37081da177e4SLinus Torvalds {
37091da177e4SLinus Torvalds 	int ret = 0;
37101da177e4SLinus Torvalds 
37116b8a66eeSJoe Perches 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
37121da177e4SLinus Torvalds 
3713f019a7a5SEric W. Biederman 	ret = rtnl_link_register(&tun_link_ops);
371479d17604SPavel Emelyanov 	if (ret) {
37156b8a66eeSJoe Perches 		pr_err("Can't register link_ops\n");
3716f019a7a5SEric W. Biederman 		goto err_linkops;
371779d17604SPavel Emelyanov 	}
371879d17604SPavel Emelyanov 
37191da177e4SLinus Torvalds 	ret = misc_register(&tun_miscdev);
372079d17604SPavel Emelyanov 	if (ret) {
37216b8a66eeSJoe Perches 		pr_err("Can't register misc device %d\n", TUN_MINOR);
372279d17604SPavel Emelyanov 		goto err_misc;
372379d17604SPavel Emelyanov 	}
37241576d986SJason Wang 
37255edfbd3cSTonghao Zhang 	ret = register_netdevice_notifier(&tun_notifier_block);
37265edfbd3cSTonghao Zhang 	if (ret) {
37275edfbd3cSTonghao Zhang 		pr_err("Can't register netdevice notifier\n");
37285edfbd3cSTonghao Zhang 		goto err_notifier;
37295edfbd3cSTonghao Zhang 	}
37305edfbd3cSTonghao Zhang 
373179d17604SPavel Emelyanov 	return  0;
37325edfbd3cSTonghao Zhang 
37335edfbd3cSTonghao Zhang err_notifier:
37345edfbd3cSTonghao Zhang 	misc_deregister(&tun_miscdev);
373579d17604SPavel Emelyanov err_misc:
3736f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
3737f019a7a5SEric W. Biederman err_linkops:
37381da177e4SLinus Torvalds 	return ret;
37391da177e4SLinus Torvalds }
37401da177e4SLinus Torvalds 
37411da177e4SLinus Torvalds static void tun_cleanup(void)
37421da177e4SLinus Torvalds {
37431da177e4SLinus Torvalds 	misc_deregister(&tun_miscdev);
3744f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
37451576d986SJason Wang 	unregister_netdevice_notifier(&tun_notifier_block);
37461da177e4SLinus Torvalds }
37471da177e4SLinus Torvalds 
374805c2828cSMichael S. Tsirkin /* Get an underlying socket object from tun file.  Returns error unless file is
374905c2828cSMichael S. Tsirkin  * attached to a device.  The returned object works like a packet socket, it
375005c2828cSMichael S. Tsirkin  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
375105c2828cSMichael S. Tsirkin  * holding a reference to the file for as long as the socket is in use. */
375205c2828cSMichael S. Tsirkin struct socket *tun_get_socket(struct file *file)
375305c2828cSMichael S. Tsirkin {
37546e914fc7SJason Wang 	struct tun_file *tfile;
375505c2828cSMichael S. Tsirkin 	if (file->f_op != &tun_fops)
375605c2828cSMichael S. Tsirkin 		return ERR_PTR(-EINVAL);
37576e914fc7SJason Wang 	tfile = file->private_data;
37586e914fc7SJason Wang 	if (!tfile)
375905c2828cSMichael S. Tsirkin 		return ERR_PTR(-EBADFD);
376054f968d6SJason Wang 	return &tfile->socket;
376105c2828cSMichael S. Tsirkin }
376205c2828cSMichael S. Tsirkin EXPORT_SYMBOL_GPL(tun_get_socket);
376305c2828cSMichael S. Tsirkin 
37645990a305SJason Wang struct ptr_ring *tun_get_tx_ring(struct file *file)
376583339c6bSJason Wang {
376683339c6bSJason Wang 	struct tun_file *tfile;
376783339c6bSJason Wang 
376883339c6bSJason Wang 	if (file->f_op != &tun_fops)
376983339c6bSJason Wang 		return ERR_PTR(-EINVAL);
377083339c6bSJason Wang 	tfile = file->private_data;
377183339c6bSJason Wang 	if (!tfile)
377283339c6bSJason Wang 		return ERR_PTR(-EBADFD);
37735990a305SJason Wang 	return &tfile->tx_ring;
377483339c6bSJason Wang }
37755990a305SJason Wang EXPORT_SYMBOL_GPL(tun_get_tx_ring);
377683339c6bSJason Wang 
37771da177e4SLinus Torvalds module_init(tun_init);
37781da177e4SLinus Torvalds module_exit(tun_cleanup);
37791da177e4SLinus Torvalds MODULE_DESCRIPTION(DRV_DESCRIPTION);
37801da177e4SLinus Torvalds MODULE_AUTHOR(DRV_COPYRIGHT);
37811da177e4SLinus Torvalds MODULE_LICENSE("GPL");
37821da177e4SLinus Torvalds MODULE_ALIAS_MISCDEV(TUN_MINOR);
3783578454ffSKay Sievers MODULE_ALIAS("devname:net/tun");
3784