xref: /openbmc/linux/drivers/net/tun.c (revision 5990a30510ed1c37a769d3a035ad2d030b843528)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  TUN - Universal TUN/TAP device driver.
31da177e4SLinus Torvalds  *  Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  This program is free software; you can redistribute it and/or modify
61da177e4SLinus Torvalds  *  it under the terms of the GNU General Public License as published by
71da177e4SLinus Torvalds  *  the Free Software Foundation; either version 2 of the License, or
81da177e4SLinus Torvalds  *  (at your option) any later version.
91da177e4SLinus Torvalds  *
101da177e4SLinus Torvalds  *  This program is distributed in the hope that it will be useful,
111da177e4SLinus Torvalds  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
121da177e4SLinus Torvalds  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
131da177e4SLinus Torvalds  *  GNU General Public License for more details.
141da177e4SLinus Torvalds  *
151da177e4SLinus Torvalds  *  $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
161da177e4SLinus Torvalds  */
171da177e4SLinus Torvalds 
181da177e4SLinus Torvalds /*
191da177e4SLinus Torvalds  *  Changes:
201da177e4SLinus Torvalds  *
21ff4cc3acSMike Kershaw  *  Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
22ff4cc3acSMike Kershaw  *    Add TUNSETLINK ioctl to set the link encapsulation
23ff4cc3acSMike Kershaw  *
241da177e4SLinus Torvalds  *  Mark Smith <markzzzsmith@yahoo.com.au>
25344dc8edSJoe Perches  *    Use eth_random_addr() for tap MAC address.
261da177e4SLinus Torvalds  *
271da177e4SLinus Torvalds  *  Harald Roelle <harald.roelle@ifi.lmu.de>  2004/04/20
281da177e4SLinus Torvalds  *    Fixes in packet dropping, queue length setting and queue wakeup.
291da177e4SLinus Torvalds  *    Increased default tx queue length.
301da177e4SLinus Torvalds  *    Added ethtool API.
311da177e4SLinus Torvalds  *    Minor cleanups
321da177e4SLinus Torvalds  *
331da177e4SLinus Torvalds  *  Daniel Podlejski <underley@underley.eu.org>
341da177e4SLinus Torvalds  *    Modifications for 2.3.99-pre5 kernel.
351da177e4SLinus Torvalds  */
361da177e4SLinus Torvalds 
376b8a66eeSJoe Perches #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
386b8a66eeSJoe Perches 
391da177e4SLinus Torvalds #define DRV_NAME	"tun"
401da177e4SLinus Torvalds #define DRV_VERSION	"1.6"
411da177e4SLinus Torvalds #define DRV_DESCRIPTION	"Universal TUN/TAP device driver"
421da177e4SLinus Torvalds #define DRV_COPYRIGHT	"(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
431da177e4SLinus Torvalds 
441da177e4SLinus Torvalds #include <linux/module.h>
451da177e4SLinus Torvalds #include <linux/errno.h>
461da177e4SLinus Torvalds #include <linux/kernel.h>
47174cd4b1SIngo Molnar #include <linux/sched/signal.h>
481da177e4SLinus Torvalds #include <linux/major.h>
491da177e4SLinus Torvalds #include <linux/slab.h>
501da177e4SLinus Torvalds #include <linux/poll.h>
511da177e4SLinus Torvalds #include <linux/fcntl.h>
521da177e4SLinus Torvalds #include <linux/init.h>
531da177e4SLinus Torvalds #include <linux/skbuff.h>
541da177e4SLinus Torvalds #include <linux/netdevice.h>
551da177e4SLinus Torvalds #include <linux/etherdevice.h>
561da177e4SLinus Torvalds #include <linux/miscdevice.h>
571da177e4SLinus Torvalds #include <linux/ethtool.h>
581da177e4SLinus Torvalds #include <linux/rtnetlink.h>
5950857e2aSArnd Bergmann #include <linux/compat.h>
601da177e4SLinus Torvalds #include <linux/if.h>
611da177e4SLinus Torvalds #include <linux/if_arp.h>
621da177e4SLinus Torvalds #include <linux/if_ether.h>
631da177e4SLinus Torvalds #include <linux/if_tun.h>
646680ec68SJason Wang #include <linux/if_vlan.h>
651da177e4SLinus Torvalds #include <linux/crc32.h>
66d647a591SPavel Emelyanov #include <linux/nsproxy.h>
67f43798c2SRusty Russell #include <linux/virtio_net.h>
6899405162SMichael S. Tsirkin #include <linux/rcupdate.h>
69881d966bSEric W. Biederman #include <net/net_namespace.h>
7079d17604SPavel Emelyanov #include <net/netns/generic.h>
71f019a7a5SEric W. Biederman #include <net/rtnetlink.h>
7233dccbb0SHerbert Xu #include <net/sock.h>
7393e14b6dSMasatake YAMATO #include <linux/seq_file.h>
74e0b46d0eSHerbert Xu #include <linux/uio.h>
751576d986SJason Wang #include <linux/skb_array.h>
76761876c8SJason Wang #include <linux/bpf.h>
77761876c8SJason Wang #include <linux/bpf_trace.h>
7890e33d45SPetar Penkov #include <linux/mutex.h>
791da177e4SLinus Torvalds 
807c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
811da177e4SLinus Torvalds 
8214daa021SRusty Russell /* Uncomment to enable debugging */
8314daa021SRusty Russell /* #define TUN_DEBUG 1 */
8414daa021SRusty Russell 
851da177e4SLinus Torvalds #ifdef TUN_DEBUG
861da177e4SLinus Torvalds static int debug;
8714daa021SRusty Russell 
886b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
896b8a66eeSJoe Perches do {								\
906b8a66eeSJoe Perches 	if (tun->debug)						\
916b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
926b8a66eeSJoe Perches } while (0)
936b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
946b8a66eeSJoe Perches do {								\
956b8a66eeSJoe Perches 	if (debug == 2)						\
966b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
976b8a66eeSJoe Perches } while (0)
9814daa021SRusty Russell #else
996b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
1006b8a66eeSJoe Perches do {								\
1016b8a66eeSJoe Perches 	if (0)							\
1026b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
1036b8a66eeSJoe Perches } while (0)
1046b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
1056b8a66eeSJoe Perches do {								\
1066b8a66eeSJoe Perches 	if (0)							\
1076b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
1086b8a66eeSJoe Perches } while (0)
1091da177e4SLinus Torvalds #endif
1101da177e4SLinus Torvalds 
111761876c8SJason Wang #define TUN_HEADROOM 256
1127df13219SJason Wang #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
11366ccbc9cSJason Wang 
114031f5e03SMichael S. Tsirkin /* TUN device flags */
115031f5e03SMichael S. Tsirkin 
116031f5e03SMichael S. Tsirkin /* IFF_ATTACH_QUEUE is never stored in device flags,
117031f5e03SMichael S. Tsirkin  * overload it to mean fasync when stored there.
118031f5e03SMichael S. Tsirkin  */
119031f5e03SMichael S. Tsirkin #define TUN_FASYNC	IFF_ATTACH_QUEUE
1201cf8e410SMichael S. Tsirkin /* High bits in flags field are unused. */
1211cf8e410SMichael S. Tsirkin #define TUN_VNET_LE     0x80000000
1228b8e658bSGreg Kurz #define TUN_VNET_BE     0x40000000
123031f5e03SMichael S. Tsirkin 
124031f5e03SMichael S. Tsirkin #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
12590e33d45SPetar Penkov 		      IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
12690e33d45SPetar Penkov 
1270690899bSMichael S. Tsirkin #define GOODCOPY_LEN 128
1280690899bSMichael S. Tsirkin 
129f271b2ccSMax Krasnyansky #define FLT_EXACT_COUNT 8
130f271b2ccSMax Krasnyansky struct tap_filter {
131f271b2ccSMax Krasnyansky 	unsigned int    count;    /* Number of addrs. Zero means disabled */
132f271b2ccSMax Krasnyansky 	u32             mask[2];  /* Mask of the hashed addrs */
133f271b2ccSMax Krasnyansky 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
134f271b2ccSMax Krasnyansky };
135f271b2ccSMax Krasnyansky 
136baf71c5cSPankaj Gupta /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
137baf71c5cSPankaj Gupta  * to max number of VCPUs in guest. */
138baf71c5cSPankaj Gupta #define MAX_TAP_QUEUES 256
139b8732fb7SJason Wang #define MAX_TAP_FLOWS  4096
140c8d68e6bSJason Wang 
14196442e42SJason Wang #define TUN_FLOW_EXPIRE (3 * HZ)
14296442e42SJason Wang 
143608b9977SPaolo Abeni struct tun_pcpu_stats {
144608b9977SPaolo Abeni 	u64 rx_packets;
145608b9977SPaolo Abeni 	u64 rx_bytes;
146608b9977SPaolo Abeni 	u64 tx_packets;
147608b9977SPaolo Abeni 	u64 tx_bytes;
148608b9977SPaolo Abeni 	struct u64_stats_sync syncp;
149608b9977SPaolo Abeni 	u32 rx_dropped;
150608b9977SPaolo Abeni 	u32 tx_dropped;
151608b9977SPaolo Abeni 	u32 rx_frame_errors;
152608b9977SPaolo Abeni };
153608b9977SPaolo Abeni 
15454f968d6SJason Wang /* A tun_file connects an open character device to a tuntap netdevice. It
15592d4ea6eSstephen hemminger  * also contains all socket related structures (except sock_fprog and tap_filter)
15654f968d6SJason Wang  * to serve as one transmit queue for tuntap device. The sock_fprog and
15754f968d6SJason Wang  * tap_filter were kept in tun_struct since they were used for filtering for the
15836fe8c09SRami Rosen  * netdevice not for a specific queue (at least I didn't see the requirement for
15954f968d6SJason Wang  * this).
1606e914fc7SJason Wang  *
1616e914fc7SJason Wang  * RCU usage:
16236fe8c09SRami Rosen  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
1636e914fc7SJason Wang  * other can only be read while rcu_read_lock or rtnl_lock is held.
16454f968d6SJason Wang  */
165631ab46bSEric W. Biederman struct tun_file {
16654f968d6SJason Wang 	struct sock sk;
16754f968d6SJason Wang 	struct socket socket;
16854f968d6SJason Wang 	struct socket_wq wq;
1696e914fc7SJason Wang 	struct tun_struct __rcu *tun;
17054f968d6SJason Wang 	struct fasync_struct *fasync;
17154f968d6SJason Wang 	/* only used for fasnyc */
17254f968d6SJason Wang 	unsigned int flags;
173fb7589a1SPavel Emelyanov 	union {
174c8d68e6bSJason Wang 		u16 queue_index;
175fb7589a1SPavel Emelyanov 		unsigned int ifindex;
176fb7589a1SPavel Emelyanov 	};
17794317099SPetar Penkov 	struct napi_struct napi;
178aec72f33SEric Dumazet 	bool napi_enabled;
17990e33d45SPetar Penkov 	struct mutex napi_mutex;	/* Protects access to the above napi */
1804008e97fSJason Wang 	struct list_head next;
1814008e97fSJason Wang 	struct tun_struct *detached;
182*5990a305SJason Wang 	struct ptr_ring tx_ring;
1838bf5c4eeSJesper Dangaard Brouer 	struct xdp_rxq_info xdp_rxq;
184631ab46bSEric W. Biederman };
185631ab46bSEric W. Biederman 
18696442e42SJason Wang struct tun_flow_entry {
18796442e42SJason Wang 	struct hlist_node hash_link;
18896442e42SJason Wang 	struct rcu_head rcu;
18996442e42SJason Wang 	struct tun_struct *tun;
19096442e42SJason Wang 
19196442e42SJason Wang 	u32 rxhash;
1929bc88939STom Herbert 	u32 rps_rxhash;
19396442e42SJason Wang 	int queue_index;
19496442e42SJason Wang 	unsigned long updated;
19596442e42SJason Wang };
19696442e42SJason Wang 
19796442e42SJason Wang #define TUN_NUM_FLOW_ENTRIES 1024
19896442e42SJason Wang 
19996f84061SJason Wang struct tun_steering_prog {
20096f84061SJason Wang 	struct rcu_head rcu;
20196f84061SJason Wang 	struct bpf_prog *prog;
20296f84061SJason Wang };
20396f84061SJason Wang 
20454f968d6SJason Wang /* Since the socket were moved to tun_file, to preserve the behavior of persist
20536fe8c09SRami Rosen  * device, socket filter, sndbuf and vnet header size were restore when the
20654f968d6SJason Wang  * file were attached to a persist device.
20754f968d6SJason Wang  */
20814daa021SRusty Russell struct tun_struct {
209c8d68e6bSJason Wang 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
210c8d68e6bSJason Wang 	unsigned int            numqueues;
211f271b2ccSMax Krasnyansky 	unsigned int 		flags;
2120625c883SEric W. Biederman 	kuid_t			owner;
2130625c883SEric W. Biederman 	kgid_t			group;
21414daa021SRusty Russell 
21514daa021SRusty Russell 	struct net_device	*dev;
216c8f44affSMichał Mirosław 	netdev_features_t	set_features;
21788255375SMichał Mirosław #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
218d591a1f3SDavid S. Miller 			  NETIF_F_TSO6)
219d9d52b51SMichael S. Tsirkin 
220eaea34b2SPaolo Abeni 	int			align;
221d9d52b51SMichael S. Tsirkin 	int			vnet_hdr_sz;
22254f968d6SJason Wang 	int			sndbuf;
22354f968d6SJason Wang 	struct tap_filter	txflt;
22454f968d6SJason Wang 	struct sock_fprog	fprog;
22554f968d6SJason Wang 	/* protected by rtnl lock */
22654f968d6SJason Wang 	bool			filter_attached;
22714daa021SRusty Russell #ifdef TUN_DEBUG
22814daa021SRusty Russell 	int debug;
22914daa021SRusty Russell #endif
23096442e42SJason Wang 	spinlock_t lock;
23196442e42SJason Wang 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
23296442e42SJason Wang 	struct timer_list flow_gc_timer;
23396442e42SJason Wang 	unsigned long ageing_time;
2344008e97fSJason Wang 	unsigned int numdisabled;
2354008e97fSJason Wang 	struct list_head disabled;
2365dbbaf2dSPaul Moore 	void *security;
237b8732fb7SJason Wang 	u32 flow_count;
2385503fcecSJason Wang 	u32 rx_batched;
239608b9977SPaolo Abeni 	struct tun_pcpu_stats __percpu *pcpu_stats;
240761876c8SJason Wang 	struct bpf_prog __rcu *xdp_prog;
24196f84061SJason Wang 	struct tun_steering_prog __rcu *steering_prog;
24214daa021SRusty Russell };
24314daa021SRusty Russell 
24494317099SPetar Penkov static int tun_napi_receive(struct napi_struct *napi, int budget)
24594317099SPetar Penkov {
24694317099SPetar Penkov 	struct tun_file *tfile = container_of(napi, struct tun_file, napi);
24794317099SPetar Penkov 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
24894317099SPetar Penkov 	struct sk_buff_head process_queue;
24994317099SPetar Penkov 	struct sk_buff *skb;
25094317099SPetar Penkov 	int received = 0;
25194317099SPetar Penkov 
25294317099SPetar Penkov 	__skb_queue_head_init(&process_queue);
25394317099SPetar Penkov 
25494317099SPetar Penkov 	spin_lock(&queue->lock);
25594317099SPetar Penkov 	skb_queue_splice_tail_init(queue, &process_queue);
25694317099SPetar Penkov 	spin_unlock(&queue->lock);
25794317099SPetar Penkov 
25894317099SPetar Penkov 	while (received < budget && (skb = __skb_dequeue(&process_queue))) {
25994317099SPetar Penkov 		napi_gro_receive(napi, skb);
26094317099SPetar Penkov 		++received;
26194317099SPetar Penkov 	}
26294317099SPetar Penkov 
26394317099SPetar Penkov 	if (!skb_queue_empty(&process_queue)) {
26494317099SPetar Penkov 		spin_lock(&queue->lock);
26594317099SPetar Penkov 		skb_queue_splice(&process_queue, queue);
26694317099SPetar Penkov 		spin_unlock(&queue->lock);
26794317099SPetar Penkov 	}
26894317099SPetar Penkov 
26994317099SPetar Penkov 	return received;
27094317099SPetar Penkov }
27194317099SPetar Penkov 
27294317099SPetar Penkov static int tun_napi_poll(struct napi_struct *napi, int budget)
27394317099SPetar Penkov {
27494317099SPetar Penkov 	unsigned int received;
27594317099SPetar Penkov 
27694317099SPetar Penkov 	received = tun_napi_receive(napi, budget);
27794317099SPetar Penkov 
27894317099SPetar Penkov 	if (received < budget)
27994317099SPetar Penkov 		napi_complete_done(napi, received);
28094317099SPetar Penkov 
28194317099SPetar Penkov 	return received;
28294317099SPetar Penkov }
28394317099SPetar Penkov 
28494317099SPetar Penkov static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
28594317099SPetar Penkov 			  bool napi_en)
28694317099SPetar Penkov {
287aec72f33SEric Dumazet 	tfile->napi_enabled = napi_en;
28894317099SPetar Penkov 	if (napi_en) {
28994317099SPetar Penkov 		netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
29094317099SPetar Penkov 			       NAPI_POLL_WEIGHT);
29194317099SPetar Penkov 		napi_enable(&tfile->napi);
29290e33d45SPetar Penkov 		mutex_init(&tfile->napi_mutex);
29394317099SPetar Penkov 	}
29494317099SPetar Penkov }
29594317099SPetar Penkov 
29694317099SPetar Penkov static void tun_napi_disable(struct tun_struct *tun, struct tun_file *tfile)
29794317099SPetar Penkov {
298aec72f33SEric Dumazet 	if (tfile->napi_enabled)
29994317099SPetar Penkov 		napi_disable(&tfile->napi);
30094317099SPetar Penkov }
30194317099SPetar Penkov 
30294317099SPetar Penkov static void tun_napi_del(struct tun_struct *tun, struct tun_file *tfile)
30394317099SPetar Penkov {
304aec72f33SEric Dumazet 	if (tfile->napi_enabled)
30594317099SPetar Penkov 		netif_napi_del(&tfile->napi);
30694317099SPetar Penkov }
30794317099SPetar Penkov 
30890e33d45SPetar Penkov static bool tun_napi_frags_enabled(const struct tun_struct *tun)
30990e33d45SPetar Penkov {
31090e33d45SPetar Penkov 	return READ_ONCE(tun->flags) & IFF_NAPI_FRAGS;
31190e33d45SPetar Penkov }
31290e33d45SPetar Penkov 
3138b8e658bSGreg Kurz #ifdef CONFIG_TUN_VNET_CROSS_LE
3148b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3158b8e658bSGreg Kurz {
3168b8e658bSGreg Kurz 	return tun->flags & TUN_VNET_BE ? false :
3178b8e658bSGreg Kurz 		virtio_legacy_is_little_endian();
3188b8e658bSGreg Kurz }
3198b8e658bSGreg Kurz 
3208b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3218b8e658bSGreg Kurz {
3228b8e658bSGreg Kurz 	int be = !!(tun->flags & TUN_VNET_BE);
3238b8e658bSGreg Kurz 
3248b8e658bSGreg Kurz 	if (put_user(be, argp))
3258b8e658bSGreg Kurz 		return -EFAULT;
3268b8e658bSGreg Kurz 
3278b8e658bSGreg Kurz 	return 0;
3288b8e658bSGreg Kurz }
3298b8e658bSGreg Kurz 
3308b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3318b8e658bSGreg Kurz {
3328b8e658bSGreg Kurz 	int be;
3338b8e658bSGreg Kurz 
3348b8e658bSGreg Kurz 	if (get_user(be, argp))
3358b8e658bSGreg Kurz 		return -EFAULT;
3368b8e658bSGreg Kurz 
3378b8e658bSGreg Kurz 	if (be)
3388b8e658bSGreg Kurz 		tun->flags |= TUN_VNET_BE;
3398b8e658bSGreg Kurz 	else
3408b8e658bSGreg Kurz 		tun->flags &= ~TUN_VNET_BE;
3418b8e658bSGreg Kurz 
3428b8e658bSGreg Kurz 	return 0;
3438b8e658bSGreg Kurz }
3448b8e658bSGreg Kurz #else
3458b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3468b8e658bSGreg Kurz {
3478b8e658bSGreg Kurz 	return virtio_legacy_is_little_endian();
3488b8e658bSGreg Kurz }
3498b8e658bSGreg Kurz 
3508b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3518b8e658bSGreg Kurz {
3528b8e658bSGreg Kurz 	return -EINVAL;
3538b8e658bSGreg Kurz }
3548b8e658bSGreg Kurz 
3558b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3568b8e658bSGreg Kurz {
3578b8e658bSGreg Kurz 	return -EINVAL;
3588b8e658bSGreg Kurz }
3598b8e658bSGreg Kurz #endif /* CONFIG_TUN_VNET_CROSS_LE */
3608b8e658bSGreg Kurz 
36125bd55bbSGreg Kurz static inline bool tun_is_little_endian(struct tun_struct *tun)
36225bd55bbSGreg Kurz {
3637d824109SGreg Kurz 	return tun->flags & TUN_VNET_LE ||
3648b8e658bSGreg Kurz 		tun_legacy_is_little_endian(tun);
36525bd55bbSGreg Kurz }
36625bd55bbSGreg Kurz 
36756f0dcc5SMichael S. Tsirkin static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
36856f0dcc5SMichael S. Tsirkin {
36925bd55bbSGreg Kurz 	return __virtio16_to_cpu(tun_is_little_endian(tun), val);
37056f0dcc5SMichael S. Tsirkin }
37156f0dcc5SMichael S. Tsirkin 
37256f0dcc5SMichael S. Tsirkin static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
37356f0dcc5SMichael S. Tsirkin {
37425bd55bbSGreg Kurz 	return __cpu_to_virtio16(tun_is_little_endian(tun), val);
37556f0dcc5SMichael S. Tsirkin }
37656f0dcc5SMichael S. Tsirkin 
37796442e42SJason Wang static inline u32 tun_hashfn(u32 rxhash)
37896442e42SJason Wang {
37996442e42SJason Wang 	return rxhash & 0x3ff;
38096442e42SJason Wang }
38196442e42SJason Wang 
38296442e42SJason Wang static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
38396442e42SJason Wang {
38496442e42SJason Wang 	struct tun_flow_entry *e;
38596442e42SJason Wang 
386b67bfe0dSSasha Levin 	hlist_for_each_entry_rcu(e, head, hash_link) {
38796442e42SJason Wang 		if (e->rxhash == rxhash)
38896442e42SJason Wang 			return e;
38996442e42SJason Wang 	}
39096442e42SJason Wang 	return NULL;
39196442e42SJason Wang }
39296442e42SJason Wang 
39396442e42SJason Wang static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
39496442e42SJason Wang 					      struct hlist_head *head,
39596442e42SJason Wang 					      u32 rxhash, u16 queue_index)
39696442e42SJason Wang {
3979fdc6befSEric Dumazet 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
3989fdc6befSEric Dumazet 
39996442e42SJason Wang 	if (e) {
40096442e42SJason Wang 		tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
40196442e42SJason Wang 			  rxhash, queue_index);
40296442e42SJason Wang 		e->updated = jiffies;
40396442e42SJason Wang 		e->rxhash = rxhash;
4049bc88939STom Herbert 		e->rps_rxhash = 0;
40596442e42SJason Wang 		e->queue_index = queue_index;
40696442e42SJason Wang 		e->tun = tun;
40796442e42SJason Wang 		hlist_add_head_rcu(&e->hash_link, head);
408b8732fb7SJason Wang 		++tun->flow_count;
40996442e42SJason Wang 	}
41096442e42SJason Wang 	return e;
41196442e42SJason Wang }
41296442e42SJason Wang 
41396442e42SJason Wang static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
41496442e42SJason Wang {
41596442e42SJason Wang 	tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
41696442e42SJason Wang 		  e->rxhash, e->queue_index);
41796442e42SJason Wang 	hlist_del_rcu(&e->hash_link);
4189fdc6befSEric Dumazet 	kfree_rcu(e, rcu);
419b8732fb7SJason Wang 	--tun->flow_count;
42096442e42SJason Wang }
42196442e42SJason Wang 
42296442e42SJason Wang static void tun_flow_flush(struct tun_struct *tun)
42396442e42SJason Wang {
42496442e42SJason Wang 	int i;
42596442e42SJason Wang 
42696442e42SJason Wang 	spin_lock_bh(&tun->lock);
42796442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
42896442e42SJason Wang 		struct tun_flow_entry *e;
429b67bfe0dSSasha Levin 		struct hlist_node *n;
43096442e42SJason Wang 
431b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
43296442e42SJason Wang 			tun_flow_delete(tun, e);
43396442e42SJason Wang 	}
43496442e42SJason Wang 	spin_unlock_bh(&tun->lock);
43596442e42SJason Wang }
43696442e42SJason Wang 
43796442e42SJason Wang static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
43896442e42SJason Wang {
43996442e42SJason Wang 	int i;
44096442e42SJason Wang 
44196442e42SJason Wang 	spin_lock_bh(&tun->lock);
44296442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
44396442e42SJason Wang 		struct tun_flow_entry *e;
444b67bfe0dSSasha Levin 		struct hlist_node *n;
44596442e42SJason Wang 
446b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
44796442e42SJason Wang 			if (e->queue_index == queue_index)
44896442e42SJason Wang 				tun_flow_delete(tun, e);
44996442e42SJason Wang 		}
45096442e42SJason Wang 	}
45196442e42SJason Wang 	spin_unlock_bh(&tun->lock);
45296442e42SJason Wang }
45396442e42SJason Wang 
454e99e88a9SKees Cook static void tun_flow_cleanup(struct timer_list *t)
45596442e42SJason Wang {
456e99e88a9SKees Cook 	struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
45796442e42SJason Wang 	unsigned long delay = tun->ageing_time;
45896442e42SJason Wang 	unsigned long next_timer = jiffies + delay;
45996442e42SJason Wang 	unsigned long count = 0;
46096442e42SJason Wang 	int i;
46196442e42SJason Wang 
46296442e42SJason Wang 	tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
46396442e42SJason Wang 
4647dbfb4efSEric Dumazet 	spin_lock(&tun->lock);
46596442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
46696442e42SJason Wang 		struct tun_flow_entry *e;
467b67bfe0dSSasha Levin 		struct hlist_node *n;
46896442e42SJason Wang 
469b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
47096442e42SJason Wang 			unsigned long this_timer;
47181d98fa4SEric Dumazet 
47296442e42SJason Wang 			this_timer = e->updated + delay;
47381d98fa4SEric Dumazet 			if (time_before_eq(this_timer, jiffies)) {
47496442e42SJason Wang 				tun_flow_delete(tun, e);
47581d98fa4SEric Dumazet 				continue;
47681d98fa4SEric Dumazet 			}
47781d98fa4SEric Dumazet 			count++;
47881d98fa4SEric Dumazet 			if (time_before(this_timer, next_timer))
47996442e42SJason Wang 				next_timer = this_timer;
48096442e42SJason Wang 		}
48196442e42SJason Wang 	}
48296442e42SJason Wang 
48396442e42SJason Wang 	if (count)
48496442e42SJason Wang 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
4857dbfb4efSEric Dumazet 	spin_unlock(&tun->lock);
48696442e42SJason Wang }
48796442e42SJason Wang 
48849974420SEric Dumazet static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
4899e85722dSJason Wang 			    struct tun_file *tfile)
49096442e42SJason Wang {
49196442e42SJason Wang 	struct hlist_head *head;
49296442e42SJason Wang 	struct tun_flow_entry *e;
49396442e42SJason Wang 	unsigned long delay = tun->ageing_time;
4949e85722dSJason Wang 	u16 queue_index = tfile->queue_index;
49596442e42SJason Wang 
49696442e42SJason Wang 	if (!rxhash)
49796442e42SJason Wang 		return;
49896442e42SJason Wang 	else
49996442e42SJason Wang 		head = &tun->flows[tun_hashfn(rxhash)];
50096442e42SJason Wang 
50196442e42SJason Wang 	rcu_read_lock();
50296442e42SJason Wang 
5039e85722dSJason Wang 	/* We may get a very small possibility of OOO during switching, not
5049e85722dSJason Wang 	 * worth to optimize.*/
5059e85722dSJason Wang 	if (tun->numqueues == 1 || tfile->detached)
50696442e42SJason Wang 		goto unlock;
50796442e42SJason Wang 
50896442e42SJason Wang 	e = tun_flow_find(head, rxhash);
50996442e42SJason Wang 	if (likely(e)) {
51096442e42SJason Wang 		/* TODO: keep queueing to old queue until it's empty? */
51196442e42SJason Wang 		e->queue_index = queue_index;
51296442e42SJason Wang 		e->updated = jiffies;
5139bc88939STom Herbert 		sock_rps_record_flow_hash(e->rps_rxhash);
51496442e42SJason Wang 	} else {
51596442e42SJason Wang 		spin_lock_bh(&tun->lock);
516b8732fb7SJason Wang 		if (!tun_flow_find(head, rxhash) &&
517b8732fb7SJason Wang 		    tun->flow_count < MAX_TAP_FLOWS)
51896442e42SJason Wang 			tun_flow_create(tun, head, rxhash, queue_index);
51996442e42SJason Wang 
52096442e42SJason Wang 		if (!timer_pending(&tun->flow_gc_timer))
52196442e42SJason Wang 			mod_timer(&tun->flow_gc_timer,
52296442e42SJason Wang 				  round_jiffies_up(jiffies + delay));
52396442e42SJason Wang 		spin_unlock_bh(&tun->lock);
52496442e42SJason Wang 	}
52596442e42SJason Wang 
52696442e42SJason Wang unlock:
52796442e42SJason Wang 	rcu_read_unlock();
52896442e42SJason Wang }
52996442e42SJason Wang 
5309bc88939STom Herbert /**
5319bc88939STom Herbert  * Save the hash received in the stack receive path and update the
5329bc88939STom Herbert  * flow_hash table accordingly.
5339bc88939STom Herbert  */
5349bc88939STom Herbert static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
5359bc88939STom Herbert {
536567e4b79SEric Dumazet 	if (unlikely(e->rps_rxhash != hash))
5379bc88939STom Herbert 		e->rps_rxhash = hash;
5389bc88939STom Herbert }
5399bc88939STom Herbert 
540c8d68e6bSJason Wang /* We try to identify a flow through its rxhash first. The reason that
54192d4ea6eSstephen hemminger  * we do not check rxq no. is because some cards(e.g 82599), chooses
542c8d68e6bSJason Wang  * the rxq based on the txq where the last packet of the flow comes. As
543c8d68e6bSJason Wang  * the userspace application move between processors, we may get a
544c8d68e6bSJason Wang  * different rxq no. here. If we could not get rxhash, then we would
545c8d68e6bSJason Wang  * hope the rxq no. may help here.
546c8d68e6bSJason Wang  */
54796f84061SJason Wang static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
548c8d68e6bSJason Wang {
54996442e42SJason Wang 	struct tun_flow_entry *e;
550c8d68e6bSJason Wang 	u32 txq = 0;
551c8d68e6bSJason Wang 	u32 numqueues = 0;
552c8d68e6bSJason Wang 
5536aa7de05SMark Rutland 	numqueues = READ_ONCE(tun->numqueues);
554c8d68e6bSJason Wang 
555feec084aSJason Wang 	txq = __skb_get_hash_symmetric(skb);
556c8d68e6bSJason Wang 	if (txq) {
55796442e42SJason Wang 		e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
5589bc88939STom Herbert 		if (e) {
5599bc88939STom Herbert 			tun_flow_save_rps_rxhash(e, txq);
560fbe4d456SZhi Yong Wu 			txq = e->queue_index;
5619bc88939STom Herbert 		} else
562c8d68e6bSJason Wang 			/* use multiply and shift instead of expensive divide */
563c8d68e6bSJason Wang 			txq = ((u64)txq * numqueues) >> 32;
564c8d68e6bSJason Wang 	} else if (likely(skb_rx_queue_recorded(skb))) {
565c8d68e6bSJason Wang 		txq = skb_get_rx_queue(skb);
566c8d68e6bSJason Wang 		while (unlikely(txq >= numqueues))
567c8d68e6bSJason Wang 			txq -= numqueues;
568c8d68e6bSJason Wang 	}
569c8d68e6bSJason Wang 
570c8d68e6bSJason Wang 	return txq;
571c8d68e6bSJason Wang }
572c8d68e6bSJason Wang 
57396f84061SJason Wang static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
57496f84061SJason Wang {
57596f84061SJason Wang 	struct tun_steering_prog *prog;
57696f84061SJason Wang 	u16 ret = 0;
57796f84061SJason Wang 
57896f84061SJason Wang 	prog = rcu_dereference(tun->steering_prog);
57996f84061SJason Wang 	if (prog)
58096f84061SJason Wang 		ret = bpf_prog_run_clear_cb(prog->prog, skb);
58196f84061SJason Wang 
58296f84061SJason Wang 	return ret % tun->numqueues;
58396f84061SJason Wang }
58496f84061SJason Wang 
58596f84061SJason Wang static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
58696f84061SJason Wang 			    void *accel_priv, select_queue_fallback_t fallback)
58796f84061SJason Wang {
58896f84061SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
58996f84061SJason Wang 	u16 ret;
59096f84061SJason Wang 
59196f84061SJason Wang 	rcu_read_lock();
59296f84061SJason Wang 	if (rcu_dereference(tun->steering_prog))
59396f84061SJason Wang 		ret = tun_ebpf_select_queue(tun, skb);
59496f84061SJason Wang 	else
59596f84061SJason Wang 		ret = tun_automq_select_queue(tun, skb);
59696f84061SJason Wang 	rcu_read_unlock();
59796f84061SJason Wang 
59896f84061SJason Wang 	return ret;
59996f84061SJason Wang }
60096f84061SJason Wang 
601cde8b15fSJason Wang static inline bool tun_not_capable(struct tun_struct *tun)
602cde8b15fSJason Wang {
603cde8b15fSJason Wang 	const struct cred *cred = current_cred();
604c260b772SEric W. Biederman 	struct net *net = dev_net(tun->dev);
605cde8b15fSJason Wang 
606cde8b15fSJason Wang 	return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
607cde8b15fSJason Wang 		  (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
608c260b772SEric W. Biederman 		!ns_capable(net->user_ns, CAP_NET_ADMIN);
609cde8b15fSJason Wang }
610cde8b15fSJason Wang 
611c8d68e6bSJason Wang static void tun_set_real_num_queues(struct tun_struct *tun)
612c8d68e6bSJason Wang {
613c8d68e6bSJason Wang 	netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
614c8d68e6bSJason Wang 	netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
615c8d68e6bSJason Wang }
616c8d68e6bSJason Wang 
6174008e97fSJason Wang static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
6184008e97fSJason Wang {
6194008e97fSJason Wang 	tfile->detached = tun;
6204008e97fSJason Wang 	list_add_tail(&tfile->next, &tun->disabled);
6214008e97fSJason Wang 	++tun->numdisabled;
6224008e97fSJason Wang }
6234008e97fSJason Wang 
624d32649d1SJason Wang static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
6254008e97fSJason Wang {
6264008e97fSJason Wang 	struct tun_struct *tun = tfile->detached;
6274008e97fSJason Wang 
6284008e97fSJason Wang 	tfile->detached = NULL;
6294008e97fSJason Wang 	list_del_init(&tfile->next);
6304008e97fSJason Wang 	--tun->numdisabled;
6314008e97fSJason Wang 	return tun;
6324008e97fSJason Wang }
6334008e97fSJason Wang 
6344bfb0513SJason Wang static void tun_queue_purge(struct tun_file *tfile)
6354bfb0513SJason Wang {
6361576d986SJason Wang 	struct sk_buff *skb;
6371576d986SJason Wang 
638*5990a305SJason Wang 	while ((skb = ptr_ring_consume(&tfile->tx_ring)) != NULL)
6391576d986SJason Wang 		kfree_skb(skb);
6401576d986SJason Wang 
6415503fcecSJason Wang 	skb_queue_purge(&tfile->sk.sk_write_queue);
6424bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_error_queue);
6434bfb0513SJason Wang }
6444bfb0513SJason Wang 
645c8d68e6bSJason Wang static void __tun_detach(struct tun_file *tfile, bool clean)
646c8d68e6bSJason Wang {
647c8d68e6bSJason Wang 	struct tun_file *ntfile;
648c8d68e6bSJason Wang 	struct tun_struct *tun;
649c8d68e6bSJason Wang 
650b8deabd3SJason Wang 	tun = rtnl_dereference(tfile->tun);
651b8deabd3SJason Wang 
65294317099SPetar Penkov 	if (tun && clean) {
65394317099SPetar Penkov 		tun_napi_disable(tun, tfile);
65494317099SPetar Penkov 		tun_napi_del(tun, tfile);
65594317099SPetar Penkov 	}
65694317099SPetar Penkov 
6579e85722dSJason Wang 	if (tun && !tfile->detached) {
658c8d68e6bSJason Wang 		u16 index = tfile->queue_index;
659c8d68e6bSJason Wang 		BUG_ON(index >= tun->numqueues);
660c8d68e6bSJason Wang 
661c8d68e6bSJason Wang 		rcu_assign_pointer(tun->tfiles[index],
662c8d68e6bSJason Wang 				   tun->tfiles[tun->numqueues - 1]);
663b8deabd3SJason Wang 		ntfile = rtnl_dereference(tun->tfiles[index]);
664c8d68e6bSJason Wang 		ntfile->queue_index = index;
665c8d68e6bSJason Wang 
666c8d68e6bSJason Wang 		--tun->numqueues;
6679e85722dSJason Wang 		if (clean) {
668c956674bSMonam Agarwal 			RCU_INIT_POINTER(tfile->tun, NULL);
669c8d68e6bSJason Wang 			sock_put(&tfile->sk);
6709e85722dSJason Wang 		} else
6714008e97fSJason Wang 			tun_disable_queue(tun, tfile);
672c8d68e6bSJason Wang 
673c8d68e6bSJason Wang 		synchronize_net();
67496442e42SJason Wang 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
675c8d68e6bSJason Wang 		/* Drop read queue */
6764bfb0513SJason Wang 		tun_queue_purge(tfile);
677c8d68e6bSJason Wang 		tun_set_real_num_queues(tun);
678dd38bd85SJason Wang 	} else if (tfile->detached && clean) {
6794008e97fSJason Wang 		tun = tun_enable_queue(tfile);
680dd38bd85SJason Wang 		sock_put(&tfile->sk);
681dd38bd85SJason Wang 	}
682c8d68e6bSJason Wang 
683c8d68e6bSJason Wang 	if (clean) {
684af668b3cSMichael S. Tsirkin 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
685af668b3cSMichael S. Tsirkin 			netif_carrier_off(tun->dev);
686af668b3cSMichael S. Tsirkin 
68740630b82SMichael S. Tsirkin 			if (!(tun->flags & IFF_PERSIST) &&
688af668b3cSMichael S. Tsirkin 			    tun->dev->reg_state == NETREG_REGISTERED)
6894008e97fSJason Wang 				unregister_netdevice(tun->dev);
690af668b3cSMichael S. Tsirkin 		}
6918bf5c4eeSJesper Dangaard Brouer 		if (tun) {
692*5990a305SJason Wang 			ptr_ring_cleanup(&tfile->tx_ring,
693*5990a305SJason Wang 					 __skb_array_destroy_skb);
6948bf5c4eeSJesper Dangaard Brouer 			xdp_rxq_info_unreg(&tfile->xdp_rxq);
6958bf5c4eeSJesper Dangaard Brouer 		}
696140e807dSEric W. Biederman 		sock_put(&tfile->sk);
697c8d68e6bSJason Wang 	}
698c8d68e6bSJason Wang }
699c8d68e6bSJason Wang 
700c8d68e6bSJason Wang static void tun_detach(struct tun_file *tfile, bool clean)
701c8d68e6bSJason Wang {
702c8d68e6bSJason Wang 	rtnl_lock();
703c8d68e6bSJason Wang 	__tun_detach(tfile, clean);
704c8d68e6bSJason Wang 	rtnl_unlock();
705c8d68e6bSJason Wang }
706c8d68e6bSJason Wang 
707c8d68e6bSJason Wang static void tun_detach_all(struct net_device *dev)
708c8d68e6bSJason Wang {
709c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
7104008e97fSJason Wang 	struct tun_file *tfile, *tmp;
711c8d68e6bSJason Wang 	int i, n = tun->numqueues;
712c8d68e6bSJason Wang 
713c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
714b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
715c8d68e6bSJason Wang 		BUG_ON(!tfile);
71694317099SPetar Penkov 		tun_napi_disable(tun, tfile);
717addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7189e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
719c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
720c8d68e6bSJason Wang 		--tun->numqueues;
721c8d68e6bSJason Wang 	}
7229e85722dSJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
723addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7249e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
725c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
7269e85722dSJason Wang 	}
727c8d68e6bSJason Wang 	BUG_ON(tun->numqueues != 0);
728c8d68e6bSJason Wang 
729c8d68e6bSJason Wang 	synchronize_net();
730c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
731b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
73294317099SPetar Penkov 		tun_napi_del(tun, tfile);
733c8d68e6bSJason Wang 		/* Drop read queue */
7344bfb0513SJason Wang 		tun_queue_purge(tfile);
7358bf5c4eeSJesper Dangaard Brouer 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
736c8d68e6bSJason Wang 		sock_put(&tfile->sk);
737c8d68e6bSJason Wang 	}
7384008e97fSJason Wang 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
7394008e97fSJason Wang 		tun_enable_queue(tfile);
7404bfb0513SJason Wang 		tun_queue_purge(tfile);
7418bf5c4eeSJesper Dangaard Brouer 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
7424008e97fSJason Wang 		sock_put(&tfile->sk);
7434008e97fSJason Wang 	}
7444008e97fSJason Wang 	BUG_ON(tun->numdisabled != 0);
745dd38bd85SJason Wang 
74640630b82SMichael S. Tsirkin 	if (tun->flags & IFF_PERSIST)
747dd38bd85SJason Wang 		module_put(THIS_MODULE);
748c8d68e6bSJason Wang }
749c8d68e6bSJason Wang 
75094317099SPetar Penkov static int tun_attach(struct tun_struct *tun, struct file *file,
75194317099SPetar Penkov 		      bool skip_filter, bool napi)
752a7385ba2SEric W. Biederman {
753631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
7541576d986SJason Wang 	struct net_device *dev = tun->dev;
75538231b7aSEric W. Biederman 	int err;
756a7385ba2SEric W. Biederman 
7575dbbaf2dSPaul Moore 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
7585dbbaf2dSPaul Moore 	if (err < 0)
7595dbbaf2dSPaul Moore 		goto out;
7605dbbaf2dSPaul Moore 
76138231b7aSEric W. Biederman 	err = -EINVAL;
7629e85722dSJason Wang 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
76338231b7aSEric W. Biederman 		goto out;
76438231b7aSEric W. Biederman 
76538231b7aSEric W. Biederman 	err = -EBUSY;
76640630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
767c8d68e6bSJason Wang 		goto out;
768c8d68e6bSJason Wang 
769c8d68e6bSJason Wang 	err = -E2BIG;
7704008e97fSJason Wang 	if (!tfile->detached &&
7714008e97fSJason Wang 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
77238231b7aSEric W. Biederman 		goto out;
77338231b7aSEric W. Biederman 
77438231b7aSEric W. Biederman 	err = 0;
77554f968d6SJason Wang 
77692d4ea6eSstephen hemminger 	/* Re-attach the filter to persist device */
777849c9b6fSPavel Emelyanov 	if (!skip_filter && (tun->filter_attached == true)) {
7788ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
7798ced425eSHannes Frederic Sowa 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
7808ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
78154f968d6SJason Wang 		if (!err)
78254f968d6SJason Wang 			goto out;
78354f968d6SJason Wang 	}
7841576d986SJason Wang 
7851576d986SJason Wang 	if (!tfile->detached &&
786*5990a305SJason Wang 	    ptr_ring_init(&tfile->tx_ring, dev->tx_queue_len, GFP_KERNEL)) {
7871576d986SJason Wang 		err = -ENOMEM;
7881576d986SJason Wang 		goto out;
7891576d986SJason Wang 	}
7901576d986SJason Wang 
791c8d68e6bSJason Wang 	tfile->queue_index = tun->numqueues;
792addf8fc4SJason Wang 	tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
7938bf5c4eeSJesper Dangaard Brouer 
7948bf5c4eeSJesper Dangaard Brouer 	if (tfile->detached) {
7958bf5c4eeSJesper Dangaard Brouer 		/* Re-attach detached tfile, updating XDP queue_index */
7968bf5c4eeSJesper Dangaard Brouer 		WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
7978bf5c4eeSJesper Dangaard Brouer 
7988bf5c4eeSJesper Dangaard Brouer 		if (tfile->xdp_rxq.queue_index    != tfile->queue_index)
7998bf5c4eeSJesper Dangaard Brouer 			tfile->xdp_rxq.queue_index = tfile->queue_index;
8008bf5c4eeSJesper Dangaard Brouer 	} else {
8018bf5c4eeSJesper Dangaard Brouer 		/* Setup XDP RX-queue info, for new tfile getting attached */
8028bf5c4eeSJesper Dangaard Brouer 		err = xdp_rxq_info_reg(&tfile->xdp_rxq,
8038bf5c4eeSJesper Dangaard Brouer 				       tun->dev, tfile->queue_index);
8048bf5c4eeSJesper Dangaard Brouer 		if (err < 0)
8058bf5c4eeSJesper Dangaard Brouer 			goto out;
8068bf5c4eeSJesper Dangaard Brouer 		err = 0;
8078bf5c4eeSJesper Dangaard Brouer 	}
8088bf5c4eeSJesper Dangaard Brouer 
8096e914fc7SJason Wang 	rcu_assign_pointer(tfile->tun, tun);
810c8d68e6bSJason Wang 	rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
811c8d68e6bSJason Wang 	tun->numqueues++;
812c8d68e6bSJason Wang 
81394317099SPetar Penkov 	if (tfile->detached) {
8144008e97fSJason Wang 		tun_enable_queue(tfile);
81594317099SPetar Penkov 	} else {
8164008e97fSJason Wang 		sock_hold(&tfile->sk);
81794317099SPetar Penkov 		tun_napi_init(tun, tfile, napi);
81894317099SPetar Penkov 	}
8194008e97fSJason Wang 
820c8d68e6bSJason Wang 	tun_set_real_num_queues(tun);
821c8d68e6bSJason Wang 
822c8d68e6bSJason Wang 	/* device is allowed to go away first, so no need to hold extra
823c8d68e6bSJason Wang 	 * refcnt.
824c8d68e6bSJason Wang 	 */
825a7385ba2SEric W. Biederman 
82638231b7aSEric W. Biederman out:
82738231b7aSEric W. Biederman 	return err;
828a7385ba2SEric W. Biederman }
829a7385ba2SEric W. Biederman 
8309484dc74Syuan linyu static struct tun_struct *tun_get(struct tun_file *tfile)
831631ab46bSEric W. Biederman {
8326e914fc7SJason Wang 	struct tun_struct *tun;
833c70f1829SEric W. Biederman 
8346e914fc7SJason Wang 	rcu_read_lock();
8356e914fc7SJason Wang 	tun = rcu_dereference(tfile->tun);
8366e914fc7SJason Wang 	if (tun)
8376e914fc7SJason Wang 		dev_hold(tun->dev);
8386e914fc7SJason Wang 	rcu_read_unlock();
839c70f1829SEric W. Biederman 
840c70f1829SEric W. Biederman 	return tun;
841631ab46bSEric W. Biederman }
842631ab46bSEric W. Biederman 
843631ab46bSEric W. Biederman static void tun_put(struct tun_struct *tun)
844631ab46bSEric W. Biederman {
8456e914fc7SJason Wang 	dev_put(tun->dev);
846631ab46bSEric W. Biederman }
847631ab46bSEric W. Biederman 
8486b8a66eeSJoe Perches /* TAP filtering */
849f271b2ccSMax Krasnyansky static void addr_hash_set(u32 *mask, const u8 *addr)
850f271b2ccSMax Krasnyansky {
851f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
852f271b2ccSMax Krasnyansky 	mask[n >> 5] |= (1 << (n & 31));
853f271b2ccSMax Krasnyansky }
854f271b2ccSMax Krasnyansky 
855f271b2ccSMax Krasnyansky static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
856f271b2ccSMax Krasnyansky {
857f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
858f271b2ccSMax Krasnyansky 	return mask[n >> 5] & (1 << (n & 31));
859f271b2ccSMax Krasnyansky }
860f271b2ccSMax Krasnyansky 
861f271b2ccSMax Krasnyansky static int update_filter(struct tap_filter *filter, void __user *arg)
862f271b2ccSMax Krasnyansky {
863f271b2ccSMax Krasnyansky 	struct { u8 u[ETH_ALEN]; } *addr;
864f271b2ccSMax Krasnyansky 	struct tun_filter uf;
865f271b2ccSMax Krasnyansky 	int err, alen, n, nexact;
866f271b2ccSMax Krasnyansky 
867f271b2ccSMax Krasnyansky 	if (copy_from_user(&uf, arg, sizeof(uf)))
868f271b2ccSMax Krasnyansky 		return -EFAULT;
869f271b2ccSMax Krasnyansky 
870f271b2ccSMax Krasnyansky 	if (!uf.count) {
871f271b2ccSMax Krasnyansky 		/* Disabled */
872f271b2ccSMax Krasnyansky 		filter->count = 0;
873f271b2ccSMax Krasnyansky 		return 0;
874f271b2ccSMax Krasnyansky 	}
875f271b2ccSMax Krasnyansky 
876f271b2ccSMax Krasnyansky 	alen = ETH_ALEN * uf.count;
87728e8190dSMarkus Elfring 	addr = memdup_user(arg + sizeof(uf), alen);
87828e8190dSMarkus Elfring 	if (IS_ERR(addr))
87928e8190dSMarkus Elfring 		return PTR_ERR(addr);
880f271b2ccSMax Krasnyansky 
881f271b2ccSMax Krasnyansky 	/* The filter is updated without holding any locks. Which is
882f271b2ccSMax Krasnyansky 	 * perfectly safe. We disable it first and in the worst
883f271b2ccSMax Krasnyansky 	 * case we'll accept a few undesired packets. */
884f271b2ccSMax Krasnyansky 	filter->count = 0;
885f271b2ccSMax Krasnyansky 	wmb();
886f271b2ccSMax Krasnyansky 
887f271b2ccSMax Krasnyansky 	/* Use first set of addresses as an exact filter */
888f271b2ccSMax Krasnyansky 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
889f271b2ccSMax Krasnyansky 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
890f271b2ccSMax Krasnyansky 
891f271b2ccSMax Krasnyansky 	nexact = n;
892f271b2ccSMax Krasnyansky 
893cfbf84fcSAlex Williamson 	/* Remaining multicast addresses are hashed,
894cfbf84fcSAlex Williamson 	 * unicast will leave the filter disabled. */
895f271b2ccSMax Krasnyansky 	memset(filter->mask, 0, sizeof(filter->mask));
896cfbf84fcSAlex Williamson 	for (; n < uf.count; n++) {
897cfbf84fcSAlex Williamson 		if (!is_multicast_ether_addr(addr[n].u)) {
898cfbf84fcSAlex Williamson 			err = 0; /* no filter */
8993b8d2a69SMarkus Elfring 			goto free_addr;
900cfbf84fcSAlex Williamson 		}
901f271b2ccSMax Krasnyansky 		addr_hash_set(filter->mask, addr[n].u);
902cfbf84fcSAlex Williamson 	}
903f271b2ccSMax Krasnyansky 
904f271b2ccSMax Krasnyansky 	/* For ALLMULTI just set the mask to all ones.
905f271b2ccSMax Krasnyansky 	 * This overrides the mask populated above. */
906f271b2ccSMax Krasnyansky 	if ((uf.flags & TUN_FLT_ALLMULTI))
907f271b2ccSMax Krasnyansky 		memset(filter->mask, ~0, sizeof(filter->mask));
908f271b2ccSMax Krasnyansky 
909f271b2ccSMax Krasnyansky 	/* Now enable the filter */
910f271b2ccSMax Krasnyansky 	wmb();
911f271b2ccSMax Krasnyansky 	filter->count = nexact;
912f271b2ccSMax Krasnyansky 
913f271b2ccSMax Krasnyansky 	/* Return the number of exact filters */
914f271b2ccSMax Krasnyansky 	err = nexact;
9153b8d2a69SMarkus Elfring free_addr:
916f271b2ccSMax Krasnyansky 	kfree(addr);
917f271b2ccSMax Krasnyansky 	return err;
918f271b2ccSMax Krasnyansky }
919f271b2ccSMax Krasnyansky 
920f271b2ccSMax Krasnyansky /* Returns: 0 - drop, !=0 - accept */
921f271b2ccSMax Krasnyansky static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
922f271b2ccSMax Krasnyansky {
923f271b2ccSMax Krasnyansky 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
924f271b2ccSMax Krasnyansky 	 * at this point. */
925f271b2ccSMax Krasnyansky 	struct ethhdr *eh = (struct ethhdr *) skb->data;
926f271b2ccSMax Krasnyansky 	int i;
927f271b2ccSMax Krasnyansky 
928f271b2ccSMax Krasnyansky 	/* Exact match */
929f271b2ccSMax Krasnyansky 	for (i = 0; i < filter->count; i++)
9302e42e474SJoe Perches 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
931f271b2ccSMax Krasnyansky 			return 1;
932f271b2ccSMax Krasnyansky 
933f271b2ccSMax Krasnyansky 	/* Inexact match (multicast only) */
934f271b2ccSMax Krasnyansky 	if (is_multicast_ether_addr(eh->h_dest))
935f271b2ccSMax Krasnyansky 		return addr_hash_test(filter->mask, eh->h_dest);
936f271b2ccSMax Krasnyansky 
937f271b2ccSMax Krasnyansky 	return 0;
938f271b2ccSMax Krasnyansky }
939f271b2ccSMax Krasnyansky 
940f271b2ccSMax Krasnyansky /*
941f271b2ccSMax Krasnyansky  * Checks whether the packet is accepted or not.
942f271b2ccSMax Krasnyansky  * Returns: 0 - drop, !=0 - accept
943f271b2ccSMax Krasnyansky  */
944f271b2ccSMax Krasnyansky static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
945f271b2ccSMax Krasnyansky {
946f271b2ccSMax Krasnyansky 	if (!filter->count)
947f271b2ccSMax Krasnyansky 		return 1;
948f271b2ccSMax Krasnyansky 
949f271b2ccSMax Krasnyansky 	return run_filter(filter, skb);
950f271b2ccSMax Krasnyansky }
951f271b2ccSMax Krasnyansky 
9521da177e4SLinus Torvalds /* Network device part of the driver */
9531da177e4SLinus Torvalds 
9547282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops;
9551da177e4SLinus Torvalds 
956c70f1829SEric W. Biederman /* Net device detach from fd. */
957c70f1829SEric W. Biederman static void tun_net_uninit(struct net_device *dev)
958c70f1829SEric W. Biederman {
959c8d68e6bSJason Wang 	tun_detach_all(dev);
960c70f1829SEric W. Biederman }
961c70f1829SEric W. Biederman 
9621da177e4SLinus Torvalds /* Net device open. */
9631da177e4SLinus Torvalds static int tun_net_open(struct net_device *dev)
9641da177e4SLinus Torvalds {
965b20e2d54SHannes Frederic Sowa 	struct tun_struct *tun = netdev_priv(dev);
966b20e2d54SHannes Frederic Sowa 	int i;
967b20e2d54SHannes Frederic Sowa 
968c8d68e6bSJason Wang 	netif_tx_start_all_queues(dev);
969b20e2d54SHannes Frederic Sowa 
970b20e2d54SHannes Frederic Sowa 	for (i = 0; i < tun->numqueues; i++) {
971b20e2d54SHannes Frederic Sowa 		struct tun_file *tfile;
972b20e2d54SHannes Frederic Sowa 
973b20e2d54SHannes Frederic Sowa 		tfile = rtnl_dereference(tun->tfiles[i]);
974b20e2d54SHannes Frederic Sowa 		tfile->socket.sk->sk_write_space(tfile->socket.sk);
975b20e2d54SHannes Frederic Sowa 	}
976b20e2d54SHannes Frederic Sowa 
9771da177e4SLinus Torvalds 	return 0;
9781da177e4SLinus Torvalds }
9791da177e4SLinus Torvalds 
9801da177e4SLinus Torvalds /* Net device close. */
9811da177e4SLinus Torvalds static int tun_net_close(struct net_device *dev)
9821da177e4SLinus Torvalds {
983c8d68e6bSJason Wang 	netif_tx_stop_all_queues(dev);
9841da177e4SLinus Torvalds 	return 0;
9851da177e4SLinus Torvalds }
9861da177e4SLinus Torvalds 
9871da177e4SLinus Torvalds /* Net device start xmit */
98896f84061SJason Wang static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
9891da177e4SLinus Torvalds {
9903df97ba8SJason Wang #ifdef CONFIG_RPS
99196f84061SJason Wang 	if (tun->numqueues == 1 && static_key_false(&rps_needed)) {
9929bc88939STom Herbert 		/* Select queue was not called for the skbuff, so we extract the
9939bc88939STom Herbert 		 * RPS hash and save it into the flow_table here.
9949bc88939STom Herbert 		 */
9959bc88939STom Herbert 		__u32 rxhash;
9969bc88939STom Herbert 
997feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
9989bc88939STom Herbert 		if (rxhash) {
9999bc88939STom Herbert 			struct tun_flow_entry *e;
10009bc88939STom Herbert 			e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
10019bc88939STom Herbert 					rxhash);
10029bc88939STom Herbert 			if (e)
10039bc88939STom Herbert 				tun_flow_save_rps_rxhash(e, rxhash);
10049bc88939STom Herbert 		}
10059bc88939STom Herbert 	}
10063df97ba8SJason Wang #endif
100796f84061SJason Wang }
100896f84061SJason Wang 
100996f84061SJason Wang /* Net device start xmit */
101096f84061SJason Wang static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
101196f84061SJason Wang {
101296f84061SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
101396f84061SJason Wang 	int txq = skb->queue_mapping;
101496f84061SJason Wang 	struct tun_file *tfile;
101596f84061SJason Wang 
101696f84061SJason Wang 	rcu_read_lock();
101796f84061SJason Wang 	tfile = rcu_dereference(tun->tfiles[txq]);
101896f84061SJason Wang 
101996f84061SJason Wang 	/* Drop packet if interface is not attached */
1020cc166427SWillem de Bruijn 	if (txq >= tun->numqueues)
102196f84061SJason Wang 		goto drop;
102296f84061SJason Wang 
102396f84061SJason Wang 	if (!rcu_dereference(tun->steering_prog))
102496f84061SJason Wang 		tun_automq_xmit(tun, skb);
10259bc88939STom Herbert 
10266e914fc7SJason Wang 	tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
10276e914fc7SJason Wang 
1028c8d68e6bSJason Wang 	BUG_ON(!tfile);
1029c8d68e6bSJason Wang 
1030f271b2ccSMax Krasnyansky 	/* Drop if the filter does not like it.
1031f271b2ccSMax Krasnyansky 	 * This is a noop if the filter is disabled.
1032f271b2ccSMax Krasnyansky 	 * Filter can be enabled only for the TAP devices. */
1033f271b2ccSMax Krasnyansky 	if (!check_filter(&tun->txflt, skb))
1034f271b2ccSMax Krasnyansky 		goto drop;
1035f271b2ccSMax Krasnyansky 
103654f968d6SJason Wang 	if (tfile->socket.sk->sk_filter &&
103754f968d6SJason Wang 	    sk_filter(tfile->socket.sk, skb))
103899405162SMichael S. Tsirkin 		goto drop;
103999405162SMichael S. Tsirkin 
10401f8b977aSWillem de Bruijn 	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
10417bf66305SJason Wang 		goto drop;
10427bf66305SJason Wang 
10437b996243SSoheil Hassas Yeganeh 	skb_tx_timestamp(skb);
1044eda29772SRichard Cochran 
10450110d6f2SMichael S. Tsirkin 	/* Orphan the skb - required as we might hang on to it
10467bf66305SJason Wang 	 * for indefinite time.
10477bf66305SJason Wang 	 */
10480110d6f2SMichael S. Tsirkin 	skb_orphan(skb);
10490110d6f2SMichael S. Tsirkin 
1050f8af75f3SEric Dumazet 	nf_reset(skb);
1051f8af75f3SEric Dumazet 
1052*5990a305SJason Wang 	if (ptr_ring_produce(&tfile->tx_ring, skb))
10531576d986SJason Wang 		goto drop;
10541da177e4SLinus Torvalds 
10551da177e4SLinus Torvalds 	/* Notify and wake up reader process */
105654f968d6SJason Wang 	if (tfile->flags & TUN_FASYNC)
105754f968d6SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
10589e641bdcSXi Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
10596e914fc7SJason Wang 
10606e914fc7SJason Wang 	rcu_read_unlock();
10616ed10654SPatrick McHardy 	return NETDEV_TX_OK;
10621da177e4SLinus Torvalds 
10631da177e4SLinus Torvalds drop:
1064608b9977SPaolo Abeni 	this_cpu_inc(tun->pcpu_stats->tx_dropped);
1065149d36f7SMichael S. Tsirkin 	skb_tx_error(skb);
10661da177e4SLinus Torvalds 	kfree_skb(skb);
10676e914fc7SJason Wang 	rcu_read_unlock();
1068baeababbSJason Wang 	return NET_XMIT_DROP;
10691da177e4SLinus Torvalds }
10701da177e4SLinus Torvalds 
1071f271b2ccSMax Krasnyansky static void tun_net_mclist(struct net_device *dev)
10721da177e4SLinus Torvalds {
1073f271b2ccSMax Krasnyansky 	/*
1074f271b2ccSMax Krasnyansky 	 * This callback is supposed to deal with mc filter in
1075f271b2ccSMax Krasnyansky 	 * _rx_ path and has nothing to do with the _tx_ path.
1076f271b2ccSMax Krasnyansky 	 * In rx path we always accept everything userspace gives us.
1077f271b2ccSMax Krasnyansky 	 */
10781da177e4SLinus Torvalds }
10791da177e4SLinus Torvalds 
1080c8f44affSMichał Mirosław static netdev_features_t tun_net_fix_features(struct net_device *dev,
1081c8f44affSMichał Mirosław 	netdev_features_t features)
108288255375SMichał Mirosław {
108388255375SMichał Mirosław 	struct tun_struct *tun = netdev_priv(dev);
108488255375SMichał Mirosław 
108588255375SMichał Mirosław 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
108688255375SMichał Mirosław }
1087bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
1088bebd097aSNeil Horman static void tun_poll_controller(struct net_device *dev)
1089bebd097aSNeil Horman {
1090bebd097aSNeil Horman 	/*
1091bebd097aSNeil Horman 	 * Tun only receives frames when:
1092bebd097aSNeil Horman 	 * 1) the char device endpoint gets data from user space
1093bebd097aSNeil Horman 	 * 2) the tun socket gets a sendmsg call from user space
109494317099SPetar Penkov 	 * If NAPI is not enabled, since both of those are synchronous
109594317099SPetar Penkov 	 * operations, we are guaranteed never to have pending data when we poll
109694317099SPetar Penkov 	 * for it so there is nothing to do here but return.
1097bebd097aSNeil Horman 	 * We need this though so netpoll recognizes us as an interface that
1098bebd097aSNeil Horman 	 * supports polling, which enables bridge devices in virt setups to
1099bebd097aSNeil Horman 	 * still use netconsole
110094317099SPetar Penkov 	 * If NAPI is enabled, however, we need to schedule polling for all
110190e33d45SPetar Penkov 	 * queues unless we are using napi_gro_frags(), which we call in
110290e33d45SPetar Penkov 	 * process context and not in NAPI context.
1103bebd097aSNeil Horman 	 */
110494317099SPetar Penkov 	struct tun_struct *tun = netdev_priv(dev);
110594317099SPetar Penkov 
110694317099SPetar Penkov 	if (tun->flags & IFF_NAPI) {
110794317099SPetar Penkov 		struct tun_file *tfile;
110894317099SPetar Penkov 		int i;
110994317099SPetar Penkov 
111090e33d45SPetar Penkov 		if (tun_napi_frags_enabled(tun))
111190e33d45SPetar Penkov 			return;
111290e33d45SPetar Penkov 
111394317099SPetar Penkov 		rcu_read_lock();
111494317099SPetar Penkov 		for (i = 0; i < tun->numqueues; i++) {
111594317099SPetar Penkov 			tfile = rcu_dereference(tun->tfiles[i]);
1116aec72f33SEric Dumazet 			if (tfile->napi_enabled)
111794317099SPetar Penkov 				napi_schedule(&tfile->napi);
111894317099SPetar Penkov 		}
111994317099SPetar Penkov 		rcu_read_unlock();
112094317099SPetar Penkov 	}
1121bebd097aSNeil Horman 	return;
1122bebd097aSNeil Horman }
1123bebd097aSNeil Horman #endif
1124eaea34b2SPaolo Abeni 
1125eaea34b2SPaolo Abeni static void tun_set_headroom(struct net_device *dev, int new_hr)
1126eaea34b2SPaolo Abeni {
1127eaea34b2SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1128eaea34b2SPaolo Abeni 
1129eaea34b2SPaolo Abeni 	if (new_hr < NET_SKB_PAD)
1130eaea34b2SPaolo Abeni 		new_hr = NET_SKB_PAD;
1131eaea34b2SPaolo Abeni 
1132eaea34b2SPaolo Abeni 	tun->align = new_hr;
1133eaea34b2SPaolo Abeni }
1134eaea34b2SPaolo Abeni 
1135bc1f4470Sstephen hemminger static void
1136608b9977SPaolo Abeni tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1137608b9977SPaolo Abeni {
1138608b9977SPaolo Abeni 	u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1139608b9977SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1140608b9977SPaolo Abeni 	struct tun_pcpu_stats *p;
1141608b9977SPaolo Abeni 	int i;
1142608b9977SPaolo Abeni 
1143608b9977SPaolo Abeni 	for_each_possible_cpu(i) {
1144608b9977SPaolo Abeni 		u64 rxpackets, rxbytes, txpackets, txbytes;
1145608b9977SPaolo Abeni 		unsigned int start;
1146608b9977SPaolo Abeni 
1147608b9977SPaolo Abeni 		p = per_cpu_ptr(tun->pcpu_stats, i);
1148608b9977SPaolo Abeni 		do {
1149608b9977SPaolo Abeni 			start = u64_stats_fetch_begin(&p->syncp);
1150608b9977SPaolo Abeni 			rxpackets	= p->rx_packets;
1151608b9977SPaolo Abeni 			rxbytes		= p->rx_bytes;
1152608b9977SPaolo Abeni 			txpackets	= p->tx_packets;
1153608b9977SPaolo Abeni 			txbytes		= p->tx_bytes;
1154608b9977SPaolo Abeni 		} while (u64_stats_fetch_retry(&p->syncp, start));
1155608b9977SPaolo Abeni 
1156608b9977SPaolo Abeni 		stats->rx_packets	+= rxpackets;
1157608b9977SPaolo Abeni 		stats->rx_bytes		+= rxbytes;
1158608b9977SPaolo Abeni 		stats->tx_packets	+= txpackets;
1159608b9977SPaolo Abeni 		stats->tx_bytes		+= txbytes;
1160608b9977SPaolo Abeni 
1161608b9977SPaolo Abeni 		/* u32 counters */
1162608b9977SPaolo Abeni 		rx_dropped	+= p->rx_dropped;
1163608b9977SPaolo Abeni 		rx_frame_errors	+= p->rx_frame_errors;
1164608b9977SPaolo Abeni 		tx_dropped	+= p->tx_dropped;
1165608b9977SPaolo Abeni 	}
1166608b9977SPaolo Abeni 	stats->rx_dropped  = rx_dropped;
1167608b9977SPaolo Abeni 	stats->rx_frame_errors = rx_frame_errors;
1168608b9977SPaolo Abeni 	stats->tx_dropped = tx_dropped;
1169608b9977SPaolo Abeni }
1170608b9977SPaolo Abeni 
1171761876c8SJason Wang static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1172761876c8SJason Wang 		       struct netlink_ext_ack *extack)
1173761876c8SJason Wang {
1174761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1175761876c8SJason Wang 	struct bpf_prog *old_prog;
1176761876c8SJason Wang 
1177761876c8SJason Wang 	old_prog = rtnl_dereference(tun->xdp_prog);
1178761876c8SJason Wang 	rcu_assign_pointer(tun->xdp_prog, prog);
1179761876c8SJason Wang 	if (old_prog)
1180761876c8SJason Wang 		bpf_prog_put(old_prog);
1181761876c8SJason Wang 
1182761876c8SJason Wang 	return 0;
1183761876c8SJason Wang }
1184761876c8SJason Wang 
1185761876c8SJason Wang static u32 tun_xdp_query(struct net_device *dev)
1186761876c8SJason Wang {
1187761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1188761876c8SJason Wang 	const struct bpf_prog *xdp_prog;
1189761876c8SJason Wang 
1190761876c8SJason Wang 	xdp_prog = rtnl_dereference(tun->xdp_prog);
1191761876c8SJason Wang 	if (xdp_prog)
1192761876c8SJason Wang 		return xdp_prog->aux->id;
1193761876c8SJason Wang 
1194761876c8SJason Wang 	return 0;
1195761876c8SJason Wang }
1196761876c8SJason Wang 
1197f4e63525SJakub Kicinski static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1198761876c8SJason Wang {
1199761876c8SJason Wang 	switch (xdp->command) {
1200761876c8SJason Wang 	case XDP_SETUP_PROG:
1201761876c8SJason Wang 		return tun_xdp_set(dev, xdp->prog, xdp->extack);
1202761876c8SJason Wang 	case XDP_QUERY_PROG:
1203761876c8SJason Wang 		xdp->prog_id = tun_xdp_query(dev);
1204761876c8SJason Wang 		xdp->prog_attached = !!xdp->prog_id;
1205761876c8SJason Wang 		return 0;
1206761876c8SJason Wang 	default:
1207761876c8SJason Wang 		return -EINVAL;
1208761876c8SJason Wang 	}
1209761876c8SJason Wang }
1210761876c8SJason Wang 
1211758e43b7SStephen Hemminger static const struct net_device_ops tun_netdev_ops = {
1212c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1213758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1214758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
121500829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
121688255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1217c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
1218bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
1219bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
1220bebd097aSNeil Horman #endif
1221eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1222608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
1223758e43b7SStephen Hemminger };
1224758e43b7SStephen Hemminger 
1225758e43b7SStephen Hemminger static const struct net_device_ops tap_netdev_ops = {
1226c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1227758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1228758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
122900829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
123088255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1231afc4b13dSJiri Pirko 	.ndo_set_rx_mode	= tun_net_mclist,
1232758e43b7SStephen Hemminger 	.ndo_set_mac_address	= eth_mac_addr,
1233758e43b7SStephen Hemminger 	.ndo_validate_addr	= eth_validate_addr,
1234c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
1235bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
1236bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
1237bebd097aSNeil Horman #endif
12385e52796aSToshiaki Makita 	.ndo_features_check	= passthru_features_check,
1239eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1240608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
1241f4e63525SJakub Kicinski 	.ndo_bpf		= tun_xdp,
1242758e43b7SStephen Hemminger };
1243758e43b7SStephen Hemminger 
1244944a1376SPavel Emelyanov static void tun_flow_init(struct tun_struct *tun)
124596442e42SJason Wang {
124696442e42SJason Wang 	int i;
124796442e42SJason Wang 
124896442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
124996442e42SJason Wang 		INIT_HLIST_HEAD(&tun->flows[i]);
125096442e42SJason Wang 
125196442e42SJason Wang 	tun->ageing_time = TUN_FLOW_EXPIRE;
1252e99e88a9SKees Cook 	timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1253e99e88a9SKees Cook 	mod_timer(&tun->flow_gc_timer,
1254e99e88a9SKees Cook 		  round_jiffies_up(jiffies + tun->ageing_time));
125596442e42SJason Wang }
125696442e42SJason Wang 
125796442e42SJason Wang static void tun_flow_uninit(struct tun_struct *tun)
125896442e42SJason Wang {
125996442e42SJason Wang 	del_timer_sync(&tun->flow_gc_timer);
126096442e42SJason Wang 	tun_flow_flush(tun);
126196442e42SJason Wang }
126296442e42SJason Wang 
126391572088SJarod Wilson #define MIN_MTU 68
126491572088SJarod Wilson #define MAX_MTU 65535
126591572088SJarod Wilson 
12661da177e4SLinus Torvalds /* Initialize net device. */
12671da177e4SLinus Torvalds static void tun_net_init(struct net_device *dev)
12681da177e4SLinus Torvalds {
12691da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
12701da177e4SLinus Torvalds 
12711da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
127240630b82SMichael S. Tsirkin 	case IFF_TUN:
1273758e43b7SStephen Hemminger 		dev->netdev_ops = &tun_netdev_ops;
1274758e43b7SStephen Hemminger 
12751da177e4SLinus Torvalds 		/* Point-to-Point TUN Device */
12761da177e4SLinus Torvalds 		dev->hard_header_len = 0;
12771da177e4SLinus Torvalds 		dev->addr_len = 0;
12781da177e4SLinus Torvalds 		dev->mtu = 1500;
12791da177e4SLinus Torvalds 
12801da177e4SLinus Torvalds 		/* Zero header length */
12811da177e4SLinus Torvalds 		dev->type = ARPHRD_NONE;
12821da177e4SLinus Torvalds 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
12831da177e4SLinus Torvalds 		break;
12841da177e4SLinus Torvalds 
128540630b82SMichael S. Tsirkin 	case IFF_TAP:
12867a0a9608SKusanagi Kouichi 		dev->netdev_ops = &tap_netdev_ops;
12871da177e4SLinus Torvalds 		/* Ethernet TAP Device */
12881da177e4SLinus Torvalds 		ether_setup(dev);
1289550fd08cSNeil Horman 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1290a676847bSstephen hemminger 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
129136226a8dSBrian Braunstein 
1292f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
129336226a8dSBrian Braunstein 
12941da177e4SLinus Torvalds 		break;
12951da177e4SLinus Torvalds 	}
129691572088SJarod Wilson 
129791572088SJarod Wilson 	dev->min_mtu = MIN_MTU;
129891572088SJarod Wilson 	dev->max_mtu = MAX_MTU - dev->hard_header_len;
12991da177e4SLinus Torvalds }
13001da177e4SLinus Torvalds 
13011da177e4SLinus Torvalds /* Character device part */
13021da177e4SLinus Torvalds 
13031da177e4SLinus Torvalds /* Poll */
13041da177e4SLinus Torvalds static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
13051da177e4SLinus Torvalds {
1306b2430de3SEric W. Biederman 	struct tun_file *tfile = file->private_data;
13079484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
13083c8a9c63SMariusz Kozlowski 	struct sock *sk;
130933dccbb0SHerbert Xu 	unsigned int mask = 0;
13101da177e4SLinus Torvalds 
13111da177e4SLinus Torvalds 	if (!tun)
1312eac9e902SEric W. Biederman 		return POLLERR;
13131da177e4SLinus Torvalds 
131454f968d6SJason Wang 	sk = tfile->socket.sk;
13153c8a9c63SMariusz Kozlowski 
13166b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
13171da177e4SLinus Torvalds 
13189e641bdcSXi Wang 	poll_wait(file, sk_sleep(sk), wait);
13191da177e4SLinus Torvalds 
1320*5990a305SJason Wang 	if (!ptr_ring_empty(&tfile->tx_ring))
13211da177e4SLinus Torvalds 		mask |= POLLIN | POLLRDNORM;
13221da177e4SLinus Torvalds 
1323b20e2d54SHannes Frederic Sowa 	if (tun->dev->flags & IFF_UP &&
1324b20e2d54SHannes Frederic Sowa 	    (sock_writeable(sk) ||
13259cd3e072SEric Dumazet 	     (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1326b20e2d54SHannes Frederic Sowa 	      sock_writeable(sk))))
132733dccbb0SHerbert Xu 		mask |= POLLOUT | POLLWRNORM;
132833dccbb0SHerbert Xu 
1329c70f1829SEric W. Biederman 	if (tun->dev->reg_state != NETREG_REGISTERED)
1330c70f1829SEric W. Biederman 		mask = POLLERR;
1331c70f1829SEric W. Biederman 
1332631ab46bSEric W. Biederman 	tun_put(tun);
13331da177e4SLinus Torvalds 	return mask;
13341da177e4SLinus Torvalds }
13351da177e4SLinus Torvalds 
133690e33d45SPetar Penkov static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
133790e33d45SPetar Penkov 					    size_t len,
133890e33d45SPetar Penkov 					    const struct iov_iter *it)
133990e33d45SPetar Penkov {
134090e33d45SPetar Penkov 	struct sk_buff *skb;
134190e33d45SPetar Penkov 	size_t linear;
134290e33d45SPetar Penkov 	int err;
134390e33d45SPetar Penkov 	int i;
134490e33d45SPetar Penkov 
134590e33d45SPetar Penkov 	if (it->nr_segs > MAX_SKB_FRAGS + 1)
134690e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
134790e33d45SPetar Penkov 
134890e33d45SPetar Penkov 	local_bh_disable();
134990e33d45SPetar Penkov 	skb = napi_get_frags(&tfile->napi);
135090e33d45SPetar Penkov 	local_bh_enable();
135190e33d45SPetar Penkov 	if (!skb)
135290e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
135390e33d45SPetar Penkov 
135490e33d45SPetar Penkov 	linear = iov_iter_single_seg_count(it);
135590e33d45SPetar Penkov 	err = __skb_grow(skb, linear);
135690e33d45SPetar Penkov 	if (err)
135790e33d45SPetar Penkov 		goto free;
135890e33d45SPetar Penkov 
135990e33d45SPetar Penkov 	skb->len = len;
136090e33d45SPetar Penkov 	skb->data_len = len - linear;
136190e33d45SPetar Penkov 	skb->truesize += skb->data_len;
136290e33d45SPetar Penkov 
136390e33d45SPetar Penkov 	for (i = 1; i < it->nr_segs; i++) {
136490e33d45SPetar Penkov 		size_t fragsz = it->iov[i].iov_len;
136590e33d45SPetar Penkov 		unsigned long offset;
136690e33d45SPetar Penkov 		struct page *page;
136790e33d45SPetar Penkov 		void *data;
136890e33d45SPetar Penkov 
136990e33d45SPetar Penkov 		if (fragsz == 0 || fragsz > PAGE_SIZE) {
137090e33d45SPetar Penkov 			err = -EINVAL;
137190e33d45SPetar Penkov 			goto free;
137290e33d45SPetar Penkov 		}
137390e33d45SPetar Penkov 
137490e33d45SPetar Penkov 		local_bh_disable();
137590e33d45SPetar Penkov 		data = napi_alloc_frag(fragsz);
137690e33d45SPetar Penkov 		local_bh_enable();
137790e33d45SPetar Penkov 		if (!data) {
137890e33d45SPetar Penkov 			err = -ENOMEM;
137990e33d45SPetar Penkov 			goto free;
138090e33d45SPetar Penkov 		}
138190e33d45SPetar Penkov 
138290e33d45SPetar Penkov 		page = virt_to_head_page(data);
138390e33d45SPetar Penkov 		offset = data - page_address(page);
138490e33d45SPetar Penkov 		skb_fill_page_desc(skb, i - 1, page, offset, fragsz);
138590e33d45SPetar Penkov 	}
138690e33d45SPetar Penkov 
138790e33d45SPetar Penkov 	return skb;
138890e33d45SPetar Penkov free:
138990e33d45SPetar Penkov 	/* frees skb and all frags allocated with napi_alloc_frag() */
139090e33d45SPetar Penkov 	napi_free_frags(&tfile->napi);
139190e33d45SPetar Penkov 	return ERR_PTR(err);
139290e33d45SPetar Penkov }
139390e33d45SPetar Penkov 
1394f42157cbSRusty Russell /* prepad is the amount to reserve at front.  len is length after that.
1395f42157cbSRusty Russell  * linear is a hint as to how much to copy (usually headers). */
139654f968d6SJason Wang static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
139733dccbb0SHerbert Xu 				     size_t prepad, size_t len,
139833dccbb0SHerbert Xu 				     size_t linear, int noblock)
1399f42157cbSRusty Russell {
140054f968d6SJason Wang 	struct sock *sk = tfile->socket.sk;
1401f42157cbSRusty Russell 	struct sk_buff *skb;
140233dccbb0SHerbert Xu 	int err;
1403f42157cbSRusty Russell 
1404f42157cbSRusty Russell 	/* Under a page?  Don't bother with paged skb. */
14050eca93bcSHerbert Xu 	if (prepad + len < PAGE_SIZE || !linear)
140633dccbb0SHerbert Xu 		linear = len;
1407f42157cbSRusty Russell 
140833dccbb0SHerbert Xu 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
140928d64271SEric Dumazet 				   &err, 0);
1410f42157cbSRusty Russell 	if (!skb)
141133dccbb0SHerbert Xu 		return ERR_PTR(err);
1412f42157cbSRusty Russell 
1413f42157cbSRusty Russell 	skb_reserve(skb, prepad);
1414f42157cbSRusty Russell 	skb_put(skb, linear);
141533dccbb0SHerbert Xu 	skb->data_len = len - linear;
141633dccbb0SHerbert Xu 	skb->len += len - linear;
1417f42157cbSRusty Russell 
1418f42157cbSRusty Russell 	return skb;
1419f42157cbSRusty Russell }
1420f42157cbSRusty Russell 
14215503fcecSJason Wang static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
14225503fcecSJason Wang 			   struct sk_buff *skb, int more)
14235503fcecSJason Wang {
14245503fcecSJason Wang 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
14255503fcecSJason Wang 	struct sk_buff_head process_queue;
14265503fcecSJason Wang 	u32 rx_batched = tun->rx_batched;
14275503fcecSJason Wang 	bool rcv = false;
14285503fcecSJason Wang 
14295503fcecSJason Wang 	if (!rx_batched || (!more && skb_queue_empty(queue))) {
14305503fcecSJason Wang 		local_bh_disable();
14315503fcecSJason Wang 		netif_receive_skb(skb);
14325503fcecSJason Wang 		local_bh_enable();
14335503fcecSJason Wang 		return;
14345503fcecSJason Wang 	}
14355503fcecSJason Wang 
14365503fcecSJason Wang 	spin_lock(&queue->lock);
14375503fcecSJason Wang 	if (!more || skb_queue_len(queue) == rx_batched) {
14385503fcecSJason Wang 		__skb_queue_head_init(&process_queue);
14395503fcecSJason Wang 		skb_queue_splice_tail_init(queue, &process_queue);
14405503fcecSJason Wang 		rcv = true;
14415503fcecSJason Wang 	} else {
14425503fcecSJason Wang 		__skb_queue_tail(queue, skb);
14435503fcecSJason Wang 	}
14445503fcecSJason Wang 	spin_unlock(&queue->lock);
14455503fcecSJason Wang 
14465503fcecSJason Wang 	if (rcv) {
14475503fcecSJason Wang 		struct sk_buff *nskb;
14485503fcecSJason Wang 
14495503fcecSJason Wang 		local_bh_disable();
14505503fcecSJason Wang 		while ((nskb = __skb_dequeue(&process_queue)))
14515503fcecSJason Wang 			netif_receive_skb(nskb);
14525503fcecSJason Wang 		netif_receive_skb(skb);
14535503fcecSJason Wang 		local_bh_enable();
14545503fcecSJason Wang 	}
14555503fcecSJason Wang }
14565503fcecSJason Wang 
145766ccbc9cSJason Wang static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
145866ccbc9cSJason Wang 			      int len, int noblock, bool zerocopy)
145966ccbc9cSJason Wang {
146066ccbc9cSJason Wang 	if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
146166ccbc9cSJason Wang 		return false;
146266ccbc9cSJason Wang 
146366ccbc9cSJason Wang 	if (tfile->socket.sk->sk_sndbuf != INT_MAX)
146466ccbc9cSJason Wang 		return false;
146566ccbc9cSJason Wang 
146666ccbc9cSJason Wang 	if (!noblock)
146766ccbc9cSJason Wang 		return false;
146866ccbc9cSJason Wang 
146966ccbc9cSJason Wang 	if (zerocopy)
147066ccbc9cSJason Wang 		return false;
147166ccbc9cSJason Wang 
147266ccbc9cSJason Wang 	if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
147366ccbc9cSJason Wang 	    SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
147466ccbc9cSJason Wang 		return false;
147566ccbc9cSJason Wang 
147666ccbc9cSJason Wang 	return true;
147766ccbc9cSJason Wang }
147866ccbc9cSJason Wang 
1479761876c8SJason Wang static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1480761876c8SJason Wang 				     struct tun_file *tfile,
148166ccbc9cSJason Wang 				     struct iov_iter *from,
1482761876c8SJason Wang 				     struct virtio_net_hdr *hdr,
14831cfe6e93SJason Wang 				     int len, int *skb_xdp)
148466ccbc9cSJason Wang {
14850bbd7dadSEric Dumazet 	struct page_frag *alloc_frag = &current->task_frag;
148666ccbc9cSJason Wang 	struct sk_buff *skb;
1487761876c8SJason Wang 	struct bpf_prog *xdp_prog;
14887df13219SJason Wang 	int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1489761876c8SJason Wang 	unsigned int delta = 0;
149066ccbc9cSJason Wang 	char *buf;
149166ccbc9cSJason Wang 	size_t copied;
1492761876c8SJason Wang 	bool xdp_xmit = false;
14937df13219SJason Wang 	int err, pad = TUN_RX_PAD;
14947df13219SJason Wang 
14957df13219SJason Wang 	rcu_read_lock();
14967df13219SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
14977df13219SJason Wang 	if (xdp_prog)
14987df13219SJason Wang 		pad += TUN_HEADROOM;
14997df13219SJason Wang 	buflen += SKB_DATA_ALIGN(len + pad);
15007df13219SJason Wang 	rcu_read_unlock();
150166ccbc9cSJason Wang 
150263b9ab65SJason Wang 	alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
150366ccbc9cSJason Wang 	if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
150466ccbc9cSJason Wang 		return ERR_PTR(-ENOMEM);
150566ccbc9cSJason Wang 
150666ccbc9cSJason Wang 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
150766ccbc9cSJason Wang 	copied = copy_page_from_iter(alloc_frag->page,
15087df13219SJason Wang 				     alloc_frag->offset + pad,
150966ccbc9cSJason Wang 				     len, from);
151066ccbc9cSJason Wang 	if (copied != len)
151166ccbc9cSJason Wang 		return ERR_PTR(-EFAULT);
151266ccbc9cSJason Wang 
15137df13219SJason Wang 	/* There's a small window that XDP may be set after the check
15147df13219SJason Wang 	 * of xdp_prog above, this should be rare and for simplicity
15157df13219SJason Wang 	 * we do XDP on skb in case the headroom is not enough.
15167df13219SJason Wang 	 */
15177df13219SJason Wang 	if (hdr->gso_type || !xdp_prog)
15181cfe6e93SJason Wang 		*skb_xdp = 1;
1519761876c8SJason Wang 	else
15201cfe6e93SJason Wang 		*skb_xdp = 0;
152166ccbc9cSJason Wang 
1522761876c8SJason Wang 	rcu_read_lock();
1523761876c8SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
15241cfe6e93SJason Wang 	if (xdp_prog && !*skb_xdp) {
1525761876c8SJason Wang 		struct xdp_buff xdp;
1526761876c8SJason Wang 		void *orig_data;
1527761876c8SJason Wang 		u32 act;
1528761876c8SJason Wang 
1529761876c8SJason Wang 		xdp.data_hard_start = buf;
15307df13219SJason Wang 		xdp.data = buf + pad;
1531de8f3a83SDaniel Borkmann 		xdp_set_data_meta_invalid(&xdp);
1532761876c8SJason Wang 		xdp.data_end = xdp.data + len;
15338bf5c4eeSJesper Dangaard Brouer 		xdp.rxq = &tfile->xdp_rxq;
1534761876c8SJason Wang 		orig_data = xdp.data;
1535761876c8SJason Wang 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
1536761876c8SJason Wang 
1537761876c8SJason Wang 		switch (act) {
1538761876c8SJason Wang 		case XDP_REDIRECT:
1539761876c8SJason Wang 			get_page(alloc_frag->page);
1540761876c8SJason Wang 			alloc_frag->offset += buflen;
1541761876c8SJason Wang 			err = xdp_do_redirect(tun->dev, &xdp, xdp_prog);
1542761876c8SJason Wang 			if (err)
1543761876c8SJason Wang 				goto err_redirect;
1544654d5738SXin Long 			rcu_read_unlock();
1545761876c8SJason Wang 			return NULL;
1546761876c8SJason Wang 		case XDP_TX:
1547761876c8SJason Wang 			xdp_xmit = true;
1548761876c8SJason Wang 			/* fall through */
1549761876c8SJason Wang 		case XDP_PASS:
1550761876c8SJason Wang 			delta = orig_data - xdp.data;
1551761876c8SJason Wang 			break;
1552761876c8SJason Wang 		default:
1553761876c8SJason Wang 			bpf_warn_invalid_xdp_action(act);
1554761876c8SJason Wang 			/* fall through */
1555761876c8SJason Wang 		case XDP_ABORTED:
1556761876c8SJason Wang 			trace_xdp_exception(tun->dev, xdp_prog, act);
1557761876c8SJason Wang 			/* fall through */
1558761876c8SJason Wang 		case XDP_DROP:
1559761876c8SJason Wang 			goto err_xdp;
1560761876c8SJason Wang 		}
1561761876c8SJason Wang 	}
1562761876c8SJason Wang 
1563761876c8SJason Wang 	skb = build_skb(buf, buflen);
1564761876c8SJason Wang 	if (!skb) {
1565761876c8SJason Wang 		rcu_read_unlock();
1566761876c8SJason Wang 		return ERR_PTR(-ENOMEM);
1567761876c8SJason Wang 	}
1568761876c8SJason Wang 
15697df13219SJason Wang 	skb_reserve(skb, pad - delta);
1570761876c8SJason Wang 	skb_put(skb, len + delta);
157166ccbc9cSJason Wang 	get_page(alloc_frag->page);
157266ccbc9cSJason Wang 	alloc_frag->offset += buflen;
157366ccbc9cSJason Wang 
1574761876c8SJason Wang 	if (xdp_xmit) {
1575761876c8SJason Wang 		skb->dev = tun->dev;
1576761876c8SJason Wang 		generic_xdp_tx(skb, xdp_prog);
1577654d5738SXin Long 		rcu_read_unlock();
1578761876c8SJason Wang 		return NULL;
1579761876c8SJason Wang 	}
1580761876c8SJason Wang 
1581761876c8SJason Wang 	rcu_read_unlock();
1582761876c8SJason Wang 
158366ccbc9cSJason Wang 	return skb;
1584761876c8SJason Wang 
1585761876c8SJason Wang err_redirect:
1586761876c8SJason Wang 	put_page(alloc_frag->page);
1587761876c8SJason Wang err_xdp:
1588761876c8SJason Wang 	rcu_read_unlock();
1589761876c8SJason Wang 	this_cpu_inc(tun->pcpu_stats->rx_dropped);
1590761876c8SJason Wang 	return NULL;
159166ccbc9cSJason Wang }
159266ccbc9cSJason Wang 
15931da177e4SLinus Torvalds /* Get packet from user space buffer */
159454f968d6SJason Wang static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1595f5ff53b4SAl Viro 			    void *msg_control, struct iov_iter *from,
15965503fcecSJason Wang 			    int noblock, bool more)
15971da177e4SLinus Torvalds {
159809640e63SHarvey Harrison 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
15991da177e4SLinus Torvalds 	struct sk_buff *skb;
1600f5ff53b4SAl Viro 	size_t total_len = iov_iter_count(from);
1601eaea34b2SPaolo Abeni 	size_t len = total_len, align = tun->align, linear;
1602f43798c2SRusty Russell 	struct virtio_net_hdr gso = { 0 };
1603608b9977SPaolo Abeni 	struct tun_pcpu_stats *stats;
160496f8d9ecSJason Wang 	int good_linear;
16050690899bSMichael S. Tsirkin 	int copylen;
16060690899bSMichael S. Tsirkin 	bool zerocopy = false;
16070690899bSMichael S. Tsirkin 	int err;
160896f84061SJason Wang 	u32 rxhash = 0;
16091cfe6e93SJason Wang 	int skb_xdp = 1;
161090e33d45SPetar Penkov 	bool frags = tun_napi_frags_enabled(tun);
16111da177e4SLinus Torvalds 
16121bd4978aSEric Dumazet 	if (!(tun->dev->flags & IFF_UP))
16131bd4978aSEric Dumazet 		return -EIO;
16141bd4978aSEric Dumazet 
161540630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
161615718ea0SDan Carpenter 		if (len < sizeof(pi))
16171da177e4SLinus Torvalds 			return -EINVAL;
161815718ea0SDan Carpenter 		len -= sizeof(pi);
16191da177e4SLinus Torvalds 
1620cbbd26b8SAl Viro 		if (!copy_from_iter_full(&pi, sizeof(pi), from))
16211da177e4SLinus Torvalds 			return -EFAULT;
16221da177e4SLinus Torvalds 	}
16231da177e4SLinus Torvalds 
162440630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR) {
1625e1edab87SWillem de Bruijn 		int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1626e1edab87SWillem de Bruijn 
1627e1edab87SWillem de Bruijn 		if (len < vnet_hdr_sz)
1628f43798c2SRusty Russell 			return -EINVAL;
1629e1edab87SWillem de Bruijn 		len -= vnet_hdr_sz;
1630f43798c2SRusty Russell 
1631cbbd26b8SAl Viro 		if (!copy_from_iter_full(&gso, sizeof(gso), from))
1632f43798c2SRusty Russell 			return -EFAULT;
1633f43798c2SRusty Russell 
16344909122fSHerbert Xu 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
163556f0dcc5SMichael S. Tsirkin 		    tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
163656f0dcc5SMichael S. Tsirkin 			gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
16374909122fSHerbert Xu 
163856f0dcc5SMichael S. Tsirkin 		if (tun16_to_cpu(tun, gso.hdr_len) > len)
1639f43798c2SRusty Russell 			return -EINVAL;
1640e1edab87SWillem de Bruijn 		iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1641f43798c2SRusty Russell 	}
1642f43798c2SRusty Russell 
164340630b82SMichael S. Tsirkin 	if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1644a504b86eSstephen hemminger 		align += NET_IP_ALIGN;
16450eca93bcSHerbert Xu 		if (unlikely(len < ETH_HLEN ||
164656f0dcc5SMichael S. Tsirkin 			     (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1647e01bf1c8SRusty Russell 			return -EINVAL;
1648e01bf1c8SRusty Russell 	}
16491da177e4SLinus Torvalds 
165096f8d9ecSJason Wang 	good_linear = SKB_MAX_HEAD(align);
165196f8d9ecSJason Wang 
165288529176SJason Wang 	if (msg_control) {
1653f5ff53b4SAl Viro 		struct iov_iter i = *from;
1654f5ff53b4SAl Viro 
165588529176SJason Wang 		/* There are 256 bytes to be copied in skb, so there is
165688529176SJason Wang 		 * enough room for skb expand head in case it is used.
16570690899bSMichael S. Tsirkin 		 * The rest of the buffer is mapped from userspace.
16580690899bSMichael S. Tsirkin 		 */
165956f0dcc5SMichael S. Tsirkin 		copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
166096f8d9ecSJason Wang 		if (copylen > good_linear)
166196f8d9ecSJason Wang 			copylen = good_linear;
16623dd5c330SJason Wang 		linear = copylen;
1663f5ff53b4SAl Viro 		iov_iter_advance(&i, copylen);
1664f5ff53b4SAl Viro 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
166588529176SJason Wang 			zerocopy = true;
166688529176SJason Wang 	}
166788529176SJason Wang 
166890e33d45SPetar Penkov 	if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
16691cfe6e93SJason Wang 		/* For the packet that is not easy to be processed
16701cfe6e93SJason Wang 		 * (e.g gso or jumbo packet), we will do it at after
16711cfe6e93SJason Wang 		 * skb was created with generic XDP routine.
16721cfe6e93SJason Wang 		 */
16731cfe6e93SJason Wang 		skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
167466ccbc9cSJason Wang 		if (IS_ERR(skb)) {
167566ccbc9cSJason Wang 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
167666ccbc9cSJason Wang 			return PTR_ERR(skb);
167766ccbc9cSJason Wang 		}
1678761876c8SJason Wang 		if (!skb)
1679761876c8SJason Wang 			return total_len;
168066ccbc9cSJason Wang 	} else {
168188529176SJason Wang 		if (!zerocopy) {
16820690899bSMichael S. Tsirkin 			copylen = len;
168356f0dcc5SMichael S. Tsirkin 			if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
168496f8d9ecSJason Wang 				linear = good_linear;
168596f8d9ecSJason Wang 			else
168656f0dcc5SMichael S. Tsirkin 				linear = tun16_to_cpu(tun, gso.hdr_len);
16873dd5c330SJason Wang 		}
16880690899bSMichael S. Tsirkin 
168990e33d45SPetar Penkov 		if (frags) {
169090e33d45SPetar Penkov 			mutex_lock(&tfile->napi_mutex);
169190e33d45SPetar Penkov 			skb = tun_napi_alloc_frags(tfile, copylen, from);
169290e33d45SPetar Penkov 			/* tun_napi_alloc_frags() enforces a layout for the skb.
169390e33d45SPetar Penkov 			 * If zerocopy is enabled, then this layout will be
169490e33d45SPetar Penkov 			 * overwritten by zerocopy_sg_from_iter().
169590e33d45SPetar Penkov 			 */
169690e33d45SPetar Penkov 			zerocopy = false;
169790e33d45SPetar Penkov 		} else {
169890e33d45SPetar Penkov 			skb = tun_alloc_skb(tfile, align, copylen, linear,
169990e33d45SPetar Penkov 					    noblock);
170090e33d45SPetar Penkov 		}
170190e33d45SPetar Penkov 
170233dccbb0SHerbert Xu 		if (IS_ERR(skb)) {
170333dccbb0SHerbert Xu 			if (PTR_ERR(skb) != -EAGAIN)
1704608b9977SPaolo Abeni 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
170590e33d45SPetar Penkov 			if (frags)
170690e33d45SPetar Penkov 				mutex_unlock(&tfile->napi_mutex);
170733dccbb0SHerbert Xu 			return PTR_ERR(skb);
17081da177e4SLinus Torvalds 		}
17091da177e4SLinus Torvalds 
17100690899bSMichael S. Tsirkin 		if (zerocopy)
1711f5ff53b4SAl Viro 			err = zerocopy_sg_from_iter(skb, from);
1712af1cc7a2SJason Wang 		else
1713f5ff53b4SAl Viro 			err = skb_copy_datagram_from_iter(skb, 0, from, len);
17140690899bSMichael S. Tsirkin 
17150690899bSMichael S. Tsirkin 		if (err) {
1716608b9977SPaolo Abeni 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
17178f22757eSDave Jones 			kfree_skb(skb);
171890e33d45SPetar Penkov 			if (frags) {
171990e33d45SPetar Penkov 				tfile->napi.skb = NULL;
172090e33d45SPetar Penkov 				mutex_unlock(&tfile->napi_mutex);
172190e33d45SPetar Penkov 			}
172290e33d45SPetar Penkov 
17231da177e4SLinus Torvalds 			return -EFAULT;
17248f22757eSDave Jones 		}
172566ccbc9cSJason Wang 	}
17261da177e4SLinus Torvalds 
17273e9e40e7SJarno Rajahalme 	if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1728df10db98SPaolo Abeni 		this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1729df10db98SPaolo Abeni 		kfree_skb(skb);
173090e33d45SPetar Penkov 		if (frags) {
173190e33d45SPetar Penkov 			tfile->napi.skb = NULL;
173290e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
173390e33d45SPetar Penkov 		}
173490e33d45SPetar Penkov 
1735df10db98SPaolo Abeni 		return -EINVAL;
1736df10db98SPaolo Abeni 	}
1737df10db98SPaolo Abeni 
17381da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
173940630b82SMichael S. Tsirkin 	case IFF_TUN:
174040630b82SMichael S. Tsirkin 		if (tun->flags & IFF_NO_PI) {
17412580c4c1SAlexander Potapenko 			u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
17422580c4c1SAlexander Potapenko 
17432580c4c1SAlexander Potapenko 			switch (ip_version) {
17442580c4c1SAlexander Potapenko 			case 4:
1745f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IP);
1746f09f7ee2SAng Way Chuang 				break;
17472580c4c1SAlexander Potapenko 			case 6:
1748f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IPV6);
1749f09f7ee2SAng Way Chuang 				break;
1750f09f7ee2SAng Way Chuang 			default:
1751608b9977SPaolo Abeni 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
1752f09f7ee2SAng Way Chuang 				kfree_skb(skb);
1753f09f7ee2SAng Way Chuang 				return -EINVAL;
1754f09f7ee2SAng Way Chuang 			}
1755f09f7ee2SAng Way Chuang 		}
1756f09f7ee2SAng Way Chuang 
1757459a98edSArnaldo Carvalho de Melo 		skb_reset_mac_header(skb);
17581da177e4SLinus Torvalds 		skb->protocol = pi.proto;
17594c13eb66SArnaldo Carvalho de Melo 		skb->dev = tun->dev;
17601da177e4SLinus Torvalds 		break;
176140630b82SMichael S. Tsirkin 	case IFF_TAP:
176290e33d45SPetar Penkov 		if (!frags)
17631da177e4SLinus Torvalds 			skb->protocol = eth_type_trans(skb, tun->dev);
17641da177e4SLinus Torvalds 		break;
17656403eab1SJoe Perches 	}
17661da177e4SLinus Torvalds 
17670690899bSMichael S. Tsirkin 	/* copy skb_ubuf_info for callback when skb has no error */
17680690899bSMichael S. Tsirkin 	if (zerocopy) {
17690690899bSMichael S. Tsirkin 		skb_shinfo(skb)->destructor_arg = msg_control;
17700690899bSMichael S. Tsirkin 		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1771c9af6db4SPravin B Shelar 		skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1772af1cc7a2SJason Wang 	} else if (msg_control) {
1773af1cc7a2SJason Wang 		struct ubuf_info *uarg = msg_control;
1774af1cc7a2SJason Wang 		uarg->callback(uarg, false);
17750690899bSMichael S. Tsirkin 	}
17760690899bSMichael S. Tsirkin 
177772f65107SVlad Yasevich 	skb_reset_network_header(skb);
177840893fd0SJason Wang 	skb_probe_transport_header(skb, 0);
177938502af7SJason Wang 
17801cfe6e93SJason Wang 	if (skb_xdp) {
1781761876c8SJason Wang 		struct bpf_prog *xdp_prog;
1782761876c8SJason Wang 		int ret;
1783761876c8SJason Wang 
1784761876c8SJason Wang 		rcu_read_lock();
1785761876c8SJason Wang 		xdp_prog = rcu_dereference(tun->xdp_prog);
1786761876c8SJason Wang 		if (xdp_prog) {
1787761876c8SJason Wang 			ret = do_xdp_generic(xdp_prog, skb);
1788761876c8SJason Wang 			if (ret != XDP_PASS) {
1789761876c8SJason Wang 				rcu_read_unlock();
1790761876c8SJason Wang 				return total_len;
1791761876c8SJason Wang 			}
1792761876c8SJason Wang 		}
1793761876c8SJason Wang 		rcu_read_unlock();
1794761876c8SJason Wang 	}
1795761876c8SJason Wang 
179696f84061SJason Wang 	rcu_read_lock();
179796f84061SJason Wang 	if (!rcu_dereference(tun->steering_prog))
1798feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
179996f84061SJason Wang 	rcu_read_unlock();
180094317099SPetar Penkov 
180190e33d45SPetar Penkov 	if (frags) {
180290e33d45SPetar Penkov 		/* Exercise flow dissector code path. */
180390e33d45SPetar Penkov 		u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
180490e33d45SPetar Penkov 
1805010f245bSEric Dumazet 		if (unlikely(headlen > skb_headlen(skb))) {
180690e33d45SPetar Penkov 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
180790e33d45SPetar Penkov 			napi_free_frags(&tfile->napi);
180890e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
180990e33d45SPetar Penkov 			WARN_ON(1);
181090e33d45SPetar Penkov 			return -ENOMEM;
181190e33d45SPetar Penkov 		}
181290e33d45SPetar Penkov 
181390e33d45SPetar Penkov 		local_bh_disable();
181490e33d45SPetar Penkov 		napi_gro_frags(&tfile->napi);
181590e33d45SPetar Penkov 		local_bh_enable();
181690e33d45SPetar Penkov 		mutex_unlock(&tfile->napi_mutex);
1817aec72f33SEric Dumazet 	} else if (tfile->napi_enabled) {
181894317099SPetar Penkov 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
181994317099SPetar Penkov 		int queue_len;
182094317099SPetar Penkov 
182194317099SPetar Penkov 		spin_lock_bh(&queue->lock);
182294317099SPetar Penkov 		__skb_queue_tail(queue, skb);
182394317099SPetar Penkov 		queue_len = skb_queue_len(queue);
182494317099SPetar Penkov 		spin_unlock(&queue->lock);
182594317099SPetar Penkov 
182694317099SPetar Penkov 		if (!more || queue_len > NAPI_POLL_WEIGHT)
182794317099SPetar Penkov 			napi_schedule(&tfile->napi);
182894317099SPetar Penkov 
182994317099SPetar Penkov 		local_bh_enable();
183094317099SPetar Penkov 	} else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
18315503fcecSJason Wang 		tun_rx_batched(tun, tfile, skb, more);
183294317099SPetar Penkov 	} else {
18331da177e4SLinus Torvalds 		netif_rx_ni(skb);
183494317099SPetar Penkov 	}
18351da177e4SLinus Torvalds 
1836608b9977SPaolo Abeni 	stats = get_cpu_ptr(tun->pcpu_stats);
1837608b9977SPaolo Abeni 	u64_stats_update_begin(&stats->syncp);
1838608b9977SPaolo Abeni 	stats->rx_packets++;
1839608b9977SPaolo Abeni 	stats->rx_bytes += len;
1840608b9977SPaolo Abeni 	u64_stats_update_end(&stats->syncp);
1841608b9977SPaolo Abeni 	put_cpu_ptr(stats);
18421da177e4SLinus Torvalds 
184396f84061SJason Wang 	if (rxhash)
18449e85722dSJason Wang 		tun_flow_update(tun, rxhash, tfile);
184596f84061SJason Wang 
18460690899bSMichael S. Tsirkin 	return total_len;
18471da177e4SLinus Torvalds }
18481da177e4SLinus Torvalds 
1849f5ff53b4SAl Viro static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
18501da177e4SLinus Torvalds {
185133dccbb0SHerbert Xu 	struct file *file = iocb->ki_filp;
185254f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
18539484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
1854631ab46bSEric W. Biederman 	ssize_t result;
18551da177e4SLinus Torvalds 
18561da177e4SLinus Torvalds 	if (!tun)
18571da177e4SLinus Torvalds 		return -EBADFD;
18581da177e4SLinus Torvalds 
18595503fcecSJason Wang 	result = tun_get_user(tun, tfile, NULL, from,
18605503fcecSJason Wang 			      file->f_flags & O_NONBLOCK, false);
1861631ab46bSEric W. Biederman 
1862631ab46bSEric W. Biederman 	tun_put(tun);
1863631ab46bSEric W. Biederman 	return result;
18641da177e4SLinus Torvalds }
18651da177e4SLinus Torvalds 
18661da177e4SLinus Torvalds /* Put packet to the user space buffer */
18676f7c156cSstephen hemminger static ssize_t tun_put_user(struct tun_struct *tun,
186854f968d6SJason Wang 			    struct tun_file *tfile,
18691da177e4SLinus Torvalds 			    struct sk_buff *skb,
1870e0b46d0eSHerbert Xu 			    struct iov_iter *iter)
18711da177e4SLinus Torvalds {
18721da177e4SLinus Torvalds 	struct tun_pi pi = { 0, skb->protocol };
1873608b9977SPaolo Abeni 	struct tun_pcpu_stats *stats;
1874e0b46d0eSHerbert Xu 	ssize_t total;
18758c847d25SJason Wang 	int vlan_offset = 0;
1876a8f9bfdfSHerbert Xu 	int vlan_hlen = 0;
18772eb783c4SHerbert Xu 	int vnet_hdr_sz = 0;
1878a8f9bfdfSHerbert Xu 
1879df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb))
1880a8f9bfdfSHerbert Xu 		vlan_hlen = VLAN_HLEN;
18811da177e4SLinus Torvalds 
188240630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR)
1883e1edab87SWillem de Bruijn 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
18841da177e4SLinus Torvalds 
1885e0b46d0eSHerbert Xu 	total = skb->len + vlan_hlen + vnet_hdr_sz;
1886e0b46d0eSHerbert Xu 
188740630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
1888e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < sizeof(pi))
18891da177e4SLinus Torvalds 			return -EINVAL;
18901da177e4SLinus Torvalds 
1891e0b46d0eSHerbert Xu 		total += sizeof(pi);
1892e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < total) {
18931da177e4SLinus Torvalds 			/* Packet will be striped */
18941da177e4SLinus Torvalds 			pi.flags |= TUN_PKT_STRIP;
18951da177e4SLinus Torvalds 		}
18961da177e4SLinus Torvalds 
1897e0b46d0eSHerbert Xu 		if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
18981da177e4SLinus Torvalds 			return -EFAULT;
18991da177e4SLinus Torvalds 	}
19001da177e4SLinus Torvalds 
19012eb783c4SHerbert Xu 	if (vnet_hdr_sz) {
19029403cd7cSJarno Rajahalme 		struct virtio_net_hdr gso;
190334166093SMike Rapoport 
1904e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < vnet_hdr_sz)
1905f43798c2SRusty Russell 			return -EINVAL;
1906f43798c2SRusty Russell 
19073e9e40e7SJarno Rajahalme 		if (virtio_net_hdr_from_skb(skb, &gso,
19086391a448SJason Wang 					    tun_is_little_endian(tun), true)) {
1909f43798c2SRusty Russell 			struct skb_shared_info *sinfo = skb_shinfo(skb);
19106b8a66eeSJoe Perches 			pr_err("unexpected GSO type: "
1911ef3db4a5SMichael S. Tsirkin 			       "0x%x, gso_size %d, hdr_len %d\n",
191256f0dcc5SMichael S. Tsirkin 			       sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
191356f0dcc5SMichael S. Tsirkin 			       tun16_to_cpu(tun, gso.hdr_len));
1914ef3db4a5SMichael S. Tsirkin 			print_hex_dump(KERN_ERR, "tun: ",
1915ef3db4a5SMichael S. Tsirkin 				       DUMP_PREFIX_NONE,
1916ef3db4a5SMichael S. Tsirkin 				       16, 1, skb->head,
191756f0dcc5SMichael S. Tsirkin 				       min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
1918ef3db4a5SMichael S. Tsirkin 			WARN_ON_ONCE(1);
1919ef3db4a5SMichael S. Tsirkin 			return -EINVAL;
1920ef3db4a5SMichael S. Tsirkin 		}
1921f43798c2SRusty Russell 
1922e0b46d0eSHerbert Xu 		if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
1923f43798c2SRusty Russell 			return -EFAULT;
19248c847d25SJason Wang 
19258c847d25SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
1926f43798c2SRusty Russell 	}
1927f43798c2SRusty Russell 
1928a8f9bfdfSHerbert Xu 	if (vlan_hlen) {
1929e0b46d0eSHerbert Xu 		int ret;
19306680ec68SJason Wang 		struct {
19316680ec68SJason Wang 			__be16 h_vlan_proto;
19326680ec68SJason Wang 			__be16 h_vlan_TCI;
19336680ec68SJason Wang 		} veth;
19341da177e4SLinus Torvalds 
19356680ec68SJason Wang 		veth.h_vlan_proto = skb->vlan_proto;
1936df8a39deSJiri Pirko 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
19371da177e4SLinus Torvalds 
19386680ec68SJason Wang 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
19396680ec68SJason Wang 
1940e0b46d0eSHerbert Xu 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
1941e0b46d0eSHerbert Xu 		if (ret || !iov_iter_count(iter))
19426680ec68SJason Wang 			goto done;
19436680ec68SJason Wang 
1944e0b46d0eSHerbert Xu 		ret = copy_to_iter(&veth, sizeof(veth), iter);
1945e0b46d0eSHerbert Xu 		if (ret != sizeof(veth) || !iov_iter_count(iter))
19466680ec68SJason Wang 			goto done;
19476680ec68SJason Wang 	}
19486680ec68SJason Wang 
1949e0b46d0eSHerbert Xu 	skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
19506680ec68SJason Wang 
19516680ec68SJason Wang done:
1952608b9977SPaolo Abeni 	/* caller is in process context, */
1953608b9977SPaolo Abeni 	stats = get_cpu_ptr(tun->pcpu_stats);
1954608b9977SPaolo Abeni 	u64_stats_update_begin(&stats->syncp);
1955608b9977SPaolo Abeni 	stats->tx_packets++;
1956608b9977SPaolo Abeni 	stats->tx_bytes += skb->len + vlan_hlen;
1957608b9977SPaolo Abeni 	u64_stats_update_end(&stats->syncp);
1958608b9977SPaolo Abeni 	put_cpu_ptr(tun->pcpu_stats);
19591da177e4SLinus Torvalds 
19601da177e4SLinus Torvalds 	return total;
19611da177e4SLinus Torvalds }
19621da177e4SLinus Torvalds 
19631576d986SJason Wang static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock,
19641576d986SJason Wang 				     int *err)
19651576d986SJason Wang {
19661576d986SJason Wang 	DECLARE_WAITQUEUE(wait, current);
19671576d986SJason Wang 	struct sk_buff *skb = NULL;
1968f48cc6b2SJason Wang 	int error = 0;
19691576d986SJason Wang 
1970*5990a305SJason Wang 	skb = ptr_ring_consume(&tfile->tx_ring);
19711576d986SJason Wang 	if (skb)
19721576d986SJason Wang 		goto out;
19731576d986SJason Wang 	if (noblock) {
1974f48cc6b2SJason Wang 		error = -EAGAIN;
19751576d986SJason Wang 		goto out;
19761576d986SJason Wang 	}
19771576d986SJason Wang 
19781576d986SJason Wang 	add_wait_queue(&tfile->wq.wait, &wait);
19791576d986SJason Wang 	current->state = TASK_INTERRUPTIBLE;
19801576d986SJason Wang 
19811576d986SJason Wang 	while (1) {
1982*5990a305SJason Wang 		skb = ptr_ring_consume(&tfile->tx_ring);
19831576d986SJason Wang 		if (skb)
19841576d986SJason Wang 			break;
19851576d986SJason Wang 		if (signal_pending(current)) {
1986f48cc6b2SJason Wang 			error = -ERESTARTSYS;
19871576d986SJason Wang 			break;
19881576d986SJason Wang 		}
19891576d986SJason Wang 		if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
1990f48cc6b2SJason Wang 			error = -EFAULT;
19911576d986SJason Wang 			break;
19921576d986SJason Wang 		}
19931576d986SJason Wang 
19941576d986SJason Wang 		schedule();
19951576d986SJason Wang 	}
19961576d986SJason Wang 
19971576d986SJason Wang 	current->state = TASK_RUNNING;
19981576d986SJason Wang 	remove_wait_queue(&tfile->wq.wait, &wait);
19991576d986SJason Wang 
20001576d986SJason Wang out:
2001f48cc6b2SJason Wang 	*err = error;
20021576d986SJason Wang 	return skb;
20031576d986SJason Wang }
20041576d986SJason Wang 
200554f968d6SJason Wang static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
20069b067034SAl Viro 			   struct iov_iter *to,
2007ac77cfd4SJason Wang 			   int noblock, struct sk_buff *skb)
20081da177e4SLinus Torvalds {
20099b067034SAl Viro 	ssize_t ret;
20101576d986SJason Wang 	int err;
20111da177e4SLinus Torvalds 
20123872baf6SRami Rosen 	tun_debug(KERN_INFO, tun, "tun_do_read\n");
20131da177e4SLinus Torvalds 
2014c33ee15bSWei Xu 	if (!iov_iter_count(to)) {
2015c33ee15bSWei Xu 		if (skb)
2016c33ee15bSWei Xu 			kfree_skb(skb);
20179b067034SAl Viro 		return 0;
2018c33ee15bSWei Xu 	}
20191da177e4SLinus Torvalds 
2020ac77cfd4SJason Wang 	if (!skb) {
20211576d986SJason Wang 		/* Read frames from ring */
20221576d986SJason Wang 		skb = tun_ring_recv(tfile, noblock, &err);
2023e0b46d0eSHerbert Xu 		if (!skb)
2024957f094fSAlex Gartrell 			return err;
2025ac77cfd4SJason Wang 	}
2026e0b46d0eSHerbert Xu 
20279b067034SAl Viro 	ret = tun_put_user(tun, tfile, skb, to);
2028f51a5e82SJason Wang 	if (unlikely(ret < 0))
20291da177e4SLinus Torvalds 		kfree_skb(skb);
2030f51a5e82SJason Wang 	else
2031f51a5e82SJason Wang 		consume_skb(skb);
20321da177e4SLinus Torvalds 
203305c2828cSMichael S. Tsirkin 	return ret;
203405c2828cSMichael S. Tsirkin }
203505c2828cSMichael S. Tsirkin 
20369b067034SAl Viro static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
203705c2828cSMichael S. Tsirkin {
203805c2828cSMichael S. Tsirkin 	struct file *file = iocb->ki_filp;
203905c2828cSMichael S. Tsirkin 	struct tun_file *tfile = file->private_data;
20409484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
20419b067034SAl Viro 	ssize_t len = iov_iter_count(to), ret;
204205c2828cSMichael S. Tsirkin 
204305c2828cSMichael S. Tsirkin 	if (!tun)
204405c2828cSMichael S. Tsirkin 		return -EBADFD;
2045ac77cfd4SJason Wang 	ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
204642404c09SDavid S. Miller 	ret = min_t(ssize_t, ret, len);
2047d0b7da8aSZhi Yong Wu 	if (ret > 0)
2048d0b7da8aSZhi Yong Wu 		iocb->ki_pos = ret;
2049631ab46bSEric W. Biederman 	tun_put(tun);
20501da177e4SLinus Torvalds 	return ret;
20511da177e4SLinus Torvalds }
20521da177e4SLinus Torvalds 
205396f84061SJason Wang static void tun_steering_prog_free(struct rcu_head *rcu)
205496f84061SJason Wang {
205596f84061SJason Wang 	struct tun_steering_prog *prog = container_of(rcu,
205696f84061SJason Wang 					 struct tun_steering_prog, rcu);
205796f84061SJason Wang 
205896f84061SJason Wang 	bpf_prog_destroy(prog->prog);
205996f84061SJason Wang 	kfree(prog);
206096f84061SJason Wang }
206196f84061SJason Wang 
206296f84061SJason Wang static int __tun_set_steering_ebpf(struct tun_struct *tun,
206396f84061SJason Wang 				   struct bpf_prog *prog)
206496f84061SJason Wang {
206596f84061SJason Wang 	struct tun_steering_prog *old, *new = NULL;
206696f84061SJason Wang 
206796f84061SJason Wang 	if (prog) {
206896f84061SJason Wang 		new = kmalloc(sizeof(*new), GFP_KERNEL);
206996f84061SJason Wang 		if (!new)
207096f84061SJason Wang 			return -ENOMEM;
207196f84061SJason Wang 		new->prog = prog;
207296f84061SJason Wang 	}
207396f84061SJason Wang 
2074124da8f6SJason Wang 	spin_lock_bh(&tun->lock);
2075124da8f6SJason Wang 	old = rcu_dereference_protected(tun->steering_prog,
2076124da8f6SJason Wang 					lockdep_is_held(&tun->lock));
207796f84061SJason Wang 	rcu_assign_pointer(tun->steering_prog, new);
2078124da8f6SJason Wang 	spin_unlock_bh(&tun->lock);
207996f84061SJason Wang 
208096f84061SJason Wang 	if (old)
208196f84061SJason Wang 		call_rcu(&old->rcu, tun_steering_prog_free);
208296f84061SJason Wang 
208396f84061SJason Wang 	return 0;
208496f84061SJason Wang }
208596f84061SJason Wang 
208696442e42SJason Wang static void tun_free_netdev(struct net_device *dev)
208796442e42SJason Wang {
208896442e42SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
208996442e42SJason Wang 
20904008e97fSJason Wang 	BUG_ON(!(list_empty(&tun->disabled)));
2091608b9977SPaolo Abeni 	free_percpu(tun->pcpu_stats);
209296442e42SJason Wang 	tun_flow_uninit(tun);
20935dbbaf2dSPaul Moore 	security_tun_dev_free_security(tun->security);
209496f84061SJason Wang 	__tun_set_steering_ebpf(tun, NULL);
209596442e42SJason Wang }
209696442e42SJason Wang 
20971da177e4SLinus Torvalds static void tun_setup(struct net_device *dev)
20981da177e4SLinus Torvalds {
20991da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
21001da177e4SLinus Torvalds 
21010625c883SEric W. Biederman 	tun->owner = INVALID_UID;
21020625c883SEric W. Biederman 	tun->group = INVALID_GID;
21031da177e4SLinus Torvalds 
21041da177e4SLinus Torvalds 	dev->ethtool_ops = &tun_ethtool_ops;
2105cf124db5SDavid S. Miller 	dev->needs_free_netdev = true;
2106cf124db5SDavid S. Miller 	dev->priv_destructor = tun_free_netdev;
2107016adb72SJason Wang 	/* We prefer our own queue length */
2108016adb72SJason Wang 	dev->tx_queue_len = TUN_READQ_SIZE;
21091da177e4SLinus Torvalds }
21101da177e4SLinus Torvalds 
2111f019a7a5SEric W. Biederman /* Trivial set of netlink ops to allow deleting tun or tap
2112f019a7a5SEric W. Biederman  * device with netlink.
2113f019a7a5SEric W. Biederman  */
2114a8b8a889SMatthias Schiffer static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2115a8b8a889SMatthias Schiffer 			struct netlink_ext_ack *extack)
2116f019a7a5SEric W. Biederman {
2117f019a7a5SEric W. Biederman 	return -EINVAL;
2118f019a7a5SEric W. Biederman }
2119f019a7a5SEric W. Biederman 
2120f019a7a5SEric W. Biederman static struct rtnl_link_ops tun_link_ops __read_mostly = {
2121f019a7a5SEric W. Biederman 	.kind		= DRV_NAME,
2122f019a7a5SEric W. Biederman 	.priv_size	= sizeof(struct tun_struct),
2123f019a7a5SEric W. Biederman 	.setup		= tun_setup,
2124f019a7a5SEric W. Biederman 	.validate	= tun_validate,
2125f019a7a5SEric W. Biederman };
2126f019a7a5SEric W. Biederman 
212733dccbb0SHerbert Xu static void tun_sock_write_space(struct sock *sk)
212833dccbb0SHerbert Xu {
212954f968d6SJason Wang 	struct tun_file *tfile;
213043815482SEric Dumazet 	wait_queue_head_t *wqueue;
213133dccbb0SHerbert Xu 
213233dccbb0SHerbert Xu 	if (!sock_writeable(sk))
213333dccbb0SHerbert Xu 		return;
213433dccbb0SHerbert Xu 
21359cd3e072SEric Dumazet 	if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
213633dccbb0SHerbert Xu 		return;
213733dccbb0SHerbert Xu 
213843815482SEric Dumazet 	wqueue = sk_sleep(sk);
213943815482SEric Dumazet 	if (wqueue && waitqueue_active(wqueue))
214043815482SEric Dumazet 		wake_up_interruptible_sync_poll(wqueue, POLLOUT |
214105c2828cSMichael S. Tsirkin 						POLLWRNORM | POLLWRBAND);
2142c722c625SHerbert Xu 
214354f968d6SJason Wang 	tfile = container_of(sk, struct tun_file, sk);
214454f968d6SJason Wang 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
214533dccbb0SHerbert Xu }
214633dccbb0SHerbert Xu 
21471b784140SYing Xue static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
214805c2828cSMichael S. Tsirkin {
214954f968d6SJason Wang 	int ret;
215054f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
21519484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
215254f968d6SJason Wang 
215354f968d6SJason Wang 	if (!tun)
215454f968d6SJason Wang 		return -EBADFD;
2155f5ff53b4SAl Viro 
2156c0371da6SAl Viro 	ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
21575503fcecSJason Wang 			   m->msg_flags & MSG_DONTWAIT,
21585503fcecSJason Wang 			   m->msg_flags & MSG_MORE);
215954f968d6SJason Wang 	tun_put(tun);
216054f968d6SJason Wang 	return ret;
216105c2828cSMichael S. Tsirkin }
216205c2828cSMichael S. Tsirkin 
21631b784140SYing Xue static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
216405c2828cSMichael S. Tsirkin 		       int flags)
216505c2828cSMichael S. Tsirkin {
216654f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
21679484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2168c33ee15bSWei Xu 	struct sk_buff *skb = m->msg_control;
216905c2828cSMichael S. Tsirkin 	int ret;
217054f968d6SJason Wang 
2171c33ee15bSWei Xu 	if (!tun) {
2172c33ee15bSWei Xu 		ret = -EBADFD;
2173c33ee15bSWei Xu 		goto out_free_skb;
2174c33ee15bSWei Xu 	}
217554f968d6SJason Wang 
2176eda29772SRichard Cochran 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
21773811ae76SGao feng 		ret = -EINVAL;
2178c33ee15bSWei Xu 		goto out_put_tun;
21793811ae76SGao feng 	}
2180eda29772SRichard Cochran 	if (flags & MSG_ERRQUEUE) {
2181eda29772SRichard Cochran 		ret = sock_recv_errqueue(sock->sk, m, total_len,
2182eda29772SRichard Cochran 					 SOL_PACKET, TUN_TX_TIMESTAMP);
2183eda29772SRichard Cochran 		goto out;
2184eda29772SRichard Cochran 	}
2185c33ee15bSWei Xu 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, skb);
218687897931SAlex Gartrell 	if (ret > (ssize_t)total_len) {
218742404c09SDavid S. Miller 		m->msg_flags |= MSG_TRUNC;
218842404c09SDavid S. Miller 		ret = flags & MSG_TRUNC ? ret : total_len;
218942404c09SDavid S. Miller 	}
21903811ae76SGao feng out:
219154f968d6SJason Wang 	tun_put(tun);
219205c2828cSMichael S. Tsirkin 	return ret;
2193c33ee15bSWei Xu 
2194c33ee15bSWei Xu out_put_tun:
2195c33ee15bSWei Xu 	tun_put(tun);
2196c33ee15bSWei Xu out_free_skb:
2197c33ee15bSWei Xu 	if (skb)
2198c33ee15bSWei Xu 		kfree_skb(skb);
2199c33ee15bSWei Xu 	return ret;
220005c2828cSMichael S. Tsirkin }
220105c2828cSMichael S. Tsirkin 
22021576d986SJason Wang static int tun_peek_len(struct socket *sock)
22031576d986SJason Wang {
22041576d986SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
22051576d986SJason Wang 	struct tun_struct *tun;
22061576d986SJason Wang 	int ret = 0;
22071576d986SJason Wang 
22089484dc74Syuan linyu 	tun = tun_get(tfile);
22091576d986SJason Wang 	if (!tun)
22101576d986SJason Wang 		return 0;
22111576d986SJason Wang 
2212*5990a305SJason Wang 	ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, __skb_array_len_with_tag);
22131576d986SJason Wang 	tun_put(tun);
22141576d986SJason Wang 
22151576d986SJason Wang 	return ret;
22161576d986SJason Wang }
22171576d986SJason Wang 
221805c2828cSMichael S. Tsirkin /* Ops structure to mimic raw sockets with tun */
221905c2828cSMichael S. Tsirkin static const struct proto_ops tun_socket_ops = {
22201576d986SJason Wang 	.peek_len = tun_peek_len,
222105c2828cSMichael S. Tsirkin 	.sendmsg = tun_sendmsg,
222205c2828cSMichael S. Tsirkin 	.recvmsg = tun_recvmsg,
222305c2828cSMichael S. Tsirkin };
222405c2828cSMichael S. Tsirkin 
222533dccbb0SHerbert Xu static struct proto tun_proto = {
222633dccbb0SHerbert Xu 	.name		= "tun",
222733dccbb0SHerbert Xu 	.owner		= THIS_MODULE,
222854f968d6SJason Wang 	.obj_size	= sizeof(struct tun_file),
222933dccbb0SHerbert Xu };
2230f019a7a5SEric W. Biederman 
2231980c9e8cSDavid Woodhouse static int tun_flags(struct tun_struct *tun)
2232980c9e8cSDavid Woodhouse {
2233031f5e03SMichael S. Tsirkin 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2234980c9e8cSDavid Woodhouse }
2235980c9e8cSDavid Woodhouse 
2236980c9e8cSDavid Woodhouse static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2237980c9e8cSDavid Woodhouse 			      char *buf)
2238980c9e8cSDavid Woodhouse {
2239980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2240980c9e8cSDavid Woodhouse 	return sprintf(buf, "0x%x\n", tun_flags(tun));
2241980c9e8cSDavid Woodhouse }
2242980c9e8cSDavid Woodhouse 
2243980c9e8cSDavid Woodhouse static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2244980c9e8cSDavid Woodhouse 			      char *buf)
2245980c9e8cSDavid Woodhouse {
2246980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
22470625c883SEric W. Biederman 	return uid_valid(tun->owner)?
22480625c883SEric W. Biederman 		sprintf(buf, "%u\n",
22490625c883SEric W. Biederman 			from_kuid_munged(current_user_ns(), tun->owner)):
22500625c883SEric W. Biederman 		sprintf(buf, "-1\n");
2251980c9e8cSDavid Woodhouse }
2252980c9e8cSDavid Woodhouse 
2253980c9e8cSDavid Woodhouse static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2254980c9e8cSDavid Woodhouse 			      char *buf)
2255980c9e8cSDavid Woodhouse {
2256980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
22570625c883SEric W. Biederman 	return gid_valid(tun->group) ?
22580625c883SEric W. Biederman 		sprintf(buf, "%u\n",
22590625c883SEric W. Biederman 			from_kgid_munged(current_user_ns(), tun->group)):
22600625c883SEric W. Biederman 		sprintf(buf, "-1\n");
2261980c9e8cSDavid Woodhouse }
2262980c9e8cSDavid Woodhouse 
2263980c9e8cSDavid Woodhouse static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2264980c9e8cSDavid Woodhouse static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2265980c9e8cSDavid Woodhouse static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2266980c9e8cSDavid Woodhouse 
2267c4d33e24STakashi Iwai static struct attribute *tun_dev_attrs[] = {
2268c4d33e24STakashi Iwai 	&dev_attr_tun_flags.attr,
2269c4d33e24STakashi Iwai 	&dev_attr_owner.attr,
2270c4d33e24STakashi Iwai 	&dev_attr_group.attr,
2271c4d33e24STakashi Iwai 	NULL
2272c4d33e24STakashi Iwai };
2273c4d33e24STakashi Iwai 
2274c4d33e24STakashi Iwai static const struct attribute_group tun_attr_group = {
2275c4d33e24STakashi Iwai 	.attrs = tun_dev_attrs
2276c4d33e24STakashi Iwai };
2277c4d33e24STakashi Iwai 
2278d647a591SPavel Emelyanov static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
22791da177e4SLinus Torvalds {
22801da177e4SLinus Torvalds 	struct tun_struct *tun;
228154f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
22821da177e4SLinus Torvalds 	struct net_device *dev;
22831da177e4SLinus Torvalds 	int err;
22841da177e4SLinus Torvalds 
22857c0c3b1aSJason Wang 	if (tfile->detached)
22867c0c3b1aSJason Wang 		return -EINVAL;
22877c0c3b1aSJason Wang 
228890e33d45SPetar Penkov 	if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
228990e33d45SPetar Penkov 		if (!capable(CAP_NET_ADMIN))
229090e33d45SPetar Penkov 			return -EPERM;
229190e33d45SPetar Penkov 
229290e33d45SPetar Penkov 		if (!(ifr->ifr_flags & IFF_NAPI) ||
229390e33d45SPetar Penkov 		    (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
229490e33d45SPetar Penkov 			return -EINVAL;
229590e33d45SPetar Penkov 	}
229690e33d45SPetar Penkov 
229774a3e5a7SEric W. Biederman 	dev = __dev_get_by_name(net, ifr->ifr_name);
229874a3e5a7SEric W. Biederman 	if (dev) {
2299f85ba780SDavid Woodhouse 		if (ifr->ifr_flags & IFF_TUN_EXCL)
2300f85ba780SDavid Woodhouse 			return -EBUSY;
230174a3e5a7SEric W. Biederman 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
230274a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
230374a3e5a7SEric W. Biederman 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
230474a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
230574a3e5a7SEric W. Biederman 		else
230674a3e5a7SEric W. Biederman 			return -EINVAL;
230774a3e5a7SEric W. Biederman 
23088e6d91aeSJason Wang 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
230940630b82SMichael S. Tsirkin 		    !!(tun->flags & IFF_MULTI_QUEUE))
23108e6d91aeSJason Wang 			return -EINVAL;
23118e6d91aeSJason Wang 
2312cde8b15fSJason Wang 		if (tun_not_capable(tun))
23132b980dbdSPaul Moore 			return -EPERM;
23145dbbaf2dSPaul Moore 		err = security_tun_dev_open(tun->security);
23152b980dbdSPaul Moore 		if (err < 0)
23162b980dbdSPaul Moore 			return err;
23172b980dbdSPaul Moore 
231894317099SPetar Penkov 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
231994317099SPetar Penkov 				 ifr->ifr_flags & IFF_NAPI);
2320a7385ba2SEric W. Biederman 		if (err < 0)
2321a7385ba2SEric W. Biederman 			return err;
23224008e97fSJason Wang 
232340630b82SMichael S. Tsirkin 		if (tun->flags & IFF_MULTI_QUEUE &&
2324e8dbad66SJason Wang 		    (tun->numqueues + tun->numdisabled > 1)) {
2325e8dbad66SJason Wang 			/* One or more queue has already been attached, no need
2326e8dbad66SJason Wang 			 * to initialize the device again.
2327e8dbad66SJason Wang 			 */
2328e8dbad66SJason Wang 			return 0;
2329e8dbad66SJason Wang 		}
233086a264abSDavid Howells 	}
23311da177e4SLinus Torvalds 	else {
23321da177e4SLinus Torvalds 		char *name;
23331da177e4SLinus Torvalds 		unsigned long flags = 0;
2334edfb6a14SJason Wang 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2335edfb6a14SJason Wang 			     MAX_TAP_QUEUES : 1;
23361da177e4SLinus Torvalds 
2337c260b772SEric W. Biederman 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2338ca6bb5d7SDavid Woodhouse 			return -EPERM;
23392b980dbdSPaul Moore 		err = security_tun_dev_create();
23402b980dbdSPaul Moore 		if (err < 0)
23412b980dbdSPaul Moore 			return err;
2342ca6bb5d7SDavid Woodhouse 
23431da177e4SLinus Torvalds 		/* Set dev type */
23441da177e4SLinus Torvalds 		if (ifr->ifr_flags & IFF_TUN) {
23451da177e4SLinus Torvalds 			/* TUN device */
234640630b82SMichael S. Tsirkin 			flags |= IFF_TUN;
23471da177e4SLinus Torvalds 			name = "tun%d";
23481da177e4SLinus Torvalds 		} else if (ifr->ifr_flags & IFF_TAP) {
23491da177e4SLinus Torvalds 			/* TAP device */
235040630b82SMichael S. Tsirkin 			flags |= IFF_TAP;
23511da177e4SLinus Torvalds 			name = "tap%d";
23521da177e4SLinus Torvalds 		} else
235336989b90SKusanagi Kouichi 			return -EINVAL;
23541da177e4SLinus Torvalds 
23551da177e4SLinus Torvalds 		if (*ifr->ifr_name)
23561da177e4SLinus Torvalds 			name = ifr->ifr_name;
23571da177e4SLinus Torvalds 
2358c8d68e6bSJason Wang 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2359c835a677STom Gundersen 				       NET_NAME_UNKNOWN, tun_setup, queues,
2360c835a677STom Gundersen 				       queues);
2361edfb6a14SJason Wang 
23621da177e4SLinus Torvalds 		if (!dev)
23631da177e4SLinus Torvalds 			return -ENOMEM;
23640ad646c8SCong Wang 		err = dev_get_valid_name(net, dev, name);
23655c25f65fSJulien Gomes 		if (err < 0)
23660ad646c8SCong Wang 			goto err_free_dev;
23671da177e4SLinus Torvalds 
2368fc54c658SPavel Emelyanov 		dev_net_set(dev, net);
2369f019a7a5SEric W. Biederman 		dev->rtnl_link_ops = &tun_link_ops;
2370fb7589a1SPavel Emelyanov 		dev->ifindex = tfile->ifindex;
2371c4d33e24STakashi Iwai 		dev->sysfs_groups[0] = &tun_attr_group;
2372758e43b7SStephen Hemminger 
23731da177e4SLinus Torvalds 		tun = netdev_priv(dev);
23741da177e4SLinus Torvalds 		tun->dev = dev;
23751da177e4SLinus Torvalds 		tun->flags = flags;
2376f271b2ccSMax Krasnyansky 		tun->txflt.count = 0;
2377d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
23781da177e4SLinus Torvalds 
2379eaea34b2SPaolo Abeni 		tun->align = NET_SKB_PAD;
238054f968d6SJason Wang 		tun->filter_attached = false;
238154f968d6SJason Wang 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
23825503fcecSJason Wang 		tun->rx_batched = 0;
238396f84061SJason Wang 		RCU_INIT_POINTER(tun->steering_prog, NULL);
238433dccbb0SHerbert Xu 
2385608b9977SPaolo Abeni 		tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2386608b9977SPaolo Abeni 		if (!tun->pcpu_stats) {
2387608b9977SPaolo Abeni 			err = -ENOMEM;
2388608b9977SPaolo Abeni 			goto err_free_dev;
2389608b9977SPaolo Abeni 		}
2390608b9977SPaolo Abeni 
239196442e42SJason Wang 		spin_lock_init(&tun->lock);
239296442e42SJason Wang 
23935dbbaf2dSPaul Moore 		err = security_tun_dev_alloc_security(&tun->security);
23945dbbaf2dSPaul Moore 		if (err < 0)
2395608b9977SPaolo Abeni 			goto err_free_stat;
23962b980dbdSPaul Moore 
23971da177e4SLinus Torvalds 		tun_net_init(dev);
2398944a1376SPavel Emelyanov 		tun_flow_init(tun);
239996442e42SJason Wang 
240088255375SMichał Mirosław 		dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
24016680ec68SJason Wang 				   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
24026680ec68SJason Wang 				   NETIF_F_HW_VLAN_STAG_TX;
24032a2bbf17SPaolo Abeni 		dev->features = dev->hw_features | NETIF_F_LLTX;
24046671b224SFernando Luis Vazquez Cao 		dev->vlan_features = dev->features &
24056671b224SFernando Luis Vazquez Cao 				     ~(NETIF_F_HW_VLAN_CTAG_TX |
24066671b224SFernando Luis Vazquez Cao 				       NETIF_F_HW_VLAN_STAG_TX);
240788255375SMichał Mirosław 
24084008e97fSJason Wang 		INIT_LIST_HEAD(&tun->disabled);
240994317099SPetar Penkov 		err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI);
2410eb0fb363SJason Wang 		if (err < 0)
2411662ca437SJason Wang 			goto err_free_flow;
2412eb0fb363SJason Wang 
24131da177e4SLinus Torvalds 		err = register_netdevice(tun->dev);
24141da177e4SLinus Torvalds 		if (err < 0)
2415662ca437SJason Wang 			goto err_detach;
2416af668b3cSMichael S. Tsirkin 	}
2417980c9e8cSDavid Woodhouse 
2418eb0fb363SJason Wang 	netif_carrier_on(tun->dev);
24191da177e4SLinus Torvalds 
24206b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_set_iff\n");
24211da177e4SLinus Torvalds 
2422031f5e03SMichael S. Tsirkin 	tun->flags = (tun->flags & ~TUN_FEATURES) |
2423031f5e03SMichael S. Tsirkin 		(ifr->ifr_flags & TUN_FEATURES);
2424c8d68e6bSJason Wang 
2425e35259a9SMax Krasnyansky 	/* Make sure persistent devices do not get stuck in
2426e35259a9SMax Krasnyansky 	 * xoff state.
2427e35259a9SMax Krasnyansky 	 */
2428e35259a9SMax Krasnyansky 	if (netif_running(tun->dev))
2429c8d68e6bSJason Wang 		netif_tx_wake_all_queues(tun->dev);
2430e35259a9SMax Krasnyansky 
24311da177e4SLinus Torvalds 	strcpy(ifr->ifr_name, tun->dev->name);
24321da177e4SLinus Torvalds 	return 0;
24331da177e4SLinus Torvalds 
2434662ca437SJason Wang err_detach:
2435662ca437SJason Wang 	tun_detach_all(dev);
2436ff244c6bSEric Dumazet 	/* register_netdevice() already called tun_free_netdev() */
2437ff244c6bSEric Dumazet 	goto err_free_dev;
2438ff244c6bSEric Dumazet 
2439662ca437SJason Wang err_free_flow:
2440662ca437SJason Wang 	tun_flow_uninit(tun);
2441662ca437SJason Wang 	security_tun_dev_free_security(tun->security);
2442608b9977SPaolo Abeni err_free_stat:
2443608b9977SPaolo Abeni 	free_percpu(tun->pcpu_stats);
24441da177e4SLinus Torvalds err_free_dev:
24451da177e4SLinus Torvalds 	free_netdev(dev);
24461da177e4SLinus Torvalds 	return err;
24471da177e4SLinus Torvalds }
24481da177e4SLinus Torvalds 
24499ce99cf6SRami Rosen static void tun_get_iff(struct net *net, struct tun_struct *tun,
2450876bfd4dSHerbert Xu 		       struct ifreq *ifr)
2451e3b99556SMark McLoughlin {
24526b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2453e3b99556SMark McLoughlin 
2454e3b99556SMark McLoughlin 	strcpy(ifr->ifr_name, tun->dev->name);
2455e3b99556SMark McLoughlin 
2456980c9e8cSDavid Woodhouse 	ifr->ifr_flags = tun_flags(tun);
2457e3b99556SMark McLoughlin 
2458e3b99556SMark McLoughlin }
2459e3b99556SMark McLoughlin 
24605228ddc9SRusty Russell /* This is like a cut-down ethtool ops, except done via tun fd so no
24615228ddc9SRusty Russell  * privs required. */
246288255375SMichał Mirosław static int set_offload(struct tun_struct *tun, unsigned long arg)
24635228ddc9SRusty Russell {
2464c8f44affSMichał Mirosław 	netdev_features_t features = 0;
24655228ddc9SRusty Russell 
24665228ddc9SRusty Russell 	if (arg & TUN_F_CSUM) {
246788255375SMichał Mirosław 		features |= NETIF_F_HW_CSUM;
24685228ddc9SRusty Russell 		arg &= ~TUN_F_CSUM;
24695228ddc9SRusty Russell 
24705228ddc9SRusty Russell 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
24715228ddc9SRusty Russell 			if (arg & TUN_F_TSO_ECN) {
24725228ddc9SRusty Russell 				features |= NETIF_F_TSO_ECN;
24735228ddc9SRusty Russell 				arg &= ~TUN_F_TSO_ECN;
24745228ddc9SRusty Russell 			}
24755228ddc9SRusty Russell 			if (arg & TUN_F_TSO4)
24765228ddc9SRusty Russell 				features |= NETIF_F_TSO;
24775228ddc9SRusty Russell 			if (arg & TUN_F_TSO6)
24785228ddc9SRusty Russell 				features |= NETIF_F_TSO6;
24795228ddc9SRusty Russell 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
24805228ddc9SRusty Russell 		}
24810c19f846SWillem de Bruijn 
24820c19f846SWillem de Bruijn 		arg &= ~TUN_F_UFO;
24835228ddc9SRusty Russell 	}
24845228ddc9SRusty Russell 
24855228ddc9SRusty Russell 	/* This gives the user a way to test for new features in future by
24865228ddc9SRusty Russell 	 * trying to set them. */
24875228ddc9SRusty Russell 	if (arg)
24885228ddc9SRusty Russell 		return -EINVAL;
24895228ddc9SRusty Russell 
249088255375SMichał Mirosław 	tun->set_features = features;
249109050957SYaroslav Isakov 	tun->dev->wanted_features &= ~TUN_USER_FEATURES;
249209050957SYaroslav Isakov 	tun->dev->wanted_features |= features;
249388255375SMichał Mirosław 	netdev_update_features(tun->dev);
24945228ddc9SRusty Russell 
24955228ddc9SRusty Russell 	return 0;
24965228ddc9SRusty Russell }
24975228ddc9SRusty Russell 
2498c8d68e6bSJason Wang static void tun_detach_filter(struct tun_struct *tun, int n)
2499c8d68e6bSJason Wang {
2500c8d68e6bSJason Wang 	int i;
2501c8d68e6bSJason Wang 	struct tun_file *tfile;
2502c8d68e6bSJason Wang 
2503c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
2504b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
25058ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
25068ced425eSHannes Frederic Sowa 		sk_detach_filter(tfile->socket.sk);
25078ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2508c8d68e6bSJason Wang 	}
2509c8d68e6bSJason Wang 
2510c8d68e6bSJason Wang 	tun->filter_attached = false;
2511c8d68e6bSJason Wang }
2512c8d68e6bSJason Wang 
2513c8d68e6bSJason Wang static int tun_attach_filter(struct tun_struct *tun)
2514c8d68e6bSJason Wang {
2515c8d68e6bSJason Wang 	int i, ret = 0;
2516c8d68e6bSJason Wang 	struct tun_file *tfile;
2517c8d68e6bSJason Wang 
2518c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2519b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
25208ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
25218ced425eSHannes Frederic Sowa 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
25228ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2523c8d68e6bSJason Wang 		if (ret) {
2524c8d68e6bSJason Wang 			tun_detach_filter(tun, i);
2525c8d68e6bSJason Wang 			return ret;
2526c8d68e6bSJason Wang 		}
2527c8d68e6bSJason Wang 	}
2528c8d68e6bSJason Wang 
2529c8d68e6bSJason Wang 	tun->filter_attached = true;
2530c8d68e6bSJason Wang 	return ret;
2531c8d68e6bSJason Wang }
2532c8d68e6bSJason Wang 
2533c8d68e6bSJason Wang static void tun_set_sndbuf(struct tun_struct *tun)
2534c8d68e6bSJason Wang {
2535c8d68e6bSJason Wang 	struct tun_file *tfile;
2536c8d68e6bSJason Wang 	int i;
2537c8d68e6bSJason Wang 
2538c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2539b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
2540c8d68e6bSJason Wang 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2541c8d68e6bSJason Wang 	}
2542c8d68e6bSJason Wang }
2543c8d68e6bSJason Wang 
2544cde8b15fSJason Wang static int tun_set_queue(struct file *file, struct ifreq *ifr)
2545cde8b15fSJason Wang {
2546cde8b15fSJason Wang 	struct tun_file *tfile = file->private_data;
2547cde8b15fSJason Wang 	struct tun_struct *tun;
2548cde8b15fSJason Wang 	int ret = 0;
2549cde8b15fSJason Wang 
2550cde8b15fSJason Wang 	rtnl_lock();
2551cde8b15fSJason Wang 
2552cde8b15fSJason Wang 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
25534008e97fSJason Wang 		tun = tfile->detached;
25545dbbaf2dSPaul Moore 		if (!tun) {
2555cde8b15fSJason Wang 			ret = -EINVAL;
25565dbbaf2dSPaul Moore 			goto unlock;
25575dbbaf2dSPaul Moore 		}
25585dbbaf2dSPaul Moore 		ret = security_tun_dev_attach_queue(tun->security);
25595dbbaf2dSPaul Moore 		if (ret < 0)
25605dbbaf2dSPaul Moore 			goto unlock;
256194317099SPetar Penkov 		ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI);
25624008e97fSJason Wang 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2563b8deabd3SJason Wang 		tun = rtnl_dereference(tfile->tun);
256440630b82SMichael S. Tsirkin 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
25654008e97fSJason Wang 			ret = -EINVAL;
2566cde8b15fSJason Wang 		else
25674008e97fSJason Wang 			__tun_detach(tfile, false);
25684008e97fSJason Wang 	} else
2569cde8b15fSJason Wang 		ret = -EINVAL;
2570cde8b15fSJason Wang 
25715dbbaf2dSPaul Moore unlock:
2572cde8b15fSJason Wang 	rtnl_unlock();
2573cde8b15fSJason Wang 	return ret;
2574cde8b15fSJason Wang }
2575cde8b15fSJason Wang 
257696f84061SJason Wang static int tun_set_steering_ebpf(struct tun_struct *tun, void __user *data)
257796f84061SJason Wang {
257896f84061SJason Wang 	struct bpf_prog *prog;
257996f84061SJason Wang 	int fd;
258096f84061SJason Wang 
258196f84061SJason Wang 	if (copy_from_user(&fd, data, sizeof(fd)))
258296f84061SJason Wang 		return -EFAULT;
258396f84061SJason Wang 
258496f84061SJason Wang 	if (fd == -1) {
258596f84061SJason Wang 		prog = NULL;
258696f84061SJason Wang 	} else {
258796f84061SJason Wang 		prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
258896f84061SJason Wang 		if (IS_ERR(prog))
258996f84061SJason Wang 			return PTR_ERR(prog);
259096f84061SJason Wang 	}
259196f84061SJason Wang 
259296f84061SJason Wang 	return __tun_set_steering_ebpf(tun, prog);
259396f84061SJason Wang }
259496f84061SJason Wang 
259550857e2aSArnd Bergmann static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
259650857e2aSArnd Bergmann 			    unsigned long arg, int ifreq_len)
25971da177e4SLinus Torvalds {
259836b50babSEric W. Biederman 	struct tun_file *tfile = file->private_data;
2599631ab46bSEric W. Biederman 	struct tun_struct *tun;
26001da177e4SLinus Torvalds 	void __user* argp = (void __user*)arg;
26011da177e4SLinus Torvalds 	struct ifreq ifr;
26020625c883SEric W. Biederman 	kuid_t owner;
26030625c883SEric W. Biederman 	kgid_t group;
260433dccbb0SHerbert Xu 	int sndbuf;
2605d9d52b51SMichael S. Tsirkin 	int vnet_hdr_sz;
2606fb7589a1SPavel Emelyanov 	unsigned int ifindex;
26071cf8e410SMichael S. Tsirkin 	int le;
2608f271b2ccSMax Krasnyansky 	int ret;
26091da177e4SLinus Torvalds 
261020861f26SGao Feng 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) {
261150857e2aSArnd Bergmann 		if (copy_from_user(&ifr, argp, ifreq_len))
26121da177e4SLinus Torvalds 			return -EFAULT;
26138bbb1813SDavid S. Miller 	} else {
2614a117dacdSMathias Krause 		memset(&ifr, 0, sizeof(ifr));
26158bbb1813SDavid S. Miller 	}
2616631ab46bSEric W. Biederman 	if (cmd == TUNGETFEATURES) {
2617631ab46bSEric W. Biederman 		/* Currently this just means: "what IFF flags are valid?".
2618631ab46bSEric W. Biederman 		 * This is needed because we never checked for invalid flags on
2619031f5e03SMichael S. Tsirkin 		 * TUNSETIFF.
2620031f5e03SMichael S. Tsirkin 		 */
2621031f5e03SMichael S. Tsirkin 		return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
2622631ab46bSEric W. Biederman 				(unsigned int __user*)argp);
2623cde8b15fSJason Wang 	} else if (cmd == TUNSETQUEUE)
2624cde8b15fSJason Wang 		return tun_set_queue(file, &ifr);
2625631ab46bSEric W. Biederman 
2626c8d68e6bSJason Wang 	ret = 0;
2627876bfd4dSHerbert Xu 	rtnl_lock();
2628876bfd4dSHerbert Xu 
26299484dc74Syuan linyu 	tun = tun_get(tfile);
26300f16bc13SGao Feng 	if (cmd == TUNSETIFF) {
26310f16bc13SGao Feng 		ret = -EEXIST;
26320f16bc13SGao Feng 		if (tun)
26330f16bc13SGao Feng 			goto unlock;
26340f16bc13SGao Feng 
26351da177e4SLinus Torvalds 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
26361da177e4SLinus Torvalds 
2637140e807dSEric W. Biederman 		ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr);
26381da177e4SLinus Torvalds 
2639876bfd4dSHerbert Xu 		if (ret)
2640876bfd4dSHerbert Xu 			goto unlock;
26411da177e4SLinus Torvalds 
264250857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2643876bfd4dSHerbert Xu 			ret = -EFAULT;
2644876bfd4dSHerbert Xu 		goto unlock;
26451da177e4SLinus Torvalds 	}
2646fb7589a1SPavel Emelyanov 	if (cmd == TUNSETIFINDEX) {
2647fb7589a1SPavel Emelyanov 		ret = -EPERM;
2648fb7589a1SPavel Emelyanov 		if (tun)
2649fb7589a1SPavel Emelyanov 			goto unlock;
2650fb7589a1SPavel Emelyanov 
2651fb7589a1SPavel Emelyanov 		ret = -EFAULT;
2652fb7589a1SPavel Emelyanov 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
2653fb7589a1SPavel Emelyanov 			goto unlock;
2654fb7589a1SPavel Emelyanov 
2655fb7589a1SPavel Emelyanov 		ret = 0;
2656fb7589a1SPavel Emelyanov 		tfile->ifindex = ifindex;
2657fb7589a1SPavel Emelyanov 		goto unlock;
2658fb7589a1SPavel Emelyanov 	}
26591da177e4SLinus Torvalds 
2660876bfd4dSHerbert Xu 	ret = -EBADFD;
26611da177e4SLinus Torvalds 	if (!tun)
2662876bfd4dSHerbert Xu 		goto unlock;
26631da177e4SLinus Torvalds 
26641e588338SJason Wang 	tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
26651da177e4SLinus Torvalds 
2666631ab46bSEric W. Biederman 	ret = 0;
26671da177e4SLinus Torvalds 	switch (cmd) {
2668e3b99556SMark McLoughlin 	case TUNGETIFF:
26699ce99cf6SRami Rosen 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2670e3b99556SMark McLoughlin 
26713d407a80SPavel Emelyanov 		if (tfile->detached)
26723d407a80SPavel Emelyanov 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
2673849c9b6fSPavel Emelyanov 		if (!tfile->socket.sk->sk_filter)
2674849c9b6fSPavel Emelyanov 			ifr.ifr_flags |= IFF_NOFILTER;
26753d407a80SPavel Emelyanov 
267650857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2677631ab46bSEric W. Biederman 			ret = -EFAULT;
2678e3b99556SMark McLoughlin 		break;
2679e3b99556SMark McLoughlin 
26801da177e4SLinus Torvalds 	case TUNSETNOCSUM:
26811da177e4SLinus Torvalds 		/* Disable/Enable checksum */
26821da177e4SLinus Torvalds 
268388255375SMichał Mirosław 		/* [unimplemented] */
268488255375SMichał Mirosław 		tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
26856b8a66eeSJoe Perches 			  arg ? "disabled" : "enabled");
26861da177e4SLinus Torvalds 		break;
26871da177e4SLinus Torvalds 
26881da177e4SLinus Torvalds 	case TUNSETPERSIST:
268954f968d6SJason Wang 		/* Disable/Enable persist mode. Keep an extra reference to the
269054f968d6SJason Wang 		 * module to prevent the module being unprobed.
269154f968d6SJason Wang 		 */
269240630b82SMichael S. Tsirkin 		if (arg && !(tun->flags & IFF_PERSIST)) {
269340630b82SMichael S. Tsirkin 			tun->flags |= IFF_PERSIST;
269454f968d6SJason Wang 			__module_get(THIS_MODULE);
2695dd38bd85SJason Wang 		}
269640630b82SMichael S. Tsirkin 		if (!arg && (tun->flags & IFF_PERSIST)) {
269740630b82SMichael S. Tsirkin 			tun->flags &= ~IFF_PERSIST;
269854f968d6SJason Wang 			module_put(THIS_MODULE);
269954f968d6SJason Wang 		}
27001da177e4SLinus Torvalds 
27016b8a66eeSJoe Perches 		tun_debug(KERN_INFO, tun, "persist %s\n",
27026b8a66eeSJoe Perches 			  arg ? "enabled" : "disabled");
27031da177e4SLinus Torvalds 		break;
27041da177e4SLinus Torvalds 
27051da177e4SLinus Torvalds 	case TUNSETOWNER:
27061da177e4SLinus Torvalds 		/* Set owner of the device */
27070625c883SEric W. Biederman 		owner = make_kuid(current_user_ns(), arg);
27080625c883SEric W. Biederman 		if (!uid_valid(owner)) {
27090625c883SEric W. Biederman 			ret = -EINVAL;
27100625c883SEric W. Biederman 			break;
27110625c883SEric W. Biederman 		}
27120625c883SEric W. Biederman 		tun->owner = owner;
27131e588338SJason Wang 		tun_debug(KERN_INFO, tun, "owner set to %u\n",
27140625c883SEric W. Biederman 			  from_kuid(&init_user_ns, tun->owner));
27151da177e4SLinus Torvalds 		break;
27161da177e4SLinus Torvalds 
27178c644623SGuido Guenther 	case TUNSETGROUP:
27188c644623SGuido Guenther 		/* Set group of the device */
27190625c883SEric W. Biederman 		group = make_kgid(current_user_ns(), arg);
27200625c883SEric W. Biederman 		if (!gid_valid(group)) {
27210625c883SEric W. Biederman 			ret = -EINVAL;
27220625c883SEric W. Biederman 			break;
27230625c883SEric W. Biederman 		}
27240625c883SEric W. Biederman 		tun->group = group;
27251e588338SJason Wang 		tun_debug(KERN_INFO, tun, "group set to %u\n",
27260625c883SEric W. Biederman 			  from_kgid(&init_user_ns, tun->group));
27278c644623SGuido Guenther 		break;
27288c644623SGuido Guenther 
2729ff4cc3acSMike Kershaw 	case TUNSETLINK:
2730ff4cc3acSMike Kershaw 		/* Only allow setting the type when the interface is down */
2731ff4cc3acSMike Kershaw 		if (tun->dev->flags & IFF_UP) {
27326b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun,
27336b8a66eeSJoe Perches 				  "Linktype set failed because interface is up\n");
273448abfe05SDavid S. Miller 			ret = -EBUSY;
2735ff4cc3acSMike Kershaw 		} else {
2736ff4cc3acSMike Kershaw 			tun->dev->type = (int) arg;
27376b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun, "linktype set to %d\n",
27386b8a66eeSJoe Perches 				  tun->dev->type);
273948abfe05SDavid S. Miller 			ret = 0;
2740ff4cc3acSMike Kershaw 		}
2741631ab46bSEric W. Biederman 		break;
2742ff4cc3acSMike Kershaw 
27431da177e4SLinus Torvalds #ifdef TUN_DEBUG
27441da177e4SLinus Torvalds 	case TUNSETDEBUG:
27451da177e4SLinus Torvalds 		tun->debug = arg;
27461da177e4SLinus Torvalds 		break;
27471da177e4SLinus Torvalds #endif
27485228ddc9SRusty Russell 	case TUNSETOFFLOAD:
274988255375SMichał Mirosław 		ret = set_offload(tun, arg);
2750631ab46bSEric W. Biederman 		break;
27515228ddc9SRusty Russell 
2752f271b2ccSMax Krasnyansky 	case TUNSETTXFILTER:
2753f271b2ccSMax Krasnyansky 		/* Can be set only for TAPs */
2754631ab46bSEric W. Biederman 		ret = -EINVAL;
275540630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2756631ab46bSEric W. Biederman 			break;
2757c0e5a8c2SHarvey Harrison 		ret = update_filter(&tun->txflt, (void __user *)arg);
2758631ab46bSEric W. Biederman 		break;
27591da177e4SLinus Torvalds 
27601da177e4SLinus Torvalds 	case SIOCGIFHWADDR:
2761b595076aSUwe Kleine-König 		/* Get hw address */
2762f271b2ccSMax Krasnyansky 		memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2763f271b2ccSMax Krasnyansky 		ifr.ifr_hwaddr.sa_family = tun->dev->type;
276450857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2765631ab46bSEric W. Biederman 			ret = -EFAULT;
2766631ab46bSEric W. Biederman 		break;
27671da177e4SLinus Torvalds 
27681da177e4SLinus Torvalds 	case SIOCSIFHWADDR:
2769f271b2ccSMax Krasnyansky 		/* Set hw address */
27706b8a66eeSJoe Perches 		tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
27716b8a66eeSJoe Perches 			  ifr.ifr_hwaddr.sa_data);
277240102371SKim B. Heino 
277340102371SKim B. Heino 		ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2774631ab46bSEric W. Biederman 		break;
277533dccbb0SHerbert Xu 
277633dccbb0SHerbert Xu 	case TUNGETSNDBUF:
277754f968d6SJason Wang 		sndbuf = tfile->socket.sk->sk_sndbuf;
277833dccbb0SHerbert Xu 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
277933dccbb0SHerbert Xu 			ret = -EFAULT;
278033dccbb0SHerbert Xu 		break;
278133dccbb0SHerbert Xu 
278233dccbb0SHerbert Xu 	case TUNSETSNDBUF:
278333dccbb0SHerbert Xu 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
278433dccbb0SHerbert Xu 			ret = -EFAULT;
278533dccbb0SHerbert Xu 			break;
278633dccbb0SHerbert Xu 		}
278793161922SCraig Gallek 		if (sndbuf <= 0) {
278893161922SCraig Gallek 			ret = -EINVAL;
278993161922SCraig Gallek 			break;
279093161922SCraig Gallek 		}
279133dccbb0SHerbert Xu 
2792c8d68e6bSJason Wang 		tun->sndbuf = sndbuf;
2793c8d68e6bSJason Wang 		tun_set_sndbuf(tun);
279433dccbb0SHerbert Xu 		break;
279533dccbb0SHerbert Xu 
2796d9d52b51SMichael S. Tsirkin 	case TUNGETVNETHDRSZ:
2797d9d52b51SMichael S. Tsirkin 		vnet_hdr_sz = tun->vnet_hdr_sz;
2798d9d52b51SMichael S. Tsirkin 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2799d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
2800d9d52b51SMichael S. Tsirkin 		break;
2801d9d52b51SMichael S. Tsirkin 
2802d9d52b51SMichael S. Tsirkin 	case TUNSETVNETHDRSZ:
2803d9d52b51SMichael S. Tsirkin 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2804d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
2805d9d52b51SMichael S. Tsirkin 			break;
2806d9d52b51SMichael S. Tsirkin 		}
2807d9d52b51SMichael S. Tsirkin 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2808d9d52b51SMichael S. Tsirkin 			ret = -EINVAL;
2809d9d52b51SMichael S. Tsirkin 			break;
2810d9d52b51SMichael S. Tsirkin 		}
2811d9d52b51SMichael S. Tsirkin 
2812d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = vnet_hdr_sz;
2813d9d52b51SMichael S. Tsirkin 		break;
2814d9d52b51SMichael S. Tsirkin 
28151cf8e410SMichael S. Tsirkin 	case TUNGETVNETLE:
28161cf8e410SMichael S. Tsirkin 		le = !!(tun->flags & TUN_VNET_LE);
28171cf8e410SMichael S. Tsirkin 		if (put_user(le, (int __user *)argp))
28181cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
28191cf8e410SMichael S. Tsirkin 		break;
28201cf8e410SMichael S. Tsirkin 
28211cf8e410SMichael S. Tsirkin 	case TUNSETVNETLE:
28221cf8e410SMichael S. Tsirkin 		if (get_user(le, (int __user *)argp)) {
28231cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
28241cf8e410SMichael S. Tsirkin 			break;
28251cf8e410SMichael S. Tsirkin 		}
28261cf8e410SMichael S. Tsirkin 		if (le)
28271cf8e410SMichael S. Tsirkin 			tun->flags |= TUN_VNET_LE;
28281cf8e410SMichael S. Tsirkin 		else
28291cf8e410SMichael S. Tsirkin 			tun->flags &= ~TUN_VNET_LE;
28301cf8e410SMichael S. Tsirkin 		break;
28311cf8e410SMichael S. Tsirkin 
28328b8e658bSGreg Kurz 	case TUNGETVNETBE:
28338b8e658bSGreg Kurz 		ret = tun_get_vnet_be(tun, argp);
28348b8e658bSGreg Kurz 		break;
28358b8e658bSGreg Kurz 
28368b8e658bSGreg Kurz 	case TUNSETVNETBE:
28378b8e658bSGreg Kurz 		ret = tun_set_vnet_be(tun, argp);
28388b8e658bSGreg Kurz 		break;
28398b8e658bSGreg Kurz 
284099405162SMichael S. Tsirkin 	case TUNATTACHFILTER:
284199405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
284299405162SMichael S. Tsirkin 		ret = -EINVAL;
284340630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
284499405162SMichael S. Tsirkin 			break;
284599405162SMichael S. Tsirkin 		ret = -EFAULT;
284654f968d6SJason Wang 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
284799405162SMichael S. Tsirkin 			break;
284899405162SMichael S. Tsirkin 
2849c8d68e6bSJason Wang 		ret = tun_attach_filter(tun);
285099405162SMichael S. Tsirkin 		break;
285199405162SMichael S. Tsirkin 
285299405162SMichael S. Tsirkin 	case TUNDETACHFILTER:
285399405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
285499405162SMichael S. Tsirkin 		ret = -EINVAL;
285540630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
285699405162SMichael S. Tsirkin 			break;
2857c8d68e6bSJason Wang 		ret = 0;
2858c8d68e6bSJason Wang 		tun_detach_filter(tun, tun->numqueues);
285999405162SMichael S. Tsirkin 		break;
286099405162SMichael S. Tsirkin 
286176975e9cSPavel Emelyanov 	case TUNGETFILTER:
286276975e9cSPavel Emelyanov 		ret = -EINVAL;
286340630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
286476975e9cSPavel Emelyanov 			break;
286576975e9cSPavel Emelyanov 		ret = -EFAULT;
286676975e9cSPavel Emelyanov 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
286776975e9cSPavel Emelyanov 			break;
286876975e9cSPavel Emelyanov 		ret = 0;
286976975e9cSPavel Emelyanov 		break;
287076975e9cSPavel Emelyanov 
287196f84061SJason Wang 	case TUNSETSTEERINGEBPF:
287296f84061SJason Wang 		ret = tun_set_steering_ebpf(tun, argp);
287396f84061SJason Wang 		break;
287496f84061SJason Wang 
28751da177e4SLinus Torvalds 	default:
2876631ab46bSEric W. Biederman 		ret = -EINVAL;
2877631ab46bSEric W. Biederman 		break;
2878ee289b64SJoe Perches 	}
28791da177e4SLinus Torvalds 
2880876bfd4dSHerbert Xu unlock:
2881876bfd4dSHerbert Xu 	rtnl_unlock();
2882876bfd4dSHerbert Xu 	if (tun)
2883631ab46bSEric W. Biederman 		tun_put(tun);
2884631ab46bSEric W. Biederman 	return ret;
28851da177e4SLinus Torvalds }
28861da177e4SLinus Torvalds 
288750857e2aSArnd Bergmann static long tun_chr_ioctl(struct file *file,
288850857e2aSArnd Bergmann 			  unsigned int cmd, unsigned long arg)
288950857e2aSArnd Bergmann {
289050857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
289150857e2aSArnd Bergmann }
289250857e2aSArnd Bergmann 
289350857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
289450857e2aSArnd Bergmann static long tun_chr_compat_ioctl(struct file *file,
289550857e2aSArnd Bergmann 			 unsigned int cmd, unsigned long arg)
289650857e2aSArnd Bergmann {
289750857e2aSArnd Bergmann 	switch (cmd) {
289850857e2aSArnd Bergmann 	case TUNSETIFF:
289950857e2aSArnd Bergmann 	case TUNGETIFF:
290050857e2aSArnd Bergmann 	case TUNSETTXFILTER:
290150857e2aSArnd Bergmann 	case TUNGETSNDBUF:
290250857e2aSArnd Bergmann 	case TUNSETSNDBUF:
290350857e2aSArnd Bergmann 	case SIOCGIFHWADDR:
290450857e2aSArnd Bergmann 	case SIOCSIFHWADDR:
290550857e2aSArnd Bergmann 		arg = (unsigned long)compat_ptr(arg);
290650857e2aSArnd Bergmann 		break;
290750857e2aSArnd Bergmann 	default:
290850857e2aSArnd Bergmann 		arg = (compat_ulong_t)arg;
290950857e2aSArnd Bergmann 		break;
291050857e2aSArnd Bergmann 	}
291150857e2aSArnd Bergmann 
291250857e2aSArnd Bergmann 	/*
291350857e2aSArnd Bergmann 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
291450857e2aSArnd Bergmann 	 * the end of that structure. All fields that are used in this
291550857e2aSArnd Bergmann 	 * driver are compatible though, we don't need to convert the
291650857e2aSArnd Bergmann 	 * contents.
291750857e2aSArnd Bergmann 	 */
291850857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
291950857e2aSArnd Bergmann }
292050857e2aSArnd Bergmann #endif /* CONFIG_COMPAT */
292150857e2aSArnd Bergmann 
29221da177e4SLinus Torvalds static int tun_chr_fasync(int fd, struct file *file, int on)
29231da177e4SLinus Torvalds {
292454f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
29251da177e4SLinus Torvalds 	int ret;
29261da177e4SLinus Torvalds 
292754f968d6SJason Wang 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
29289d319522SJonathan Corbet 		goto out;
29291da177e4SLinus Torvalds 
29301da177e4SLinus Torvalds 	if (on) {
2931e0b93eddSJeff Layton 		__f_setown(file, task_pid(current), PIDTYPE_PID, 0);
293254f968d6SJason Wang 		tfile->flags |= TUN_FASYNC;
29331da177e4SLinus Torvalds 	} else
293454f968d6SJason Wang 		tfile->flags &= ~TUN_FASYNC;
29359d319522SJonathan Corbet 	ret = 0;
29369d319522SJonathan Corbet out:
29379d319522SJonathan Corbet 	return ret;
29381da177e4SLinus Torvalds }
29391da177e4SLinus Torvalds 
29401da177e4SLinus Torvalds static int tun_chr_open(struct inode *inode, struct file * file)
29411da177e4SLinus Torvalds {
2942140e807dSEric W. Biederman 	struct net *net = current->nsproxy->net_ns;
2943631ab46bSEric W. Biederman 	struct tun_file *tfile;
2944deed49fbSThomas Gleixner 
29456b8a66eeSJoe Perches 	DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2946631ab46bSEric W. Biederman 
2947140e807dSEric W. Biederman 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
294811aa9c28SEric W. Biederman 					    &tun_proto, 0);
2949631ab46bSEric W. Biederman 	if (!tfile)
2950631ab46bSEric W. Biederman 		return -ENOMEM;
2951c956674bSMonam Agarwal 	RCU_INIT_POINTER(tfile->tun, NULL);
295254f968d6SJason Wang 	tfile->flags = 0;
2953fb7589a1SPavel Emelyanov 	tfile->ifindex = 0;
295454f968d6SJason Wang 
295554f968d6SJason Wang 	init_waitqueue_head(&tfile->wq.wait);
29569e641bdcSXi Wang 	RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
295754f968d6SJason Wang 
295854f968d6SJason Wang 	tfile->socket.file = file;
295954f968d6SJason Wang 	tfile->socket.ops = &tun_socket_ops;
296054f968d6SJason Wang 
296154f968d6SJason Wang 	sock_init_data(&tfile->socket, &tfile->sk);
296254f968d6SJason Wang 
296354f968d6SJason Wang 	tfile->sk.sk_write_space = tun_sock_write_space;
296454f968d6SJason Wang 	tfile->sk.sk_sndbuf = INT_MAX;
296554f968d6SJason Wang 
2966631ab46bSEric W. Biederman 	file->private_data = tfile;
29674008e97fSJason Wang 	INIT_LIST_HEAD(&tfile->next);
296854f968d6SJason Wang 
296919a6afb2SJason Wang 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
297019a6afb2SJason Wang 
29711da177e4SLinus Torvalds 	return 0;
29721da177e4SLinus Torvalds }
29731da177e4SLinus Torvalds 
29741da177e4SLinus Torvalds static int tun_chr_close(struct inode *inode, struct file *file)
29751da177e4SLinus Torvalds {
2976631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
29771da177e4SLinus Torvalds 
2978c8d68e6bSJason Wang 	tun_detach(tfile, true);
29791da177e4SLinus Torvalds 
29801da177e4SLinus Torvalds 	return 0;
29811da177e4SLinus Torvalds }
29821da177e4SLinus Torvalds 
298393e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
29849484dc74Syuan linyu static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
298593e14b6dSMasatake YAMATO {
29869484dc74Syuan linyu 	struct tun_file *tfile = file->private_data;
298793e14b6dSMasatake YAMATO 	struct tun_struct *tun;
298893e14b6dSMasatake YAMATO 	struct ifreq ifr;
298993e14b6dSMasatake YAMATO 
299093e14b6dSMasatake YAMATO 	memset(&ifr, 0, sizeof(ifr));
299193e14b6dSMasatake YAMATO 
299293e14b6dSMasatake YAMATO 	rtnl_lock();
29939484dc74Syuan linyu 	tun = tun_get(tfile);
299493e14b6dSMasatake YAMATO 	if (tun)
299593e14b6dSMasatake YAMATO 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
299693e14b6dSMasatake YAMATO 	rtnl_unlock();
299793e14b6dSMasatake YAMATO 
299893e14b6dSMasatake YAMATO 	if (tun)
299993e14b6dSMasatake YAMATO 		tun_put(tun);
300093e14b6dSMasatake YAMATO 
3001a3816ab0SJoe Perches 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
300293e14b6dSMasatake YAMATO }
300393e14b6dSMasatake YAMATO #endif
300493e14b6dSMasatake YAMATO 
3005d54b1fdbSArjan van de Ven static const struct file_operations tun_fops = {
30061da177e4SLinus Torvalds 	.owner	= THIS_MODULE,
30071da177e4SLinus Torvalds 	.llseek = no_llseek,
30089b067034SAl Viro 	.read_iter  = tun_chr_read_iter,
3009f5ff53b4SAl Viro 	.write_iter = tun_chr_write_iter,
30101da177e4SLinus Torvalds 	.poll	= tun_chr_poll,
3011876bfd4dSHerbert Xu 	.unlocked_ioctl	= tun_chr_ioctl,
301250857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
301350857e2aSArnd Bergmann 	.compat_ioctl = tun_chr_compat_ioctl,
301450857e2aSArnd Bergmann #endif
30151da177e4SLinus Torvalds 	.open	= tun_chr_open,
30161da177e4SLinus Torvalds 	.release = tun_chr_close,
301793e14b6dSMasatake YAMATO 	.fasync = tun_chr_fasync,
301893e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
301993e14b6dSMasatake YAMATO 	.show_fdinfo = tun_chr_show_fdinfo,
302093e14b6dSMasatake YAMATO #endif
30211da177e4SLinus Torvalds };
30221da177e4SLinus Torvalds 
30231da177e4SLinus Torvalds static struct miscdevice tun_miscdev = {
30241da177e4SLinus Torvalds 	.minor = TUN_MINOR,
30251da177e4SLinus Torvalds 	.name = "tun",
3026e454cea2SKay Sievers 	.nodename = "net/tun",
30271da177e4SLinus Torvalds 	.fops = &tun_fops,
30281da177e4SLinus Torvalds };
30291da177e4SLinus Torvalds 
30301da177e4SLinus Torvalds /* ethtool interface */
30311da177e4SLinus Torvalds 
303229ccc49dSPhilippe Reynes static int tun_get_link_ksettings(struct net_device *dev,
303329ccc49dSPhilippe Reynes 				  struct ethtool_link_ksettings *cmd)
30341da177e4SLinus Torvalds {
303529ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
303629ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
303729ccc49dSPhilippe Reynes 	cmd->base.speed		= SPEED_10;
303829ccc49dSPhilippe Reynes 	cmd->base.duplex	= DUPLEX_FULL;
303929ccc49dSPhilippe Reynes 	cmd->base.port		= PORT_TP;
304029ccc49dSPhilippe Reynes 	cmd->base.phy_address	= 0;
304129ccc49dSPhilippe Reynes 	cmd->base.autoneg	= AUTONEG_DISABLE;
30421da177e4SLinus Torvalds 	return 0;
30431da177e4SLinus Torvalds }
30441da177e4SLinus Torvalds 
30451da177e4SLinus Torvalds static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
30461da177e4SLinus Torvalds {
30471da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
30481da177e4SLinus Torvalds 
304933a5ba14SRick Jones 	strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
305033a5ba14SRick Jones 	strlcpy(info->version, DRV_VERSION, sizeof(info->version));
30511da177e4SLinus Torvalds 
30521da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
305340630b82SMichael S. Tsirkin 	case IFF_TUN:
305433a5ba14SRick Jones 		strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
30551da177e4SLinus Torvalds 		break;
305640630b82SMichael S. Tsirkin 	case IFF_TAP:
305733a5ba14SRick Jones 		strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
30581da177e4SLinus Torvalds 		break;
30591da177e4SLinus Torvalds 	}
30601da177e4SLinus Torvalds }
30611da177e4SLinus Torvalds 
30621da177e4SLinus Torvalds static u32 tun_get_msglevel(struct net_device *dev)
30631da177e4SLinus Torvalds {
30641da177e4SLinus Torvalds #ifdef TUN_DEBUG
30651da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
30661da177e4SLinus Torvalds 	return tun->debug;
30671da177e4SLinus Torvalds #else
30681da177e4SLinus Torvalds 	return -EOPNOTSUPP;
30691da177e4SLinus Torvalds #endif
30701da177e4SLinus Torvalds }
30711da177e4SLinus Torvalds 
30721da177e4SLinus Torvalds static void tun_set_msglevel(struct net_device *dev, u32 value)
30731da177e4SLinus Torvalds {
30741da177e4SLinus Torvalds #ifdef TUN_DEBUG
30751da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
30761da177e4SLinus Torvalds 	tun->debug = value;
30771da177e4SLinus Torvalds #endif
30781da177e4SLinus Torvalds }
30791da177e4SLinus Torvalds 
30805503fcecSJason Wang static int tun_get_coalesce(struct net_device *dev,
30815503fcecSJason Wang 			    struct ethtool_coalesce *ec)
30825503fcecSJason Wang {
30835503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
30845503fcecSJason Wang 
30855503fcecSJason Wang 	ec->rx_max_coalesced_frames = tun->rx_batched;
30865503fcecSJason Wang 
30875503fcecSJason Wang 	return 0;
30885503fcecSJason Wang }
30895503fcecSJason Wang 
30905503fcecSJason Wang static int tun_set_coalesce(struct net_device *dev,
30915503fcecSJason Wang 			    struct ethtool_coalesce *ec)
30925503fcecSJason Wang {
30935503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
30945503fcecSJason Wang 
30955503fcecSJason Wang 	if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
30965503fcecSJason Wang 		tun->rx_batched = NAPI_POLL_WEIGHT;
30975503fcecSJason Wang 	else
30985503fcecSJason Wang 		tun->rx_batched = ec->rx_max_coalesced_frames;
30995503fcecSJason Wang 
31005503fcecSJason Wang 	return 0;
31015503fcecSJason Wang }
31025503fcecSJason Wang 
31037282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops = {
31041da177e4SLinus Torvalds 	.get_drvinfo	= tun_get_drvinfo,
31051da177e4SLinus Torvalds 	.get_msglevel	= tun_get_msglevel,
31061da177e4SLinus Torvalds 	.set_msglevel	= tun_set_msglevel,
3107bee31369SNolan Leake 	.get_link	= ethtool_op_get_link,
3108eda29772SRichard Cochran 	.get_ts_info	= ethtool_op_get_ts_info,
31095503fcecSJason Wang 	.get_coalesce   = tun_get_coalesce,
31105503fcecSJason Wang 	.set_coalesce   = tun_set_coalesce,
311129ccc49dSPhilippe Reynes 	.get_link_ksettings = tun_get_link_ksettings,
31121da177e4SLinus Torvalds };
31131da177e4SLinus Torvalds 
31141576d986SJason Wang static int tun_queue_resize(struct tun_struct *tun)
31151576d986SJason Wang {
31161576d986SJason Wang 	struct net_device *dev = tun->dev;
31171576d986SJason Wang 	struct tun_file *tfile;
3118*5990a305SJason Wang 	struct ptr_ring **rings;
31191576d986SJason Wang 	int n = tun->numqueues + tun->numdisabled;
31201576d986SJason Wang 	int ret, i;
31211576d986SJason Wang 
3122*5990a305SJason Wang 	rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
3123*5990a305SJason Wang 	if (!rings)
31241576d986SJason Wang 		return -ENOMEM;
31251576d986SJason Wang 
31261576d986SJason Wang 	for (i = 0; i < tun->numqueues; i++) {
31271576d986SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
3128*5990a305SJason Wang 		rings[i] = &tfile->tx_ring;
31291576d986SJason Wang 	}
31301576d986SJason Wang 	list_for_each_entry(tfile, &tun->disabled, next)
3131*5990a305SJason Wang 		rings[i++] = &tfile->tx_ring;
31321576d986SJason Wang 
3133*5990a305SJason Wang 	ret = ptr_ring_resize_multiple(rings, n,
3134*5990a305SJason Wang 				       dev->tx_queue_len, GFP_KERNEL,
3135*5990a305SJason Wang 				       __skb_array_destroy_skb);
31361576d986SJason Wang 
3137*5990a305SJason Wang 	kfree(rings);
31381576d986SJason Wang 	return ret;
31391576d986SJason Wang }
31401576d986SJason Wang 
31411576d986SJason Wang static int tun_device_event(struct notifier_block *unused,
31421576d986SJason Wang 			    unsigned long event, void *ptr)
31431576d986SJason Wang {
31441576d986SJason Wang 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
31451576d986SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
31461576d986SJason Wang 
314786dfb4acSCraig Gallek 	if (dev->rtnl_link_ops != &tun_link_ops)
314886dfb4acSCraig Gallek 		return NOTIFY_DONE;
314986dfb4acSCraig Gallek 
31501576d986SJason Wang 	switch (event) {
31511576d986SJason Wang 	case NETDEV_CHANGE_TX_QUEUE_LEN:
31521576d986SJason Wang 		if (tun_queue_resize(tun))
31531576d986SJason Wang 			return NOTIFY_BAD;
31541576d986SJason Wang 		break;
31551576d986SJason Wang 	default:
31561576d986SJason Wang 		break;
31571576d986SJason Wang 	}
31581576d986SJason Wang 
31591576d986SJason Wang 	return NOTIFY_DONE;
31601576d986SJason Wang }
31611576d986SJason Wang 
31621576d986SJason Wang static struct notifier_block tun_notifier_block __read_mostly = {
31631576d986SJason Wang 	.notifier_call	= tun_device_event,
31641576d986SJason Wang };
316579d17604SPavel Emelyanov 
31661da177e4SLinus Torvalds static int __init tun_init(void)
31671da177e4SLinus Torvalds {
31681da177e4SLinus Torvalds 	int ret = 0;
31691da177e4SLinus Torvalds 
31706b8a66eeSJoe Perches 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
31711da177e4SLinus Torvalds 
3172f019a7a5SEric W. Biederman 	ret = rtnl_link_register(&tun_link_ops);
317379d17604SPavel Emelyanov 	if (ret) {
31746b8a66eeSJoe Perches 		pr_err("Can't register link_ops\n");
3175f019a7a5SEric W. Biederman 		goto err_linkops;
317679d17604SPavel Emelyanov 	}
317779d17604SPavel Emelyanov 
31781da177e4SLinus Torvalds 	ret = misc_register(&tun_miscdev);
317979d17604SPavel Emelyanov 	if (ret) {
31806b8a66eeSJoe Perches 		pr_err("Can't register misc device %d\n", TUN_MINOR);
318179d17604SPavel Emelyanov 		goto err_misc;
318279d17604SPavel Emelyanov 	}
31831576d986SJason Wang 
31845edfbd3cSTonghao Zhang 	ret = register_netdevice_notifier(&tun_notifier_block);
31855edfbd3cSTonghao Zhang 	if (ret) {
31865edfbd3cSTonghao Zhang 		pr_err("Can't register netdevice notifier\n");
31875edfbd3cSTonghao Zhang 		goto err_notifier;
31885edfbd3cSTonghao Zhang 	}
31895edfbd3cSTonghao Zhang 
319079d17604SPavel Emelyanov 	return  0;
31915edfbd3cSTonghao Zhang 
31925edfbd3cSTonghao Zhang err_notifier:
31935edfbd3cSTonghao Zhang 	misc_deregister(&tun_miscdev);
319479d17604SPavel Emelyanov err_misc:
3195f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
3196f019a7a5SEric W. Biederman err_linkops:
31971da177e4SLinus Torvalds 	return ret;
31981da177e4SLinus Torvalds }
31991da177e4SLinus Torvalds 
32001da177e4SLinus Torvalds static void tun_cleanup(void)
32011da177e4SLinus Torvalds {
32021da177e4SLinus Torvalds 	misc_deregister(&tun_miscdev);
3203f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
32041576d986SJason Wang 	unregister_netdevice_notifier(&tun_notifier_block);
32051da177e4SLinus Torvalds }
32061da177e4SLinus Torvalds 
320705c2828cSMichael S. Tsirkin /* Get an underlying socket object from tun file.  Returns error unless file is
320805c2828cSMichael S. Tsirkin  * attached to a device.  The returned object works like a packet socket, it
320905c2828cSMichael S. Tsirkin  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
321005c2828cSMichael S. Tsirkin  * holding a reference to the file for as long as the socket is in use. */
321105c2828cSMichael S. Tsirkin struct socket *tun_get_socket(struct file *file)
321205c2828cSMichael S. Tsirkin {
32136e914fc7SJason Wang 	struct tun_file *tfile;
321405c2828cSMichael S. Tsirkin 	if (file->f_op != &tun_fops)
321505c2828cSMichael S. Tsirkin 		return ERR_PTR(-EINVAL);
32166e914fc7SJason Wang 	tfile = file->private_data;
32176e914fc7SJason Wang 	if (!tfile)
321805c2828cSMichael S. Tsirkin 		return ERR_PTR(-EBADFD);
321954f968d6SJason Wang 	return &tfile->socket;
322005c2828cSMichael S. Tsirkin }
322105c2828cSMichael S. Tsirkin EXPORT_SYMBOL_GPL(tun_get_socket);
322205c2828cSMichael S. Tsirkin 
3223*5990a305SJason Wang struct ptr_ring *tun_get_tx_ring(struct file *file)
322483339c6bSJason Wang {
322583339c6bSJason Wang 	struct tun_file *tfile;
322683339c6bSJason Wang 
322783339c6bSJason Wang 	if (file->f_op != &tun_fops)
322883339c6bSJason Wang 		return ERR_PTR(-EINVAL);
322983339c6bSJason Wang 	tfile = file->private_data;
323083339c6bSJason Wang 	if (!tfile)
323183339c6bSJason Wang 		return ERR_PTR(-EBADFD);
3232*5990a305SJason Wang 	return &tfile->tx_ring;
323383339c6bSJason Wang }
3234*5990a305SJason Wang EXPORT_SYMBOL_GPL(tun_get_tx_ring);
323583339c6bSJason Wang 
32361da177e4SLinus Torvalds module_init(tun_init);
32371da177e4SLinus Torvalds module_exit(tun_cleanup);
32381da177e4SLinus Torvalds MODULE_DESCRIPTION(DRV_DESCRIPTION);
32391da177e4SLinus Torvalds MODULE_AUTHOR(DRV_COPYRIGHT);
32401da177e4SLinus Torvalds MODULE_LICENSE("GPL");
32411da177e4SLinus Torvalds MODULE_ALIAS_MISCDEV(TUN_MINOR);
3242578454ffSKay Sievers MODULE_ALIAS("devname:net/tun");
3243