xref: /openbmc/linux/drivers/net/tun.c (revision 1ffcbc8537d0bc32aaca7000cb9c904ec4b6300f)
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>
81f2780d6dSKirill Tkhai #include <linux/proc_fs.h>
821da177e4SLinus Torvalds 
8314daa021SRusty Russell /* Uncomment to enable debugging */
8414daa021SRusty Russell /* #define TUN_DEBUG 1 */
8514daa021SRusty Russell 
861da177e4SLinus Torvalds #ifdef TUN_DEBUG
871da177e4SLinus Torvalds static int debug;
8814daa021SRusty Russell 
896b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
906b8a66eeSJoe Perches do {								\
916b8a66eeSJoe Perches 	if (tun->debug)						\
926b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
936b8a66eeSJoe Perches } while (0)
946b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
956b8a66eeSJoe Perches do {								\
966b8a66eeSJoe Perches 	if (debug == 2)						\
976b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
986b8a66eeSJoe Perches } while (0)
9914daa021SRusty Russell #else
1006b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
1016b8a66eeSJoe Perches do {								\
1026b8a66eeSJoe Perches 	if (0)							\
1036b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
1046b8a66eeSJoe Perches } while (0)
1056b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
1066b8a66eeSJoe Perches do {								\
1076b8a66eeSJoe Perches 	if (0)							\
1086b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
1096b8a66eeSJoe Perches } while (0)
1101da177e4SLinus Torvalds #endif
1111da177e4SLinus Torvalds 
112761876c8SJason Wang #define TUN_HEADROOM 256
1137df13219SJason Wang #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
11466ccbc9cSJason Wang 
115031f5e03SMichael S. Tsirkin /* TUN device flags */
116031f5e03SMichael S. Tsirkin 
117031f5e03SMichael S. Tsirkin /* IFF_ATTACH_QUEUE is never stored in device flags,
118031f5e03SMichael S. Tsirkin  * overload it to mean fasync when stored there.
119031f5e03SMichael S. Tsirkin  */
120031f5e03SMichael S. Tsirkin #define TUN_FASYNC	IFF_ATTACH_QUEUE
1211cf8e410SMichael S. Tsirkin /* High bits in flags field are unused. */
1221cf8e410SMichael S. Tsirkin #define TUN_VNET_LE     0x80000000
1238b8e658bSGreg Kurz #define TUN_VNET_BE     0x40000000
124031f5e03SMichael S. Tsirkin 
125031f5e03SMichael S. Tsirkin #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
12690e33d45SPetar Penkov 		      IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
12790e33d45SPetar Penkov 
1280690899bSMichael S. Tsirkin #define GOODCOPY_LEN 128
1290690899bSMichael S. Tsirkin 
130f271b2ccSMax Krasnyansky #define FLT_EXACT_COUNT 8
131f271b2ccSMax Krasnyansky struct tap_filter {
132f271b2ccSMax Krasnyansky 	unsigned int    count;    /* Number of addrs. Zero means disabled */
133f271b2ccSMax Krasnyansky 	u32             mask[2];  /* Mask of the hashed addrs */
134f271b2ccSMax Krasnyansky 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
135f271b2ccSMax Krasnyansky };
136f271b2ccSMax Krasnyansky 
137baf71c5cSPankaj Gupta /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
138baf71c5cSPankaj Gupta  * to max number of VCPUs in guest. */
139baf71c5cSPankaj Gupta #define MAX_TAP_QUEUES 256
140b8732fb7SJason Wang #define MAX_TAP_FLOWS  4096
141c8d68e6bSJason Wang 
14296442e42SJason Wang #define TUN_FLOW_EXPIRE (3 * HZ)
14396442e42SJason Wang 
144608b9977SPaolo Abeni struct tun_pcpu_stats {
145608b9977SPaolo Abeni 	u64 rx_packets;
146608b9977SPaolo Abeni 	u64 rx_bytes;
147608b9977SPaolo Abeni 	u64 tx_packets;
148608b9977SPaolo Abeni 	u64 tx_bytes;
149608b9977SPaolo Abeni 	struct u64_stats_sync syncp;
150608b9977SPaolo Abeni 	u32 rx_dropped;
151608b9977SPaolo Abeni 	u32 tx_dropped;
152608b9977SPaolo Abeni 	u32 rx_frame_errors;
153608b9977SPaolo Abeni };
154608b9977SPaolo Abeni 
15554f968d6SJason Wang /* A tun_file connects an open character device to a tuntap netdevice. It
15692d4ea6eSstephen hemminger  * also contains all socket related structures (except sock_fprog and tap_filter)
15754f968d6SJason Wang  * to serve as one transmit queue for tuntap device. The sock_fprog and
15854f968d6SJason Wang  * tap_filter were kept in tun_struct since they were used for filtering for the
15936fe8c09SRami Rosen  * netdevice not for a specific queue (at least I didn't see the requirement for
16054f968d6SJason Wang  * this).
1616e914fc7SJason Wang  *
1626e914fc7SJason Wang  * RCU usage:
16336fe8c09SRami Rosen  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
1646e914fc7SJason Wang  * other can only be read while rcu_read_lock or rtnl_lock is held.
16554f968d6SJason Wang  */
166631ab46bSEric W. Biederman struct tun_file {
16754f968d6SJason Wang 	struct sock sk;
16854f968d6SJason Wang 	struct socket socket;
16954f968d6SJason Wang 	struct socket_wq wq;
1706e914fc7SJason Wang 	struct tun_struct __rcu *tun;
17154f968d6SJason Wang 	struct fasync_struct *fasync;
17254f968d6SJason Wang 	/* only used for fasnyc */
17354f968d6SJason Wang 	unsigned int flags;
174fb7589a1SPavel Emelyanov 	union {
175c8d68e6bSJason Wang 		u16 queue_index;
176fb7589a1SPavel Emelyanov 		unsigned int ifindex;
177fb7589a1SPavel Emelyanov 	};
17894317099SPetar Penkov 	struct napi_struct napi;
179aec72f33SEric Dumazet 	bool napi_enabled;
18090e33d45SPetar Penkov 	struct mutex napi_mutex;	/* Protects access to the above napi */
1814008e97fSJason Wang 	struct list_head next;
1824008e97fSJason Wang 	struct tun_struct *detached;
1835990a305SJason Wang 	struct ptr_ring tx_ring;
1848bf5c4eeSJesper Dangaard Brouer 	struct xdp_rxq_info xdp_rxq;
185631ab46bSEric W. Biederman };
186631ab46bSEric W. Biederman 
18796442e42SJason Wang struct tun_flow_entry {
18896442e42SJason Wang 	struct hlist_node hash_link;
18996442e42SJason Wang 	struct rcu_head rcu;
19096442e42SJason Wang 	struct tun_struct *tun;
19196442e42SJason Wang 
19296442e42SJason Wang 	u32 rxhash;
1939bc88939STom Herbert 	u32 rps_rxhash;
19496442e42SJason Wang 	int queue_index;
19596442e42SJason Wang 	unsigned long updated;
19696442e42SJason Wang };
19796442e42SJason Wang 
19896442e42SJason Wang #define TUN_NUM_FLOW_ENTRIES 1024
19996442e42SJason Wang 
200cd5681d7SJason Wang struct tun_prog {
20196f84061SJason Wang 	struct rcu_head rcu;
20296f84061SJason Wang 	struct bpf_prog *prog;
20396f84061SJason Wang };
20496f84061SJason Wang 
20554f968d6SJason Wang /* Since the socket were moved to tun_file, to preserve the behavior of persist
20636fe8c09SRami Rosen  * device, socket filter, sndbuf and vnet header size were restore when the
20754f968d6SJason Wang  * file were attached to a persist device.
20854f968d6SJason Wang  */
20914daa021SRusty Russell struct tun_struct {
210c8d68e6bSJason Wang 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
211c8d68e6bSJason Wang 	unsigned int            numqueues;
212f271b2ccSMax Krasnyansky 	unsigned int 		flags;
2130625c883SEric W. Biederman 	kuid_t			owner;
2140625c883SEric W. Biederman 	kgid_t			group;
21514daa021SRusty Russell 
21614daa021SRusty Russell 	struct net_device	*dev;
217c8f44affSMichał Mirosław 	netdev_features_t	set_features;
21888255375SMichał Mirosław #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
219d591a1f3SDavid S. Miller 			  NETIF_F_TSO6)
220d9d52b51SMichael S. Tsirkin 
221eaea34b2SPaolo Abeni 	int			align;
222d9d52b51SMichael S. Tsirkin 	int			vnet_hdr_sz;
22354f968d6SJason Wang 	int			sndbuf;
22454f968d6SJason Wang 	struct tap_filter	txflt;
22554f968d6SJason Wang 	struct sock_fprog	fprog;
22654f968d6SJason Wang 	/* protected by rtnl lock */
22754f968d6SJason Wang 	bool			filter_attached;
22814daa021SRusty Russell #ifdef TUN_DEBUG
22914daa021SRusty Russell 	int debug;
23014daa021SRusty Russell #endif
23196442e42SJason Wang 	spinlock_t lock;
23296442e42SJason Wang 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
23396442e42SJason Wang 	struct timer_list flow_gc_timer;
23496442e42SJason Wang 	unsigned long ageing_time;
2354008e97fSJason Wang 	unsigned int numdisabled;
2364008e97fSJason Wang 	struct list_head disabled;
2375dbbaf2dSPaul Moore 	void *security;
238b8732fb7SJason Wang 	u32 flow_count;
2395503fcecSJason Wang 	u32 rx_batched;
240608b9977SPaolo Abeni 	struct tun_pcpu_stats __percpu *pcpu_stats;
241761876c8SJason Wang 	struct bpf_prog __rcu *xdp_prog;
242cd5681d7SJason Wang 	struct tun_prog __rcu *steering_prog;
243aff3d70aSJason Wang 	struct tun_prog __rcu *filter_prog;
24414daa021SRusty Russell };
24514daa021SRusty Russell 
246aff3d70aSJason Wang struct veth {
247aff3d70aSJason Wang 	__be16 h_vlan_proto;
248aff3d70aSJason Wang 	__be16 h_vlan_TCI;
2491da177e4SLinus Torvalds };
2501da177e4SLinus Torvalds 
251*1ffcbc85SJesper Dangaard Brouer bool tun_is_xdp_frame(void *ptr)
252fc72d1d5SJason Wang {
253fc72d1d5SJason Wang 	return (unsigned long)ptr & TUN_XDP_FLAG;
254fc72d1d5SJason Wang }
255*1ffcbc85SJesper Dangaard Brouer EXPORT_SYMBOL(tun_is_xdp_frame);
256fc72d1d5SJason Wang 
257fc72d1d5SJason Wang void *tun_xdp_to_ptr(void *ptr)
258fc72d1d5SJason Wang {
259fc72d1d5SJason Wang 	return (void *)((unsigned long)ptr | TUN_XDP_FLAG);
260fc72d1d5SJason Wang }
261fc72d1d5SJason Wang EXPORT_SYMBOL(tun_xdp_to_ptr);
262fc72d1d5SJason Wang 
263fc72d1d5SJason Wang void *tun_ptr_to_xdp(void *ptr)
264fc72d1d5SJason Wang {
265fc72d1d5SJason Wang 	return (void *)((unsigned long)ptr & ~TUN_XDP_FLAG);
266fc72d1d5SJason Wang }
267fc72d1d5SJason Wang EXPORT_SYMBOL(tun_ptr_to_xdp);
268fc72d1d5SJason Wang 
26994317099SPetar Penkov static int tun_napi_receive(struct napi_struct *napi, int budget)
27094317099SPetar Penkov {
27194317099SPetar Penkov 	struct tun_file *tfile = container_of(napi, struct tun_file, napi);
27294317099SPetar Penkov 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
27394317099SPetar Penkov 	struct sk_buff_head process_queue;
27494317099SPetar Penkov 	struct sk_buff *skb;
27594317099SPetar Penkov 	int received = 0;
27694317099SPetar Penkov 
27794317099SPetar Penkov 	__skb_queue_head_init(&process_queue);
27894317099SPetar Penkov 
27994317099SPetar Penkov 	spin_lock(&queue->lock);
28094317099SPetar Penkov 	skb_queue_splice_tail_init(queue, &process_queue);
28194317099SPetar Penkov 	spin_unlock(&queue->lock);
28294317099SPetar Penkov 
28394317099SPetar Penkov 	while (received < budget && (skb = __skb_dequeue(&process_queue))) {
28494317099SPetar Penkov 		napi_gro_receive(napi, skb);
28594317099SPetar Penkov 		++received;
28694317099SPetar Penkov 	}
28794317099SPetar Penkov 
28894317099SPetar Penkov 	if (!skb_queue_empty(&process_queue)) {
28994317099SPetar Penkov 		spin_lock(&queue->lock);
29094317099SPetar Penkov 		skb_queue_splice(&process_queue, queue);
29194317099SPetar Penkov 		spin_unlock(&queue->lock);
29294317099SPetar Penkov 	}
29394317099SPetar Penkov 
29494317099SPetar Penkov 	return received;
29594317099SPetar Penkov }
29694317099SPetar Penkov 
29794317099SPetar Penkov static int tun_napi_poll(struct napi_struct *napi, int budget)
29894317099SPetar Penkov {
29994317099SPetar Penkov 	unsigned int received;
30094317099SPetar Penkov 
30194317099SPetar Penkov 	received = tun_napi_receive(napi, budget);
30294317099SPetar Penkov 
30394317099SPetar Penkov 	if (received < budget)
30494317099SPetar Penkov 		napi_complete_done(napi, received);
30594317099SPetar Penkov 
30694317099SPetar Penkov 	return received;
30794317099SPetar Penkov }
30894317099SPetar Penkov 
30994317099SPetar Penkov static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
31094317099SPetar Penkov 			  bool napi_en)
31194317099SPetar Penkov {
312aec72f33SEric Dumazet 	tfile->napi_enabled = napi_en;
31394317099SPetar Penkov 	if (napi_en) {
31494317099SPetar Penkov 		netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
31594317099SPetar Penkov 			       NAPI_POLL_WEIGHT);
31694317099SPetar Penkov 		napi_enable(&tfile->napi);
31790e33d45SPetar Penkov 		mutex_init(&tfile->napi_mutex);
31894317099SPetar Penkov 	}
31994317099SPetar Penkov }
32094317099SPetar Penkov 
32194317099SPetar Penkov static void tun_napi_disable(struct tun_struct *tun, struct tun_file *tfile)
32294317099SPetar Penkov {
323aec72f33SEric Dumazet 	if (tfile->napi_enabled)
32494317099SPetar Penkov 		napi_disable(&tfile->napi);
32594317099SPetar Penkov }
32694317099SPetar Penkov 
32794317099SPetar Penkov static void tun_napi_del(struct tun_struct *tun, struct tun_file *tfile)
32894317099SPetar Penkov {
329aec72f33SEric Dumazet 	if (tfile->napi_enabled)
33094317099SPetar Penkov 		netif_napi_del(&tfile->napi);
33194317099SPetar Penkov }
33294317099SPetar Penkov 
33390e33d45SPetar Penkov static bool tun_napi_frags_enabled(const struct tun_struct *tun)
33490e33d45SPetar Penkov {
33590e33d45SPetar Penkov 	return READ_ONCE(tun->flags) & IFF_NAPI_FRAGS;
33690e33d45SPetar Penkov }
33790e33d45SPetar Penkov 
3388b8e658bSGreg Kurz #ifdef CONFIG_TUN_VNET_CROSS_LE
3398b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3408b8e658bSGreg Kurz {
3418b8e658bSGreg Kurz 	return tun->flags & TUN_VNET_BE ? false :
3428b8e658bSGreg Kurz 		virtio_legacy_is_little_endian();
3438b8e658bSGreg Kurz }
3448b8e658bSGreg Kurz 
3458b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3468b8e658bSGreg Kurz {
3478b8e658bSGreg Kurz 	int be = !!(tun->flags & TUN_VNET_BE);
3488b8e658bSGreg Kurz 
3498b8e658bSGreg Kurz 	if (put_user(be, argp))
3508b8e658bSGreg Kurz 		return -EFAULT;
3518b8e658bSGreg Kurz 
3528b8e658bSGreg Kurz 	return 0;
3538b8e658bSGreg Kurz }
3548b8e658bSGreg Kurz 
3558b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3568b8e658bSGreg Kurz {
3578b8e658bSGreg Kurz 	int be;
3588b8e658bSGreg Kurz 
3598b8e658bSGreg Kurz 	if (get_user(be, argp))
3608b8e658bSGreg Kurz 		return -EFAULT;
3618b8e658bSGreg Kurz 
3628b8e658bSGreg Kurz 	if (be)
3638b8e658bSGreg Kurz 		tun->flags |= TUN_VNET_BE;
3648b8e658bSGreg Kurz 	else
3658b8e658bSGreg Kurz 		tun->flags &= ~TUN_VNET_BE;
3668b8e658bSGreg Kurz 
3678b8e658bSGreg Kurz 	return 0;
3688b8e658bSGreg Kurz }
3698b8e658bSGreg Kurz #else
3708b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3718b8e658bSGreg Kurz {
3728b8e658bSGreg Kurz 	return virtio_legacy_is_little_endian();
3738b8e658bSGreg Kurz }
3748b8e658bSGreg Kurz 
3758b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3768b8e658bSGreg Kurz {
3778b8e658bSGreg Kurz 	return -EINVAL;
3788b8e658bSGreg Kurz }
3798b8e658bSGreg Kurz 
3808b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3818b8e658bSGreg Kurz {
3828b8e658bSGreg Kurz 	return -EINVAL;
3838b8e658bSGreg Kurz }
3848b8e658bSGreg Kurz #endif /* CONFIG_TUN_VNET_CROSS_LE */
3858b8e658bSGreg Kurz 
38625bd55bbSGreg Kurz static inline bool tun_is_little_endian(struct tun_struct *tun)
38725bd55bbSGreg Kurz {
3887d824109SGreg Kurz 	return tun->flags & TUN_VNET_LE ||
3898b8e658bSGreg Kurz 		tun_legacy_is_little_endian(tun);
39025bd55bbSGreg Kurz }
39125bd55bbSGreg Kurz 
39256f0dcc5SMichael S. Tsirkin static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
39356f0dcc5SMichael S. Tsirkin {
39425bd55bbSGreg Kurz 	return __virtio16_to_cpu(tun_is_little_endian(tun), val);
39556f0dcc5SMichael S. Tsirkin }
39656f0dcc5SMichael S. Tsirkin 
39756f0dcc5SMichael S. Tsirkin static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
39856f0dcc5SMichael S. Tsirkin {
39925bd55bbSGreg Kurz 	return __cpu_to_virtio16(tun_is_little_endian(tun), val);
40056f0dcc5SMichael S. Tsirkin }
40156f0dcc5SMichael S. Tsirkin 
40296442e42SJason Wang static inline u32 tun_hashfn(u32 rxhash)
40396442e42SJason Wang {
40496442e42SJason Wang 	return rxhash & 0x3ff;
40596442e42SJason Wang }
40696442e42SJason Wang 
40796442e42SJason Wang static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
40896442e42SJason Wang {
40996442e42SJason Wang 	struct tun_flow_entry *e;
41096442e42SJason Wang 
411b67bfe0dSSasha Levin 	hlist_for_each_entry_rcu(e, head, hash_link) {
41296442e42SJason Wang 		if (e->rxhash == rxhash)
41396442e42SJason Wang 			return e;
41496442e42SJason Wang 	}
41596442e42SJason Wang 	return NULL;
41696442e42SJason Wang }
41796442e42SJason Wang 
41896442e42SJason Wang static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
41996442e42SJason Wang 					      struct hlist_head *head,
42096442e42SJason Wang 					      u32 rxhash, u16 queue_index)
42196442e42SJason Wang {
4229fdc6befSEric Dumazet 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
4239fdc6befSEric Dumazet 
42496442e42SJason Wang 	if (e) {
42596442e42SJason Wang 		tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
42696442e42SJason Wang 			  rxhash, queue_index);
42796442e42SJason Wang 		e->updated = jiffies;
42896442e42SJason Wang 		e->rxhash = rxhash;
4299bc88939STom Herbert 		e->rps_rxhash = 0;
43096442e42SJason Wang 		e->queue_index = queue_index;
43196442e42SJason Wang 		e->tun = tun;
43296442e42SJason Wang 		hlist_add_head_rcu(&e->hash_link, head);
433b8732fb7SJason Wang 		++tun->flow_count;
43496442e42SJason Wang 	}
43596442e42SJason Wang 	return e;
43696442e42SJason Wang }
43796442e42SJason Wang 
43896442e42SJason Wang static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
43996442e42SJason Wang {
44096442e42SJason Wang 	tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
44196442e42SJason Wang 		  e->rxhash, e->queue_index);
44296442e42SJason Wang 	hlist_del_rcu(&e->hash_link);
4439fdc6befSEric Dumazet 	kfree_rcu(e, rcu);
444b8732fb7SJason Wang 	--tun->flow_count;
44596442e42SJason Wang }
44696442e42SJason Wang 
44796442e42SJason Wang static void tun_flow_flush(struct tun_struct *tun)
44896442e42SJason Wang {
44996442e42SJason Wang 	int i;
45096442e42SJason Wang 
45196442e42SJason Wang 	spin_lock_bh(&tun->lock);
45296442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
45396442e42SJason Wang 		struct tun_flow_entry *e;
454b67bfe0dSSasha Levin 		struct hlist_node *n;
45596442e42SJason Wang 
456b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
45796442e42SJason Wang 			tun_flow_delete(tun, e);
45896442e42SJason Wang 	}
45996442e42SJason Wang 	spin_unlock_bh(&tun->lock);
46096442e42SJason Wang }
46196442e42SJason Wang 
46296442e42SJason Wang static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
46396442e42SJason Wang {
46496442e42SJason Wang 	int i;
46596442e42SJason Wang 
46696442e42SJason Wang 	spin_lock_bh(&tun->lock);
46796442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
46896442e42SJason Wang 		struct tun_flow_entry *e;
469b67bfe0dSSasha Levin 		struct hlist_node *n;
47096442e42SJason Wang 
471b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
47296442e42SJason Wang 			if (e->queue_index == queue_index)
47396442e42SJason Wang 				tun_flow_delete(tun, e);
47496442e42SJason Wang 		}
47596442e42SJason Wang 	}
47696442e42SJason Wang 	spin_unlock_bh(&tun->lock);
47796442e42SJason Wang }
47896442e42SJason Wang 
479e99e88a9SKees Cook static void tun_flow_cleanup(struct timer_list *t)
48096442e42SJason Wang {
481e99e88a9SKees Cook 	struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
48296442e42SJason Wang 	unsigned long delay = tun->ageing_time;
48396442e42SJason Wang 	unsigned long next_timer = jiffies + delay;
48496442e42SJason Wang 	unsigned long count = 0;
48596442e42SJason Wang 	int i;
48696442e42SJason Wang 
48796442e42SJason Wang 	tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
48896442e42SJason Wang 
4897dbfb4efSEric Dumazet 	spin_lock(&tun->lock);
49096442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
49196442e42SJason Wang 		struct tun_flow_entry *e;
492b67bfe0dSSasha Levin 		struct hlist_node *n;
49396442e42SJason Wang 
494b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
49596442e42SJason Wang 			unsigned long this_timer;
49681d98fa4SEric Dumazet 
49796442e42SJason Wang 			this_timer = e->updated + delay;
49881d98fa4SEric Dumazet 			if (time_before_eq(this_timer, jiffies)) {
49996442e42SJason Wang 				tun_flow_delete(tun, e);
50081d98fa4SEric Dumazet 				continue;
50181d98fa4SEric Dumazet 			}
50281d98fa4SEric Dumazet 			count++;
50381d98fa4SEric Dumazet 			if (time_before(this_timer, next_timer))
50496442e42SJason Wang 				next_timer = this_timer;
50596442e42SJason Wang 		}
50696442e42SJason Wang 	}
50796442e42SJason Wang 
50896442e42SJason Wang 	if (count)
50996442e42SJason Wang 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
5107dbfb4efSEric Dumazet 	spin_unlock(&tun->lock);
51196442e42SJason Wang }
51296442e42SJason Wang 
51349974420SEric Dumazet static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
5149e85722dSJason Wang 			    struct tun_file *tfile)
51596442e42SJason Wang {
51696442e42SJason Wang 	struct hlist_head *head;
51796442e42SJason Wang 	struct tun_flow_entry *e;
51896442e42SJason Wang 	unsigned long delay = tun->ageing_time;
5199e85722dSJason Wang 	u16 queue_index = tfile->queue_index;
52096442e42SJason Wang 
52196442e42SJason Wang 	if (!rxhash)
52296442e42SJason Wang 		return;
52396442e42SJason Wang 	else
52496442e42SJason Wang 		head = &tun->flows[tun_hashfn(rxhash)];
52596442e42SJason Wang 
52696442e42SJason Wang 	rcu_read_lock();
52796442e42SJason Wang 
5289e85722dSJason Wang 	/* We may get a very small possibility of OOO during switching, not
5299e85722dSJason Wang 	 * worth to optimize.*/
5309e85722dSJason Wang 	if (tun->numqueues == 1 || tfile->detached)
53196442e42SJason Wang 		goto unlock;
53296442e42SJason Wang 
53396442e42SJason Wang 	e = tun_flow_find(head, rxhash);
53496442e42SJason Wang 	if (likely(e)) {
53596442e42SJason Wang 		/* TODO: keep queueing to old queue until it's empty? */
53696442e42SJason Wang 		e->queue_index = queue_index;
53796442e42SJason Wang 		e->updated = jiffies;
5389bc88939STom Herbert 		sock_rps_record_flow_hash(e->rps_rxhash);
53996442e42SJason Wang 	} else {
54096442e42SJason Wang 		spin_lock_bh(&tun->lock);
541b8732fb7SJason Wang 		if (!tun_flow_find(head, rxhash) &&
542b8732fb7SJason Wang 		    tun->flow_count < MAX_TAP_FLOWS)
54396442e42SJason Wang 			tun_flow_create(tun, head, rxhash, queue_index);
54496442e42SJason Wang 
54596442e42SJason Wang 		if (!timer_pending(&tun->flow_gc_timer))
54696442e42SJason Wang 			mod_timer(&tun->flow_gc_timer,
54796442e42SJason Wang 				  round_jiffies_up(jiffies + delay));
54896442e42SJason Wang 		spin_unlock_bh(&tun->lock);
54996442e42SJason Wang 	}
55096442e42SJason Wang 
55196442e42SJason Wang unlock:
55296442e42SJason Wang 	rcu_read_unlock();
55396442e42SJason Wang }
55496442e42SJason Wang 
5559bc88939STom Herbert /**
5569bc88939STom Herbert  * Save the hash received in the stack receive path and update the
5579bc88939STom Herbert  * flow_hash table accordingly.
5589bc88939STom Herbert  */
5599bc88939STom Herbert static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
5609bc88939STom Herbert {
561567e4b79SEric Dumazet 	if (unlikely(e->rps_rxhash != hash))
5629bc88939STom Herbert 		e->rps_rxhash = hash;
5639bc88939STom Herbert }
5649bc88939STom Herbert 
565c8d68e6bSJason Wang /* We try to identify a flow through its rxhash first. The reason that
56692d4ea6eSstephen hemminger  * we do not check rxq no. is because some cards(e.g 82599), chooses
567c8d68e6bSJason Wang  * the rxq based on the txq where the last packet of the flow comes. As
568c8d68e6bSJason Wang  * the userspace application move between processors, we may get a
569c8d68e6bSJason Wang  * different rxq no. here. If we could not get rxhash, then we would
570c8d68e6bSJason Wang  * hope the rxq no. may help here.
571c8d68e6bSJason Wang  */
57296f84061SJason Wang static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
573c8d68e6bSJason Wang {
57496442e42SJason Wang 	struct tun_flow_entry *e;
575c8d68e6bSJason Wang 	u32 txq = 0;
576c8d68e6bSJason Wang 	u32 numqueues = 0;
577c8d68e6bSJason Wang 
5786aa7de05SMark Rutland 	numqueues = READ_ONCE(tun->numqueues);
579c8d68e6bSJason Wang 
580feec084aSJason Wang 	txq = __skb_get_hash_symmetric(skb);
581c8d68e6bSJason Wang 	if (txq) {
58296442e42SJason Wang 		e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
5839bc88939STom Herbert 		if (e) {
5849bc88939STom Herbert 			tun_flow_save_rps_rxhash(e, txq);
585fbe4d456SZhi Yong Wu 			txq = e->queue_index;
5869bc88939STom Herbert 		} else
587c8d68e6bSJason Wang 			/* use multiply and shift instead of expensive divide */
588c8d68e6bSJason Wang 			txq = ((u64)txq * numqueues) >> 32;
589c8d68e6bSJason Wang 	} else if (likely(skb_rx_queue_recorded(skb))) {
590c8d68e6bSJason Wang 		txq = skb_get_rx_queue(skb);
591c8d68e6bSJason Wang 		while (unlikely(txq >= numqueues))
592c8d68e6bSJason Wang 			txq -= numqueues;
593c8d68e6bSJason Wang 	}
594c8d68e6bSJason Wang 
595c8d68e6bSJason Wang 	return txq;
596c8d68e6bSJason Wang }
597c8d68e6bSJason Wang 
59896f84061SJason Wang static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
59996f84061SJason Wang {
600cd5681d7SJason Wang 	struct tun_prog *prog;
60196f84061SJason Wang 	u16 ret = 0;
60296f84061SJason Wang 
60396f84061SJason Wang 	prog = rcu_dereference(tun->steering_prog);
60496f84061SJason Wang 	if (prog)
60596f84061SJason Wang 		ret = bpf_prog_run_clear_cb(prog->prog, skb);
60696f84061SJason Wang 
60796f84061SJason Wang 	return ret % tun->numqueues;
60896f84061SJason Wang }
60996f84061SJason Wang 
61096f84061SJason Wang static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
61196f84061SJason Wang 			    void *accel_priv, select_queue_fallback_t fallback)
61296f84061SJason Wang {
61396f84061SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
61496f84061SJason Wang 	u16 ret;
61596f84061SJason Wang 
61696f84061SJason Wang 	rcu_read_lock();
61796f84061SJason Wang 	if (rcu_dereference(tun->steering_prog))
61896f84061SJason Wang 		ret = tun_ebpf_select_queue(tun, skb);
61996f84061SJason Wang 	else
62096f84061SJason Wang 		ret = tun_automq_select_queue(tun, skb);
62196f84061SJason Wang 	rcu_read_unlock();
62296f84061SJason Wang 
62396f84061SJason Wang 	return ret;
62496f84061SJason Wang }
62596f84061SJason Wang 
626cde8b15fSJason Wang static inline bool tun_not_capable(struct tun_struct *tun)
627cde8b15fSJason Wang {
628cde8b15fSJason Wang 	const struct cred *cred = current_cred();
629c260b772SEric W. Biederman 	struct net *net = dev_net(tun->dev);
630cde8b15fSJason Wang 
631cde8b15fSJason Wang 	return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
632cde8b15fSJason Wang 		  (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
633c260b772SEric W. Biederman 		!ns_capable(net->user_ns, CAP_NET_ADMIN);
634cde8b15fSJason Wang }
635cde8b15fSJason Wang 
636c8d68e6bSJason Wang static void tun_set_real_num_queues(struct tun_struct *tun)
637c8d68e6bSJason Wang {
638c8d68e6bSJason Wang 	netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
639c8d68e6bSJason Wang 	netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
640c8d68e6bSJason Wang }
641c8d68e6bSJason Wang 
6424008e97fSJason Wang static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
6434008e97fSJason Wang {
6444008e97fSJason Wang 	tfile->detached = tun;
6454008e97fSJason Wang 	list_add_tail(&tfile->next, &tun->disabled);
6464008e97fSJason Wang 	++tun->numdisabled;
6474008e97fSJason Wang }
6484008e97fSJason Wang 
649d32649d1SJason Wang static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
6504008e97fSJason Wang {
6514008e97fSJason Wang 	struct tun_struct *tun = tfile->detached;
6524008e97fSJason Wang 
6534008e97fSJason Wang 	tfile->detached = NULL;
6544008e97fSJason Wang 	list_del_init(&tfile->next);
6554008e97fSJason Wang 	--tun->numdisabled;
6564008e97fSJason Wang 	return tun;
6574008e97fSJason Wang }
6584008e97fSJason Wang 
6593a403076SJason Wang void tun_ptr_free(void *ptr)
660fc72d1d5SJason Wang {
661fc72d1d5SJason Wang 	if (!ptr)
662fc72d1d5SJason Wang 		return;
663*1ffcbc85SJesper Dangaard Brouer 	if (tun_is_xdp_frame(ptr)) {
664*1ffcbc85SJesper Dangaard Brouer 		struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
665fc72d1d5SJason Wang 
666*1ffcbc85SJesper Dangaard Brouer 		xdp_return_frame(xdpf->data, &xdpf->mem);
667fc72d1d5SJason Wang 	} else {
668fc72d1d5SJason Wang 		__skb_array_destroy_skb(ptr);
669fc72d1d5SJason Wang 	}
670fc72d1d5SJason Wang }
6713a403076SJason Wang EXPORT_SYMBOL_GPL(tun_ptr_free);
672fc72d1d5SJason Wang 
6734bfb0513SJason Wang static void tun_queue_purge(struct tun_file *tfile)
6744bfb0513SJason Wang {
675fc72d1d5SJason Wang 	void *ptr;
6761576d986SJason Wang 
677fc72d1d5SJason Wang 	while ((ptr = ptr_ring_consume(&tfile->tx_ring)) != NULL)
678fc72d1d5SJason Wang 		tun_ptr_free(ptr);
6791576d986SJason Wang 
6805503fcecSJason Wang 	skb_queue_purge(&tfile->sk.sk_write_queue);
6814bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_error_queue);
6824bfb0513SJason Wang }
6834bfb0513SJason Wang 
6848565d26bSDavid S. Miller static void tun_cleanup_tx_ring(struct tun_file *tfile)
6854df0bfc7SCong Wang {
6868565d26bSDavid S. Miller 	if (tfile->tx_ring.queue) {
6878565d26bSDavid S. Miller 		ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
6888565d26bSDavid S. Miller 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
6898565d26bSDavid S. Miller 		memset(&tfile->tx_ring, 0, sizeof(tfile->tx_ring));
6904df0bfc7SCong Wang 	}
6914df0bfc7SCong Wang }
6924df0bfc7SCong Wang 
693c8d68e6bSJason Wang static void __tun_detach(struct tun_file *tfile, bool clean)
694c8d68e6bSJason Wang {
695c8d68e6bSJason Wang 	struct tun_file *ntfile;
696c8d68e6bSJason Wang 	struct tun_struct *tun;
697c8d68e6bSJason Wang 
698b8deabd3SJason Wang 	tun = rtnl_dereference(tfile->tun);
699b8deabd3SJason Wang 
70094317099SPetar Penkov 	if (tun && clean) {
70194317099SPetar Penkov 		tun_napi_disable(tun, tfile);
70294317099SPetar Penkov 		tun_napi_del(tun, tfile);
70394317099SPetar Penkov 	}
70494317099SPetar Penkov 
7059e85722dSJason Wang 	if (tun && !tfile->detached) {
706c8d68e6bSJason Wang 		u16 index = tfile->queue_index;
707c8d68e6bSJason Wang 		BUG_ON(index >= tun->numqueues);
708c8d68e6bSJason Wang 
709c8d68e6bSJason Wang 		rcu_assign_pointer(tun->tfiles[index],
710c8d68e6bSJason Wang 				   tun->tfiles[tun->numqueues - 1]);
711b8deabd3SJason Wang 		ntfile = rtnl_dereference(tun->tfiles[index]);
712c8d68e6bSJason Wang 		ntfile->queue_index = index;
713c8d68e6bSJason Wang 
714c8d68e6bSJason Wang 		--tun->numqueues;
7159e85722dSJason Wang 		if (clean) {
716c956674bSMonam Agarwal 			RCU_INIT_POINTER(tfile->tun, NULL);
717c8d68e6bSJason Wang 			sock_put(&tfile->sk);
7189e85722dSJason Wang 		} else
7194008e97fSJason Wang 			tun_disable_queue(tun, tfile);
720c8d68e6bSJason Wang 
721c8d68e6bSJason Wang 		synchronize_net();
72296442e42SJason Wang 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
723c8d68e6bSJason Wang 		/* Drop read queue */
7244bfb0513SJason Wang 		tun_queue_purge(tfile);
725c8d68e6bSJason Wang 		tun_set_real_num_queues(tun);
726dd38bd85SJason Wang 	} else if (tfile->detached && clean) {
7274008e97fSJason Wang 		tun = tun_enable_queue(tfile);
728dd38bd85SJason Wang 		sock_put(&tfile->sk);
729dd38bd85SJason Wang 	}
730c8d68e6bSJason Wang 
731c8d68e6bSJason Wang 	if (clean) {
732af668b3cSMichael S. Tsirkin 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
733af668b3cSMichael S. Tsirkin 			netif_carrier_off(tun->dev);
734af668b3cSMichael S. Tsirkin 
73540630b82SMichael S. Tsirkin 			if (!(tun->flags & IFF_PERSIST) &&
736af668b3cSMichael S. Tsirkin 			    tun->dev->reg_state == NETREG_REGISTERED)
7374008e97fSJason Wang 				unregister_netdevice(tun->dev);
738af668b3cSMichael S. Tsirkin 		}
7398565d26bSDavid S. Miller 		tun_cleanup_tx_ring(tfile);
740140e807dSEric W. Biederman 		sock_put(&tfile->sk);
741c8d68e6bSJason Wang 	}
742c8d68e6bSJason Wang }
743c8d68e6bSJason Wang 
744c8d68e6bSJason Wang static void tun_detach(struct tun_file *tfile, bool clean)
745c8d68e6bSJason Wang {
74683c1f36fSSabrina Dubroca 	struct tun_struct *tun;
74783c1f36fSSabrina Dubroca 	struct net_device *dev;
74883c1f36fSSabrina Dubroca 
749c8d68e6bSJason Wang 	rtnl_lock();
75083c1f36fSSabrina Dubroca 	tun = rtnl_dereference(tfile->tun);
75183c1f36fSSabrina Dubroca 	dev = tun ? tun->dev : NULL;
752c8d68e6bSJason Wang 	__tun_detach(tfile, clean);
75383c1f36fSSabrina Dubroca 	if (dev)
75483c1f36fSSabrina Dubroca 		netdev_state_change(dev);
755c8d68e6bSJason Wang 	rtnl_unlock();
756c8d68e6bSJason Wang }
757c8d68e6bSJason Wang 
758c8d68e6bSJason Wang static void tun_detach_all(struct net_device *dev)
759c8d68e6bSJason Wang {
760c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
7614008e97fSJason Wang 	struct tun_file *tfile, *tmp;
762c8d68e6bSJason Wang 	int i, n = tun->numqueues;
763c8d68e6bSJason Wang 
764c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
765b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
766c8d68e6bSJason Wang 		BUG_ON(!tfile);
76794317099SPetar Penkov 		tun_napi_disable(tun, tfile);
768addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7699e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
770c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
771c8d68e6bSJason Wang 		--tun->numqueues;
772c8d68e6bSJason Wang 	}
7739e85722dSJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
774addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7759e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
776c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
7779e85722dSJason Wang 	}
778c8d68e6bSJason Wang 	BUG_ON(tun->numqueues != 0);
779c8d68e6bSJason Wang 
780c8d68e6bSJason Wang 	synchronize_net();
781c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
782b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
78394317099SPetar Penkov 		tun_napi_del(tun, tfile);
784c8d68e6bSJason Wang 		/* Drop read queue */
7854bfb0513SJason Wang 		tun_queue_purge(tfile);
786c8d68e6bSJason Wang 		sock_put(&tfile->sk);
7878565d26bSDavid S. Miller 		tun_cleanup_tx_ring(tfile);
788c8d68e6bSJason Wang 	}
7894008e97fSJason Wang 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
7904008e97fSJason Wang 		tun_enable_queue(tfile);
7914bfb0513SJason Wang 		tun_queue_purge(tfile);
7924008e97fSJason Wang 		sock_put(&tfile->sk);
7938565d26bSDavid S. Miller 		tun_cleanup_tx_ring(tfile);
7944008e97fSJason Wang 	}
7954008e97fSJason Wang 	BUG_ON(tun->numdisabled != 0);
796dd38bd85SJason Wang 
79740630b82SMichael S. Tsirkin 	if (tun->flags & IFF_PERSIST)
798dd38bd85SJason Wang 		module_put(THIS_MODULE);
799c8d68e6bSJason Wang }
800c8d68e6bSJason Wang 
80194317099SPetar Penkov static int tun_attach(struct tun_struct *tun, struct file *file,
80294317099SPetar Penkov 		      bool skip_filter, bool napi)
803a7385ba2SEric W. Biederman {
804631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
8051576d986SJason Wang 	struct net_device *dev = tun->dev;
80638231b7aSEric W. Biederman 	int err;
807a7385ba2SEric W. Biederman 
8085dbbaf2dSPaul Moore 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
8095dbbaf2dSPaul Moore 	if (err < 0)
8105dbbaf2dSPaul Moore 		goto out;
8115dbbaf2dSPaul Moore 
81238231b7aSEric W. Biederman 	err = -EINVAL;
8139e85722dSJason Wang 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
81438231b7aSEric W. Biederman 		goto out;
81538231b7aSEric W. Biederman 
81638231b7aSEric W. Biederman 	err = -EBUSY;
81740630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
818c8d68e6bSJason Wang 		goto out;
819c8d68e6bSJason Wang 
820c8d68e6bSJason Wang 	err = -E2BIG;
8214008e97fSJason Wang 	if (!tfile->detached &&
8224008e97fSJason Wang 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
82338231b7aSEric W. Biederman 		goto out;
82438231b7aSEric W. Biederman 
82538231b7aSEric W. Biederman 	err = 0;
82654f968d6SJason Wang 
82792d4ea6eSstephen hemminger 	/* Re-attach the filter to persist device */
828849c9b6fSPavel Emelyanov 	if (!skip_filter && (tun->filter_attached == true)) {
8298ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
8308ced425eSHannes Frederic Sowa 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
8318ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
83254f968d6SJason Wang 		if (!err)
83354f968d6SJason Wang 			goto out;
83454f968d6SJason Wang 	}
8351576d986SJason Wang 
8361576d986SJason Wang 	if (!tfile->detached &&
8375990a305SJason Wang 	    ptr_ring_init(&tfile->tx_ring, dev->tx_queue_len, GFP_KERNEL)) {
8381576d986SJason Wang 		err = -ENOMEM;
8391576d986SJason Wang 		goto out;
8401576d986SJason Wang 	}
8411576d986SJason Wang 
842c8d68e6bSJason Wang 	tfile->queue_index = tun->numqueues;
843addf8fc4SJason Wang 	tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
8448bf5c4eeSJesper Dangaard Brouer 
8458bf5c4eeSJesper Dangaard Brouer 	if (tfile->detached) {
8468bf5c4eeSJesper Dangaard Brouer 		/* Re-attach detached tfile, updating XDP queue_index */
8478bf5c4eeSJesper Dangaard Brouer 		WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
8488bf5c4eeSJesper Dangaard Brouer 
8498bf5c4eeSJesper Dangaard Brouer 		if (tfile->xdp_rxq.queue_index    != tfile->queue_index)
8508bf5c4eeSJesper Dangaard Brouer 			tfile->xdp_rxq.queue_index = tfile->queue_index;
8518bf5c4eeSJesper Dangaard Brouer 	} else {
8528bf5c4eeSJesper Dangaard Brouer 		/* Setup XDP RX-queue info, for new tfile getting attached */
8538bf5c4eeSJesper Dangaard Brouer 		err = xdp_rxq_info_reg(&tfile->xdp_rxq,
8548bf5c4eeSJesper Dangaard Brouer 				       tun->dev, tfile->queue_index);
8558bf5c4eeSJesper Dangaard Brouer 		if (err < 0)
8568bf5c4eeSJesper Dangaard Brouer 			goto out;
8578bf5c4eeSJesper Dangaard Brouer 		err = 0;
8588bf5c4eeSJesper Dangaard Brouer 	}
8598bf5c4eeSJesper Dangaard Brouer 
8606e914fc7SJason Wang 	rcu_assign_pointer(tfile->tun, tun);
861c8d68e6bSJason Wang 	rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
862c8d68e6bSJason Wang 	tun->numqueues++;
863c8d68e6bSJason Wang 
86494317099SPetar Penkov 	if (tfile->detached) {
8654008e97fSJason Wang 		tun_enable_queue(tfile);
86694317099SPetar Penkov 	} else {
8674008e97fSJason Wang 		sock_hold(&tfile->sk);
86894317099SPetar Penkov 		tun_napi_init(tun, tfile, napi);
86994317099SPetar Penkov 	}
8704008e97fSJason Wang 
871c8d68e6bSJason Wang 	tun_set_real_num_queues(tun);
872c8d68e6bSJason Wang 
873c8d68e6bSJason Wang 	/* device is allowed to go away first, so no need to hold extra
874c8d68e6bSJason Wang 	 * refcnt.
875c8d68e6bSJason Wang 	 */
876a7385ba2SEric W. Biederman 
87738231b7aSEric W. Biederman out:
87838231b7aSEric W. Biederman 	return err;
879a7385ba2SEric W. Biederman }
880a7385ba2SEric W. Biederman 
8819484dc74Syuan linyu static struct tun_struct *tun_get(struct tun_file *tfile)
882631ab46bSEric W. Biederman {
8836e914fc7SJason Wang 	struct tun_struct *tun;
884c70f1829SEric W. Biederman 
8856e914fc7SJason Wang 	rcu_read_lock();
8866e914fc7SJason Wang 	tun = rcu_dereference(tfile->tun);
8876e914fc7SJason Wang 	if (tun)
8886e914fc7SJason Wang 		dev_hold(tun->dev);
8896e914fc7SJason Wang 	rcu_read_unlock();
890c70f1829SEric W. Biederman 
891c70f1829SEric W. Biederman 	return tun;
892631ab46bSEric W. Biederman }
893631ab46bSEric W. Biederman 
894631ab46bSEric W. Biederman static void tun_put(struct tun_struct *tun)
895631ab46bSEric W. Biederman {
8966e914fc7SJason Wang 	dev_put(tun->dev);
897631ab46bSEric W. Biederman }
898631ab46bSEric W. Biederman 
8996b8a66eeSJoe Perches /* TAP filtering */
900f271b2ccSMax Krasnyansky static void addr_hash_set(u32 *mask, const u8 *addr)
901f271b2ccSMax Krasnyansky {
902f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
903f271b2ccSMax Krasnyansky 	mask[n >> 5] |= (1 << (n & 31));
904f271b2ccSMax Krasnyansky }
905f271b2ccSMax Krasnyansky 
906f271b2ccSMax Krasnyansky static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
907f271b2ccSMax Krasnyansky {
908f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
909f271b2ccSMax Krasnyansky 	return mask[n >> 5] & (1 << (n & 31));
910f271b2ccSMax Krasnyansky }
911f271b2ccSMax Krasnyansky 
912f271b2ccSMax Krasnyansky static int update_filter(struct tap_filter *filter, void __user *arg)
913f271b2ccSMax Krasnyansky {
914f271b2ccSMax Krasnyansky 	struct { u8 u[ETH_ALEN]; } *addr;
915f271b2ccSMax Krasnyansky 	struct tun_filter uf;
916f271b2ccSMax Krasnyansky 	int err, alen, n, nexact;
917f271b2ccSMax Krasnyansky 
918f271b2ccSMax Krasnyansky 	if (copy_from_user(&uf, arg, sizeof(uf)))
919f271b2ccSMax Krasnyansky 		return -EFAULT;
920f271b2ccSMax Krasnyansky 
921f271b2ccSMax Krasnyansky 	if (!uf.count) {
922f271b2ccSMax Krasnyansky 		/* Disabled */
923f271b2ccSMax Krasnyansky 		filter->count = 0;
924f271b2ccSMax Krasnyansky 		return 0;
925f271b2ccSMax Krasnyansky 	}
926f271b2ccSMax Krasnyansky 
927f271b2ccSMax Krasnyansky 	alen = ETH_ALEN * uf.count;
92828e8190dSMarkus Elfring 	addr = memdup_user(arg + sizeof(uf), alen);
92928e8190dSMarkus Elfring 	if (IS_ERR(addr))
93028e8190dSMarkus Elfring 		return PTR_ERR(addr);
931f271b2ccSMax Krasnyansky 
932f271b2ccSMax Krasnyansky 	/* The filter is updated without holding any locks. Which is
933f271b2ccSMax Krasnyansky 	 * perfectly safe. We disable it first and in the worst
934f271b2ccSMax Krasnyansky 	 * case we'll accept a few undesired packets. */
935f271b2ccSMax Krasnyansky 	filter->count = 0;
936f271b2ccSMax Krasnyansky 	wmb();
937f271b2ccSMax Krasnyansky 
938f271b2ccSMax Krasnyansky 	/* Use first set of addresses as an exact filter */
939f271b2ccSMax Krasnyansky 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
940f271b2ccSMax Krasnyansky 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
941f271b2ccSMax Krasnyansky 
942f271b2ccSMax Krasnyansky 	nexact = n;
943f271b2ccSMax Krasnyansky 
944cfbf84fcSAlex Williamson 	/* Remaining multicast addresses are hashed,
945cfbf84fcSAlex Williamson 	 * unicast will leave the filter disabled. */
946f271b2ccSMax Krasnyansky 	memset(filter->mask, 0, sizeof(filter->mask));
947cfbf84fcSAlex Williamson 	for (; n < uf.count; n++) {
948cfbf84fcSAlex Williamson 		if (!is_multicast_ether_addr(addr[n].u)) {
949cfbf84fcSAlex Williamson 			err = 0; /* no filter */
9503b8d2a69SMarkus Elfring 			goto free_addr;
951cfbf84fcSAlex Williamson 		}
952f271b2ccSMax Krasnyansky 		addr_hash_set(filter->mask, addr[n].u);
953cfbf84fcSAlex Williamson 	}
954f271b2ccSMax Krasnyansky 
955f271b2ccSMax Krasnyansky 	/* For ALLMULTI just set the mask to all ones.
956f271b2ccSMax Krasnyansky 	 * This overrides the mask populated above. */
957f271b2ccSMax Krasnyansky 	if ((uf.flags & TUN_FLT_ALLMULTI))
958f271b2ccSMax Krasnyansky 		memset(filter->mask, ~0, sizeof(filter->mask));
959f271b2ccSMax Krasnyansky 
960f271b2ccSMax Krasnyansky 	/* Now enable the filter */
961f271b2ccSMax Krasnyansky 	wmb();
962f271b2ccSMax Krasnyansky 	filter->count = nexact;
963f271b2ccSMax Krasnyansky 
964f271b2ccSMax Krasnyansky 	/* Return the number of exact filters */
965f271b2ccSMax Krasnyansky 	err = nexact;
9663b8d2a69SMarkus Elfring free_addr:
967f271b2ccSMax Krasnyansky 	kfree(addr);
968f271b2ccSMax Krasnyansky 	return err;
969f271b2ccSMax Krasnyansky }
970f271b2ccSMax Krasnyansky 
971f271b2ccSMax Krasnyansky /* Returns: 0 - drop, !=0 - accept */
972f271b2ccSMax Krasnyansky static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
973f271b2ccSMax Krasnyansky {
974f271b2ccSMax Krasnyansky 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
975f271b2ccSMax Krasnyansky 	 * at this point. */
976f271b2ccSMax Krasnyansky 	struct ethhdr *eh = (struct ethhdr *) skb->data;
977f271b2ccSMax Krasnyansky 	int i;
978f271b2ccSMax Krasnyansky 
979f271b2ccSMax Krasnyansky 	/* Exact match */
980f271b2ccSMax Krasnyansky 	for (i = 0; i < filter->count; i++)
9812e42e474SJoe Perches 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
982f271b2ccSMax Krasnyansky 			return 1;
983f271b2ccSMax Krasnyansky 
984f271b2ccSMax Krasnyansky 	/* Inexact match (multicast only) */
985f271b2ccSMax Krasnyansky 	if (is_multicast_ether_addr(eh->h_dest))
986f271b2ccSMax Krasnyansky 		return addr_hash_test(filter->mask, eh->h_dest);
987f271b2ccSMax Krasnyansky 
988f271b2ccSMax Krasnyansky 	return 0;
989f271b2ccSMax Krasnyansky }
990f271b2ccSMax Krasnyansky 
991f271b2ccSMax Krasnyansky /*
992f271b2ccSMax Krasnyansky  * Checks whether the packet is accepted or not.
993f271b2ccSMax Krasnyansky  * Returns: 0 - drop, !=0 - accept
994f271b2ccSMax Krasnyansky  */
995f271b2ccSMax Krasnyansky static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
996f271b2ccSMax Krasnyansky {
997f271b2ccSMax Krasnyansky 	if (!filter->count)
998f271b2ccSMax Krasnyansky 		return 1;
999f271b2ccSMax Krasnyansky 
1000f271b2ccSMax Krasnyansky 	return run_filter(filter, skb);
1001f271b2ccSMax Krasnyansky }
1002f271b2ccSMax Krasnyansky 
10031da177e4SLinus Torvalds /* Network device part of the driver */
10041da177e4SLinus Torvalds 
10051da177e4SLinus Torvalds static const struct ethtool_ops tun_ethtool_ops;
10061da177e4SLinus Torvalds 
1007c70f1829SEric W. Biederman /* Net device detach from fd. */
1008c70f1829SEric W. Biederman static void tun_net_uninit(struct net_device *dev)
1009c70f1829SEric W. Biederman {
1010c8d68e6bSJason Wang 	tun_detach_all(dev);
1011c70f1829SEric W. Biederman }
1012c70f1829SEric W. Biederman 
10131da177e4SLinus Torvalds /* Net device open. */
10141da177e4SLinus Torvalds static int tun_net_open(struct net_device *dev)
10151da177e4SLinus Torvalds {
1016b20e2d54SHannes Frederic Sowa 	struct tun_struct *tun = netdev_priv(dev);
1017b20e2d54SHannes Frederic Sowa 	int i;
1018b20e2d54SHannes Frederic Sowa 
1019c8d68e6bSJason Wang 	netif_tx_start_all_queues(dev);
1020b20e2d54SHannes Frederic Sowa 
1021b20e2d54SHannes Frederic Sowa 	for (i = 0; i < tun->numqueues; i++) {
1022b20e2d54SHannes Frederic Sowa 		struct tun_file *tfile;
1023b20e2d54SHannes Frederic Sowa 
1024b20e2d54SHannes Frederic Sowa 		tfile = rtnl_dereference(tun->tfiles[i]);
1025b20e2d54SHannes Frederic Sowa 		tfile->socket.sk->sk_write_space(tfile->socket.sk);
1026b20e2d54SHannes Frederic Sowa 	}
1027b20e2d54SHannes Frederic Sowa 
10281da177e4SLinus Torvalds 	return 0;
10291da177e4SLinus Torvalds }
10301da177e4SLinus Torvalds 
10311da177e4SLinus Torvalds /* Net device close. */
10321da177e4SLinus Torvalds static int tun_net_close(struct net_device *dev)
10331da177e4SLinus Torvalds {
1034c8d68e6bSJason Wang 	netif_tx_stop_all_queues(dev);
10351da177e4SLinus Torvalds 	return 0;
10361da177e4SLinus Torvalds }
10371da177e4SLinus Torvalds 
10381da177e4SLinus Torvalds /* Net device start xmit */
103996f84061SJason Wang static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
10401da177e4SLinus Torvalds {
10413df97ba8SJason Wang #ifdef CONFIG_RPS
104296f84061SJason Wang 	if (tun->numqueues == 1 && static_key_false(&rps_needed)) {
10439bc88939STom Herbert 		/* Select queue was not called for the skbuff, so we extract the
10449bc88939STom Herbert 		 * RPS hash and save it into the flow_table here.
10459bc88939STom Herbert 		 */
10469bc88939STom Herbert 		__u32 rxhash;
10479bc88939STom Herbert 
1048feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
10499bc88939STom Herbert 		if (rxhash) {
10509bc88939STom Herbert 			struct tun_flow_entry *e;
10519bc88939STom Herbert 			e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
10529bc88939STom Herbert 					rxhash);
10539bc88939STom Herbert 			if (e)
10549bc88939STom Herbert 				tun_flow_save_rps_rxhash(e, rxhash);
10559bc88939STom Herbert 		}
10569bc88939STom Herbert 	}
10573df97ba8SJason Wang #endif
105896f84061SJason Wang }
105996f84061SJason Wang 
1060aff3d70aSJason Wang static unsigned int run_ebpf_filter(struct tun_struct *tun,
1061aff3d70aSJason Wang 				    struct sk_buff *skb,
1062aff3d70aSJason Wang 				    int len)
1063aff3d70aSJason Wang {
1064aff3d70aSJason Wang 	struct tun_prog *prog = rcu_dereference(tun->filter_prog);
1065aff3d70aSJason Wang 
1066aff3d70aSJason Wang 	if (prog)
1067aff3d70aSJason Wang 		len = bpf_prog_run_clear_cb(prog->prog, skb);
1068aff3d70aSJason Wang 
1069aff3d70aSJason Wang 	return len;
1070aff3d70aSJason Wang }
1071aff3d70aSJason Wang 
107296f84061SJason Wang /* Net device start xmit */
107396f84061SJason Wang static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
107496f84061SJason Wang {
107596f84061SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
107696f84061SJason Wang 	int txq = skb->queue_mapping;
107796f84061SJason Wang 	struct tun_file *tfile;
1078aff3d70aSJason Wang 	int len = skb->len;
107996f84061SJason Wang 
108096f84061SJason Wang 	rcu_read_lock();
108196f84061SJason Wang 	tfile = rcu_dereference(tun->tfiles[txq]);
108296f84061SJason Wang 
108396f84061SJason Wang 	/* Drop packet if interface is not attached */
1084cc166427SWillem de Bruijn 	if (txq >= tun->numqueues)
108596f84061SJason Wang 		goto drop;
108696f84061SJason Wang 
108796f84061SJason Wang 	if (!rcu_dereference(tun->steering_prog))
108896f84061SJason Wang 		tun_automq_xmit(tun, skb);
10899bc88939STom Herbert 
10906e914fc7SJason Wang 	tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
10916e914fc7SJason Wang 
1092c8d68e6bSJason Wang 	BUG_ON(!tfile);
1093c8d68e6bSJason Wang 
1094f271b2ccSMax Krasnyansky 	/* Drop if the filter does not like it.
1095f271b2ccSMax Krasnyansky 	 * This is a noop if the filter is disabled.
1096f271b2ccSMax Krasnyansky 	 * Filter can be enabled only for the TAP devices. */
1097f271b2ccSMax Krasnyansky 	if (!check_filter(&tun->txflt, skb))
1098f271b2ccSMax Krasnyansky 		goto drop;
1099f271b2ccSMax Krasnyansky 
110054f968d6SJason Wang 	if (tfile->socket.sk->sk_filter &&
110154f968d6SJason Wang 	    sk_filter(tfile->socket.sk, skb))
110299405162SMichael S. Tsirkin 		goto drop;
110399405162SMichael S. Tsirkin 
1104aff3d70aSJason Wang 	len = run_ebpf_filter(tun, skb, len);
1105aff3d70aSJason Wang 
1106aff3d70aSJason Wang 	/* Trim extra bytes since we may insert vlan proto & TCI
1107aff3d70aSJason Wang 	 * in tun_put_user().
1108aff3d70aSJason Wang 	 */
1109aff3d70aSJason Wang 	len -= skb_vlan_tag_present(skb) ? sizeof(struct veth) : 0;
1110aff3d70aSJason Wang 	if (len <= 0 || pskb_trim(skb, len))
1111aff3d70aSJason Wang 		goto drop;
1112aff3d70aSJason Wang 
11131f8b977aSWillem de Bruijn 	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
11147bf66305SJason Wang 		goto drop;
11157bf66305SJason Wang 
11167b996243SSoheil Hassas Yeganeh 	skb_tx_timestamp(skb);
1117eda29772SRichard Cochran 
11180110d6f2SMichael S. Tsirkin 	/* Orphan the skb - required as we might hang on to it
11197bf66305SJason Wang 	 * for indefinite time.
11207bf66305SJason Wang 	 */
11210110d6f2SMichael S. Tsirkin 	skb_orphan(skb);
11220110d6f2SMichael S. Tsirkin 
1123f8af75f3SEric Dumazet 	nf_reset(skb);
1124f8af75f3SEric Dumazet 
11255990a305SJason Wang 	if (ptr_ring_produce(&tfile->tx_ring, skb))
11261576d986SJason Wang 		goto drop;
11271da177e4SLinus Torvalds 
11281da177e4SLinus Torvalds 	/* Notify and wake up reader process */
112954f968d6SJason Wang 	if (tfile->flags & TUN_FASYNC)
113054f968d6SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
11319e641bdcSXi Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
11326e914fc7SJason Wang 
11336e914fc7SJason Wang 	rcu_read_unlock();
11346ed10654SPatrick McHardy 	return NETDEV_TX_OK;
11351da177e4SLinus Torvalds 
11361da177e4SLinus Torvalds drop:
1137608b9977SPaolo Abeni 	this_cpu_inc(tun->pcpu_stats->tx_dropped);
1138149d36f7SMichael S. Tsirkin 	skb_tx_error(skb);
11391da177e4SLinus Torvalds 	kfree_skb(skb);
11406e914fc7SJason Wang 	rcu_read_unlock();
1141baeababbSJason Wang 	return NET_XMIT_DROP;
11421da177e4SLinus Torvalds }
11431da177e4SLinus Torvalds 
1144f271b2ccSMax Krasnyansky static void tun_net_mclist(struct net_device *dev)
11451da177e4SLinus Torvalds {
1146f271b2ccSMax Krasnyansky 	/*
1147f271b2ccSMax Krasnyansky 	 * This callback is supposed to deal with mc filter in
1148f271b2ccSMax Krasnyansky 	 * _rx_ path and has nothing to do with the _tx_ path.
1149f271b2ccSMax Krasnyansky 	 * In rx path we always accept everything userspace gives us.
1150f271b2ccSMax Krasnyansky 	 */
11511da177e4SLinus Torvalds }
11521da177e4SLinus Torvalds 
1153c8f44affSMichał Mirosław static netdev_features_t tun_net_fix_features(struct net_device *dev,
1154c8f44affSMichał Mirosław 	netdev_features_t features)
115588255375SMichał Mirosław {
115688255375SMichał Mirosław 	struct tun_struct *tun = netdev_priv(dev);
115788255375SMichał Mirosław 
115888255375SMichał Mirosław 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
115988255375SMichał Mirosław }
1160bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
1161bebd097aSNeil Horman static void tun_poll_controller(struct net_device *dev)
1162bebd097aSNeil Horman {
1163bebd097aSNeil Horman 	/*
1164bebd097aSNeil Horman 	 * Tun only receives frames when:
1165bebd097aSNeil Horman 	 * 1) the char device endpoint gets data from user space
1166bebd097aSNeil Horman 	 * 2) the tun socket gets a sendmsg call from user space
116794317099SPetar Penkov 	 * If NAPI is not enabled, since both of those are synchronous
116894317099SPetar Penkov 	 * operations, we are guaranteed never to have pending data when we poll
116994317099SPetar Penkov 	 * for it so there is nothing to do here but return.
1170bebd097aSNeil Horman 	 * We need this though so netpoll recognizes us as an interface that
1171bebd097aSNeil Horman 	 * supports polling, which enables bridge devices in virt setups to
1172bebd097aSNeil Horman 	 * still use netconsole
117394317099SPetar Penkov 	 * If NAPI is enabled, however, we need to schedule polling for all
117490e33d45SPetar Penkov 	 * queues unless we are using napi_gro_frags(), which we call in
117590e33d45SPetar Penkov 	 * process context and not in NAPI context.
1176bebd097aSNeil Horman 	 */
117794317099SPetar Penkov 	struct tun_struct *tun = netdev_priv(dev);
117894317099SPetar Penkov 
117994317099SPetar Penkov 	if (tun->flags & IFF_NAPI) {
118094317099SPetar Penkov 		struct tun_file *tfile;
118194317099SPetar Penkov 		int i;
118294317099SPetar Penkov 
118390e33d45SPetar Penkov 		if (tun_napi_frags_enabled(tun))
118490e33d45SPetar Penkov 			return;
118590e33d45SPetar Penkov 
118694317099SPetar Penkov 		rcu_read_lock();
118794317099SPetar Penkov 		for (i = 0; i < tun->numqueues; i++) {
118894317099SPetar Penkov 			tfile = rcu_dereference(tun->tfiles[i]);
1189aec72f33SEric Dumazet 			if (tfile->napi_enabled)
119094317099SPetar Penkov 				napi_schedule(&tfile->napi);
119194317099SPetar Penkov 		}
119294317099SPetar Penkov 		rcu_read_unlock();
119394317099SPetar Penkov 	}
1194bebd097aSNeil Horman 	return;
1195bebd097aSNeil Horman }
1196bebd097aSNeil Horman #endif
1197eaea34b2SPaolo Abeni 
1198eaea34b2SPaolo Abeni static void tun_set_headroom(struct net_device *dev, int new_hr)
1199eaea34b2SPaolo Abeni {
1200eaea34b2SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1201eaea34b2SPaolo Abeni 
1202eaea34b2SPaolo Abeni 	if (new_hr < NET_SKB_PAD)
1203eaea34b2SPaolo Abeni 		new_hr = NET_SKB_PAD;
1204eaea34b2SPaolo Abeni 
1205eaea34b2SPaolo Abeni 	tun->align = new_hr;
1206eaea34b2SPaolo Abeni }
1207eaea34b2SPaolo Abeni 
1208bc1f4470Sstephen hemminger static void
1209608b9977SPaolo Abeni tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1210608b9977SPaolo Abeni {
1211608b9977SPaolo Abeni 	u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1212608b9977SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1213608b9977SPaolo Abeni 	struct tun_pcpu_stats *p;
1214608b9977SPaolo Abeni 	int i;
1215608b9977SPaolo Abeni 
1216608b9977SPaolo Abeni 	for_each_possible_cpu(i) {
1217608b9977SPaolo Abeni 		u64 rxpackets, rxbytes, txpackets, txbytes;
1218608b9977SPaolo Abeni 		unsigned int start;
1219608b9977SPaolo Abeni 
1220608b9977SPaolo Abeni 		p = per_cpu_ptr(tun->pcpu_stats, i);
1221608b9977SPaolo Abeni 		do {
1222608b9977SPaolo Abeni 			start = u64_stats_fetch_begin(&p->syncp);
1223608b9977SPaolo Abeni 			rxpackets	= p->rx_packets;
1224608b9977SPaolo Abeni 			rxbytes		= p->rx_bytes;
1225608b9977SPaolo Abeni 			txpackets	= p->tx_packets;
1226608b9977SPaolo Abeni 			txbytes		= p->tx_bytes;
1227608b9977SPaolo Abeni 		} while (u64_stats_fetch_retry(&p->syncp, start));
1228608b9977SPaolo Abeni 
1229608b9977SPaolo Abeni 		stats->rx_packets	+= rxpackets;
1230608b9977SPaolo Abeni 		stats->rx_bytes		+= rxbytes;
1231608b9977SPaolo Abeni 		stats->tx_packets	+= txpackets;
1232608b9977SPaolo Abeni 		stats->tx_bytes		+= txbytes;
1233608b9977SPaolo Abeni 
1234608b9977SPaolo Abeni 		/* u32 counters */
1235608b9977SPaolo Abeni 		rx_dropped	+= p->rx_dropped;
1236608b9977SPaolo Abeni 		rx_frame_errors	+= p->rx_frame_errors;
1237608b9977SPaolo Abeni 		tx_dropped	+= p->tx_dropped;
1238608b9977SPaolo Abeni 	}
1239608b9977SPaolo Abeni 	stats->rx_dropped  = rx_dropped;
1240608b9977SPaolo Abeni 	stats->rx_frame_errors = rx_frame_errors;
1241608b9977SPaolo Abeni 	stats->tx_dropped = tx_dropped;
1242608b9977SPaolo Abeni }
1243608b9977SPaolo Abeni 
1244761876c8SJason Wang static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1245761876c8SJason Wang 		       struct netlink_ext_ack *extack)
1246761876c8SJason Wang {
1247761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1248761876c8SJason Wang 	struct bpf_prog *old_prog;
1249761876c8SJason Wang 
1250761876c8SJason Wang 	old_prog = rtnl_dereference(tun->xdp_prog);
1251761876c8SJason Wang 	rcu_assign_pointer(tun->xdp_prog, prog);
1252761876c8SJason Wang 	if (old_prog)
1253761876c8SJason Wang 		bpf_prog_put(old_prog);
1254761876c8SJason Wang 
1255761876c8SJason Wang 	return 0;
1256761876c8SJason Wang }
1257761876c8SJason Wang 
1258761876c8SJason Wang static u32 tun_xdp_query(struct net_device *dev)
1259761876c8SJason Wang {
1260761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1261761876c8SJason Wang 	const struct bpf_prog *xdp_prog;
1262761876c8SJason Wang 
1263761876c8SJason Wang 	xdp_prog = rtnl_dereference(tun->xdp_prog);
1264761876c8SJason Wang 	if (xdp_prog)
1265761876c8SJason Wang 		return xdp_prog->aux->id;
1266761876c8SJason Wang 
1267761876c8SJason Wang 	return 0;
1268761876c8SJason Wang }
1269761876c8SJason Wang 
1270f4e63525SJakub Kicinski static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1271761876c8SJason Wang {
1272761876c8SJason Wang 	switch (xdp->command) {
1273761876c8SJason Wang 	case XDP_SETUP_PROG:
1274761876c8SJason Wang 		return tun_xdp_set(dev, xdp->prog, xdp->extack);
1275761876c8SJason Wang 	case XDP_QUERY_PROG:
1276761876c8SJason Wang 		xdp->prog_id = tun_xdp_query(dev);
1277761876c8SJason Wang 		xdp->prog_attached = !!xdp->prog_id;
1278761876c8SJason Wang 		return 0;
1279761876c8SJason Wang 	default:
1280761876c8SJason Wang 		return -EINVAL;
1281761876c8SJason Wang 	}
1282761876c8SJason Wang }
1283761876c8SJason Wang 
1284758e43b7SStephen Hemminger static const struct net_device_ops tun_netdev_ops = {
1285c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1286758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1287758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
128800829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
128988255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1290c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
1291bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
1292bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
1293bebd097aSNeil Horman #endif
1294eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1295608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
1296758e43b7SStephen Hemminger };
1297758e43b7SStephen Hemminger 
1298fc72d1d5SJason Wang static int tun_xdp_xmit(struct net_device *dev, struct xdp_buff *xdp)
1299fc72d1d5SJason Wang {
1300fc72d1d5SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1301*1ffcbc85SJesper Dangaard Brouer 	struct xdp_frame *frame;
1302fc72d1d5SJason Wang 	struct tun_file *tfile;
1303fc72d1d5SJason Wang 	u32 numqueues;
1304fc72d1d5SJason Wang 	int ret = 0;
1305fc72d1d5SJason Wang 
1306*1ffcbc85SJesper Dangaard Brouer 	frame = convert_to_xdp_frame(xdp);
1307*1ffcbc85SJesper Dangaard Brouer 	if (unlikely(!frame))
1308*1ffcbc85SJesper Dangaard Brouer 		return -EOVERFLOW;
1309fc72d1d5SJason Wang 
1310fc72d1d5SJason Wang 	rcu_read_lock();
1311fc72d1d5SJason Wang 
1312fc72d1d5SJason Wang 	numqueues = READ_ONCE(tun->numqueues);
1313fc72d1d5SJason Wang 	if (!numqueues) {
1314fc72d1d5SJason Wang 		ret = -ENOSPC;
1315fc72d1d5SJason Wang 		goto out;
1316fc72d1d5SJason Wang 	}
1317fc72d1d5SJason Wang 
1318fc72d1d5SJason Wang 	tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1319fc72d1d5SJason Wang 					    numqueues]);
1320fc72d1d5SJason Wang 	/* Encode the XDP flag into lowest bit for consumer to differ
1321fc72d1d5SJason Wang 	 * XDP buffer from sk_buff.
1322fc72d1d5SJason Wang 	 */
1323*1ffcbc85SJesper Dangaard Brouer 	if (ptr_ring_produce(&tfile->tx_ring, tun_xdp_to_ptr(frame))) {
1324fc72d1d5SJason Wang 		this_cpu_inc(tun->pcpu_stats->tx_dropped);
1325fc72d1d5SJason Wang 		ret = -ENOSPC;
1326fc72d1d5SJason Wang 	}
1327fc72d1d5SJason Wang 
1328fc72d1d5SJason Wang out:
1329fc72d1d5SJason Wang 	rcu_read_unlock();
1330fc72d1d5SJason Wang 	return ret;
1331fc72d1d5SJason Wang }
1332fc72d1d5SJason Wang 
1333fc72d1d5SJason Wang static void tun_xdp_flush(struct net_device *dev)
1334fc72d1d5SJason Wang {
1335fc72d1d5SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1336fc72d1d5SJason Wang 	struct tun_file *tfile;
1337fc72d1d5SJason Wang 	u32 numqueues;
1338fc72d1d5SJason Wang 
1339fc72d1d5SJason Wang 	rcu_read_lock();
1340fc72d1d5SJason Wang 
1341fc72d1d5SJason Wang 	numqueues = READ_ONCE(tun->numqueues);
1342fc72d1d5SJason Wang 	if (!numqueues)
1343fc72d1d5SJason Wang 		goto out;
1344fc72d1d5SJason Wang 
1345fc72d1d5SJason Wang 	tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1346fc72d1d5SJason Wang 					    numqueues]);
1347fc72d1d5SJason Wang 	/* Notify and wake up reader process */
1348fc72d1d5SJason Wang 	if (tfile->flags & TUN_FASYNC)
1349fc72d1d5SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1350fc72d1d5SJason Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1351fc72d1d5SJason Wang 
1352fc72d1d5SJason Wang out:
1353fc72d1d5SJason Wang 	rcu_read_unlock();
1354fc72d1d5SJason Wang }
1355fc72d1d5SJason Wang 
1356758e43b7SStephen Hemminger static const struct net_device_ops tap_netdev_ops = {
1357c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1358758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1359758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
136000829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
136188255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1362afc4b13dSJiri Pirko 	.ndo_set_rx_mode	= tun_net_mclist,
1363758e43b7SStephen Hemminger 	.ndo_set_mac_address	= eth_mac_addr,
1364758e43b7SStephen Hemminger 	.ndo_validate_addr	= eth_validate_addr,
1365c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
1366bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
1367bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
1368bebd097aSNeil Horman #endif
13695e52796aSToshiaki Makita 	.ndo_features_check	= passthru_features_check,
1370eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1371608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
1372f4e63525SJakub Kicinski 	.ndo_bpf		= tun_xdp,
1373fc72d1d5SJason Wang 	.ndo_xdp_xmit		= tun_xdp_xmit,
1374fc72d1d5SJason Wang 	.ndo_xdp_flush		= tun_xdp_flush,
1375758e43b7SStephen Hemminger };
1376758e43b7SStephen Hemminger 
1377944a1376SPavel Emelyanov static void tun_flow_init(struct tun_struct *tun)
137896442e42SJason Wang {
137996442e42SJason Wang 	int i;
138096442e42SJason Wang 
138196442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
138296442e42SJason Wang 		INIT_HLIST_HEAD(&tun->flows[i]);
138396442e42SJason Wang 
138496442e42SJason Wang 	tun->ageing_time = TUN_FLOW_EXPIRE;
1385e99e88a9SKees Cook 	timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1386e99e88a9SKees Cook 	mod_timer(&tun->flow_gc_timer,
1387e99e88a9SKees Cook 		  round_jiffies_up(jiffies + tun->ageing_time));
138896442e42SJason Wang }
138996442e42SJason Wang 
139096442e42SJason Wang static void tun_flow_uninit(struct tun_struct *tun)
139196442e42SJason Wang {
139296442e42SJason Wang 	del_timer_sync(&tun->flow_gc_timer);
139396442e42SJason Wang 	tun_flow_flush(tun);
139496442e42SJason Wang }
139596442e42SJason Wang 
139691572088SJarod Wilson #define MIN_MTU 68
139791572088SJarod Wilson #define MAX_MTU 65535
139891572088SJarod Wilson 
13991da177e4SLinus Torvalds /* Initialize net device. */
14001da177e4SLinus Torvalds static void tun_net_init(struct net_device *dev)
14011da177e4SLinus Torvalds {
14021da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
14031da177e4SLinus Torvalds 
14041da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
140540630b82SMichael S. Tsirkin 	case IFF_TUN:
1406758e43b7SStephen Hemminger 		dev->netdev_ops = &tun_netdev_ops;
1407758e43b7SStephen Hemminger 
14081da177e4SLinus Torvalds 		/* Point-to-Point TUN Device */
14091da177e4SLinus Torvalds 		dev->hard_header_len = 0;
14101da177e4SLinus Torvalds 		dev->addr_len = 0;
14111da177e4SLinus Torvalds 		dev->mtu = 1500;
14121da177e4SLinus Torvalds 
14131da177e4SLinus Torvalds 		/* Zero header length */
14141da177e4SLinus Torvalds 		dev->type = ARPHRD_NONE;
14151da177e4SLinus Torvalds 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
14161da177e4SLinus Torvalds 		break;
14171da177e4SLinus Torvalds 
141840630b82SMichael S. Tsirkin 	case IFF_TAP:
14197a0a9608SKusanagi Kouichi 		dev->netdev_ops = &tap_netdev_ops;
14201da177e4SLinus Torvalds 		/* Ethernet TAP Device */
14211da177e4SLinus Torvalds 		ether_setup(dev);
1422550fd08cSNeil Horman 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1423a676847bSstephen hemminger 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
142436226a8dSBrian Braunstein 
1425f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
142636226a8dSBrian Braunstein 
14271da177e4SLinus Torvalds 		break;
14281da177e4SLinus Torvalds 	}
142991572088SJarod Wilson 
143091572088SJarod Wilson 	dev->min_mtu = MIN_MTU;
143191572088SJarod Wilson 	dev->max_mtu = MAX_MTU - dev->hard_header_len;
14321da177e4SLinus Torvalds }
14331da177e4SLinus Torvalds 
14341da177e4SLinus Torvalds /* Character device part */
14351da177e4SLinus Torvalds 
14361da177e4SLinus Torvalds /* Poll */
1437afc9a42bSAl Viro static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
14381da177e4SLinus Torvalds {
1439b2430de3SEric W. Biederman 	struct tun_file *tfile = file->private_data;
14409484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
14413c8a9c63SMariusz Kozlowski 	struct sock *sk;
1442afc9a42bSAl Viro 	__poll_t mask = 0;
14431da177e4SLinus Torvalds 
14441da177e4SLinus Torvalds 	if (!tun)
1445a9a08845SLinus Torvalds 		return EPOLLERR;
14461da177e4SLinus Torvalds 
144754f968d6SJason Wang 	sk = tfile->socket.sk;
14483c8a9c63SMariusz Kozlowski 
14496b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
14501da177e4SLinus Torvalds 
14519e641bdcSXi Wang 	poll_wait(file, sk_sleep(sk), wait);
14521da177e4SLinus Torvalds 
14535990a305SJason Wang 	if (!ptr_ring_empty(&tfile->tx_ring))
1454a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
14551da177e4SLinus Torvalds 
1456b20e2d54SHannes Frederic Sowa 	if (tun->dev->flags & IFF_UP &&
1457b20e2d54SHannes Frederic Sowa 	    (sock_writeable(sk) ||
14589cd3e072SEric Dumazet 	     (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1459b20e2d54SHannes Frederic Sowa 	      sock_writeable(sk))))
1460a9a08845SLinus Torvalds 		mask |= EPOLLOUT | EPOLLWRNORM;
146133dccbb0SHerbert Xu 
1462c70f1829SEric W. Biederman 	if (tun->dev->reg_state != NETREG_REGISTERED)
1463a9a08845SLinus Torvalds 		mask = EPOLLERR;
1464c70f1829SEric W. Biederman 
1465631ab46bSEric W. Biederman 	tun_put(tun);
14661da177e4SLinus Torvalds 	return mask;
14671da177e4SLinus Torvalds }
14681da177e4SLinus Torvalds 
146990e33d45SPetar Penkov static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
147090e33d45SPetar Penkov 					    size_t len,
147190e33d45SPetar Penkov 					    const struct iov_iter *it)
147290e33d45SPetar Penkov {
147390e33d45SPetar Penkov 	struct sk_buff *skb;
147490e33d45SPetar Penkov 	size_t linear;
147590e33d45SPetar Penkov 	int err;
147690e33d45SPetar Penkov 	int i;
147790e33d45SPetar Penkov 
147890e33d45SPetar Penkov 	if (it->nr_segs > MAX_SKB_FRAGS + 1)
147990e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
148090e33d45SPetar Penkov 
148190e33d45SPetar Penkov 	local_bh_disable();
148290e33d45SPetar Penkov 	skb = napi_get_frags(&tfile->napi);
148390e33d45SPetar Penkov 	local_bh_enable();
148490e33d45SPetar Penkov 	if (!skb)
148590e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
148690e33d45SPetar Penkov 
148790e33d45SPetar Penkov 	linear = iov_iter_single_seg_count(it);
148890e33d45SPetar Penkov 	err = __skb_grow(skb, linear);
148990e33d45SPetar Penkov 	if (err)
149090e33d45SPetar Penkov 		goto free;
149190e33d45SPetar Penkov 
149290e33d45SPetar Penkov 	skb->len = len;
149390e33d45SPetar Penkov 	skb->data_len = len - linear;
149490e33d45SPetar Penkov 	skb->truesize += skb->data_len;
149590e33d45SPetar Penkov 
149690e33d45SPetar Penkov 	for (i = 1; i < it->nr_segs; i++) {
149743a08e0fSEric Dumazet 		struct page_frag *pfrag = &current->task_frag;
149890e33d45SPetar Penkov 		size_t fragsz = it->iov[i].iov_len;
149990e33d45SPetar Penkov 
150090e33d45SPetar Penkov 		if (fragsz == 0 || fragsz > PAGE_SIZE) {
150190e33d45SPetar Penkov 			err = -EINVAL;
150290e33d45SPetar Penkov 			goto free;
150390e33d45SPetar Penkov 		}
150490e33d45SPetar Penkov 
150543a08e0fSEric Dumazet 		if (!skb_page_frag_refill(fragsz, pfrag, GFP_KERNEL)) {
150690e33d45SPetar Penkov 			err = -ENOMEM;
150790e33d45SPetar Penkov 			goto free;
150890e33d45SPetar Penkov 		}
150990e33d45SPetar Penkov 
151043a08e0fSEric Dumazet 		skb_fill_page_desc(skb, i - 1, pfrag->page,
151143a08e0fSEric Dumazet 				   pfrag->offset, fragsz);
151243a08e0fSEric Dumazet 		page_ref_inc(pfrag->page);
151343a08e0fSEric Dumazet 		pfrag->offset += fragsz;
151490e33d45SPetar Penkov 	}
151590e33d45SPetar Penkov 
151690e33d45SPetar Penkov 	return skb;
151790e33d45SPetar Penkov free:
151890e33d45SPetar Penkov 	/* frees skb and all frags allocated with napi_alloc_frag() */
151990e33d45SPetar Penkov 	napi_free_frags(&tfile->napi);
152090e33d45SPetar Penkov 	return ERR_PTR(err);
152190e33d45SPetar Penkov }
152290e33d45SPetar Penkov 
1523f42157cbSRusty Russell /* prepad is the amount to reserve at front.  len is length after that.
1524f42157cbSRusty Russell  * linear is a hint as to how much to copy (usually headers). */
152554f968d6SJason Wang static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
152633dccbb0SHerbert Xu 				     size_t prepad, size_t len,
152733dccbb0SHerbert Xu 				     size_t linear, int noblock)
1528f42157cbSRusty Russell {
152954f968d6SJason Wang 	struct sock *sk = tfile->socket.sk;
1530f42157cbSRusty Russell 	struct sk_buff *skb;
153133dccbb0SHerbert Xu 	int err;
1532f42157cbSRusty Russell 
1533f42157cbSRusty Russell 	/* Under a page?  Don't bother with paged skb. */
15340eca93bcSHerbert Xu 	if (prepad + len < PAGE_SIZE || !linear)
153533dccbb0SHerbert Xu 		linear = len;
1536f42157cbSRusty Russell 
153733dccbb0SHerbert Xu 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
153828d64271SEric Dumazet 				   &err, 0);
1539f42157cbSRusty Russell 	if (!skb)
154033dccbb0SHerbert Xu 		return ERR_PTR(err);
1541f42157cbSRusty Russell 
1542f42157cbSRusty Russell 	skb_reserve(skb, prepad);
1543f42157cbSRusty Russell 	skb_put(skb, linear);
154433dccbb0SHerbert Xu 	skb->data_len = len - linear;
154533dccbb0SHerbert Xu 	skb->len += len - linear;
1546f42157cbSRusty Russell 
1547f42157cbSRusty Russell 	return skb;
1548f42157cbSRusty Russell }
1549f42157cbSRusty Russell 
15505503fcecSJason Wang static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
15515503fcecSJason Wang 			   struct sk_buff *skb, int more)
15525503fcecSJason Wang {
15535503fcecSJason Wang 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
15545503fcecSJason Wang 	struct sk_buff_head process_queue;
15555503fcecSJason Wang 	u32 rx_batched = tun->rx_batched;
15565503fcecSJason Wang 	bool rcv = false;
15575503fcecSJason Wang 
15585503fcecSJason Wang 	if (!rx_batched || (!more && skb_queue_empty(queue))) {
15595503fcecSJason Wang 		local_bh_disable();
15605503fcecSJason Wang 		netif_receive_skb(skb);
15615503fcecSJason Wang 		local_bh_enable();
15625503fcecSJason Wang 		return;
15635503fcecSJason Wang 	}
15645503fcecSJason Wang 
15655503fcecSJason Wang 	spin_lock(&queue->lock);
15665503fcecSJason Wang 	if (!more || skb_queue_len(queue) == rx_batched) {
15675503fcecSJason Wang 		__skb_queue_head_init(&process_queue);
15685503fcecSJason Wang 		skb_queue_splice_tail_init(queue, &process_queue);
15695503fcecSJason Wang 		rcv = true;
15705503fcecSJason Wang 	} else {
15715503fcecSJason Wang 		__skb_queue_tail(queue, skb);
15725503fcecSJason Wang 	}
15735503fcecSJason Wang 	spin_unlock(&queue->lock);
15745503fcecSJason Wang 
15755503fcecSJason Wang 	if (rcv) {
15765503fcecSJason Wang 		struct sk_buff *nskb;
15775503fcecSJason Wang 
15785503fcecSJason Wang 		local_bh_disable();
15795503fcecSJason Wang 		while ((nskb = __skb_dequeue(&process_queue)))
15805503fcecSJason Wang 			netif_receive_skb(nskb);
15815503fcecSJason Wang 		netif_receive_skb(skb);
15825503fcecSJason Wang 		local_bh_enable();
15835503fcecSJason Wang 	}
15845503fcecSJason Wang }
15855503fcecSJason Wang 
158666ccbc9cSJason Wang static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
158766ccbc9cSJason Wang 			      int len, int noblock, bool zerocopy)
158866ccbc9cSJason Wang {
158966ccbc9cSJason Wang 	if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
159066ccbc9cSJason Wang 		return false;
159166ccbc9cSJason Wang 
159266ccbc9cSJason Wang 	if (tfile->socket.sk->sk_sndbuf != INT_MAX)
159366ccbc9cSJason Wang 		return false;
159466ccbc9cSJason Wang 
159566ccbc9cSJason Wang 	if (!noblock)
159666ccbc9cSJason Wang 		return false;
159766ccbc9cSJason Wang 
159866ccbc9cSJason Wang 	if (zerocopy)
159966ccbc9cSJason Wang 		return false;
160066ccbc9cSJason Wang 
160166ccbc9cSJason Wang 	if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
160266ccbc9cSJason Wang 	    SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
160366ccbc9cSJason Wang 		return false;
160466ccbc9cSJason Wang 
160566ccbc9cSJason Wang 	return true;
160666ccbc9cSJason Wang }
160766ccbc9cSJason Wang 
1608761876c8SJason Wang static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1609761876c8SJason Wang 				     struct tun_file *tfile,
161066ccbc9cSJason Wang 				     struct iov_iter *from,
1611761876c8SJason Wang 				     struct virtio_net_hdr *hdr,
16121cfe6e93SJason Wang 				     int len, int *skb_xdp)
161366ccbc9cSJason Wang {
16140bbd7dadSEric Dumazet 	struct page_frag *alloc_frag = &current->task_frag;
161566ccbc9cSJason Wang 	struct sk_buff *skb;
1616761876c8SJason Wang 	struct bpf_prog *xdp_prog;
16177df13219SJason Wang 	int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1618761876c8SJason Wang 	unsigned int delta = 0;
161966ccbc9cSJason Wang 	char *buf;
162066ccbc9cSJason Wang 	size_t copied;
16217df13219SJason Wang 	int err, pad = TUN_RX_PAD;
16227df13219SJason Wang 
16237df13219SJason Wang 	rcu_read_lock();
16247df13219SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
16257df13219SJason Wang 	if (xdp_prog)
16267df13219SJason Wang 		pad += TUN_HEADROOM;
16277df13219SJason Wang 	buflen += SKB_DATA_ALIGN(len + pad);
16287df13219SJason Wang 	rcu_read_unlock();
162966ccbc9cSJason Wang 
163063b9ab65SJason Wang 	alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
163166ccbc9cSJason Wang 	if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
163266ccbc9cSJason Wang 		return ERR_PTR(-ENOMEM);
163366ccbc9cSJason Wang 
163466ccbc9cSJason Wang 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
163566ccbc9cSJason Wang 	copied = copy_page_from_iter(alloc_frag->page,
16367df13219SJason Wang 				     alloc_frag->offset + pad,
163766ccbc9cSJason Wang 				     len, from);
163866ccbc9cSJason Wang 	if (copied != len)
163966ccbc9cSJason Wang 		return ERR_PTR(-EFAULT);
164066ccbc9cSJason Wang 
16417df13219SJason Wang 	/* There's a small window that XDP may be set after the check
16427df13219SJason Wang 	 * of xdp_prog above, this should be rare and for simplicity
16437df13219SJason Wang 	 * we do XDP on skb in case the headroom is not enough.
16447df13219SJason Wang 	 */
16457df13219SJason Wang 	if (hdr->gso_type || !xdp_prog)
16461cfe6e93SJason Wang 		*skb_xdp = 1;
1647761876c8SJason Wang 	else
16481cfe6e93SJason Wang 		*skb_xdp = 0;
164966ccbc9cSJason Wang 
165023e43f07SJason Wang 	preempt_disable();
1651761876c8SJason Wang 	rcu_read_lock();
1652761876c8SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
16531cfe6e93SJason Wang 	if (xdp_prog && !*skb_xdp) {
1654761876c8SJason Wang 		struct xdp_buff xdp;
1655761876c8SJason Wang 		void *orig_data;
1656761876c8SJason Wang 		u32 act;
1657761876c8SJason Wang 
1658761876c8SJason Wang 		xdp.data_hard_start = buf;
16597df13219SJason Wang 		xdp.data = buf + pad;
1660de8f3a83SDaniel Borkmann 		xdp_set_data_meta_invalid(&xdp);
1661761876c8SJason Wang 		xdp.data_end = xdp.data + len;
16628bf5c4eeSJesper Dangaard Brouer 		xdp.rxq = &tfile->xdp_rxq;
1663761876c8SJason Wang 		orig_data = xdp.data;
1664761876c8SJason Wang 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
1665761876c8SJason Wang 
1666761876c8SJason Wang 		switch (act) {
1667761876c8SJason Wang 		case XDP_REDIRECT:
1668761876c8SJason Wang 			get_page(alloc_frag->page);
1669761876c8SJason Wang 			alloc_frag->offset += buflen;
1670761876c8SJason Wang 			err = xdp_do_redirect(tun->dev, &xdp, xdp_prog);
16711bb4f2e8SJason Wang 			xdp_do_flush_map();
1672761876c8SJason Wang 			if (err)
1673761876c8SJason Wang 				goto err_redirect;
1674654d5738SXin Long 			rcu_read_unlock();
167523e43f07SJason Wang 			preempt_enable();
1676761876c8SJason Wang 			return NULL;
1677761876c8SJason Wang 		case XDP_TX:
167859655a5bSJason Wang 			get_page(alloc_frag->page);
167959655a5bSJason Wang 			alloc_frag->offset += buflen;
168059655a5bSJason Wang 			if (tun_xdp_xmit(tun->dev, &xdp))
168159655a5bSJason Wang 				goto err_redirect;
168259655a5bSJason Wang 			tun_xdp_flush(tun->dev);
168359655a5bSJason Wang 			rcu_read_unlock();
168459655a5bSJason Wang 			preempt_enable();
168559655a5bSJason Wang 			return NULL;
1686761876c8SJason Wang 		case XDP_PASS:
1687761876c8SJason Wang 			delta = orig_data - xdp.data;
1688761876c8SJason Wang 			break;
1689761876c8SJason Wang 		default:
1690761876c8SJason Wang 			bpf_warn_invalid_xdp_action(act);
1691761876c8SJason Wang 			/* fall through */
1692761876c8SJason Wang 		case XDP_ABORTED:
1693761876c8SJason Wang 			trace_xdp_exception(tun->dev, xdp_prog, act);
1694761876c8SJason Wang 			/* fall through */
1695761876c8SJason Wang 		case XDP_DROP:
1696761876c8SJason Wang 			goto err_xdp;
1697761876c8SJason Wang 		}
1698761876c8SJason Wang 	}
1699761876c8SJason Wang 
1700761876c8SJason Wang 	skb = build_skb(buf, buflen);
1701761876c8SJason Wang 	if (!skb) {
1702761876c8SJason Wang 		rcu_read_unlock();
170323e43f07SJason Wang 		preempt_enable();
1704761876c8SJason Wang 		return ERR_PTR(-ENOMEM);
1705761876c8SJason Wang 	}
1706761876c8SJason Wang 
17077df13219SJason Wang 	skb_reserve(skb, pad - delta);
1708761876c8SJason Wang 	skb_put(skb, len + delta);
170966ccbc9cSJason Wang 	get_page(alloc_frag->page);
171066ccbc9cSJason Wang 	alloc_frag->offset += buflen;
171166ccbc9cSJason Wang 
1712761876c8SJason Wang 	rcu_read_unlock();
171323e43f07SJason Wang 	preempt_enable();
1714761876c8SJason Wang 
171566ccbc9cSJason Wang 	return skb;
1716761876c8SJason Wang 
1717761876c8SJason Wang err_redirect:
1718761876c8SJason Wang 	put_page(alloc_frag->page);
1719761876c8SJason Wang err_xdp:
1720761876c8SJason Wang 	rcu_read_unlock();
172123e43f07SJason Wang 	preempt_enable();
1722761876c8SJason Wang 	this_cpu_inc(tun->pcpu_stats->rx_dropped);
1723761876c8SJason Wang 	return NULL;
172466ccbc9cSJason Wang }
172566ccbc9cSJason Wang 
17261da177e4SLinus Torvalds /* Get packet from user space buffer */
172754f968d6SJason Wang static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1728f5ff53b4SAl Viro 			    void *msg_control, struct iov_iter *from,
17295503fcecSJason Wang 			    int noblock, bool more)
17301da177e4SLinus Torvalds {
173109640e63SHarvey Harrison 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
17321da177e4SLinus Torvalds 	struct sk_buff *skb;
1733f5ff53b4SAl Viro 	size_t total_len = iov_iter_count(from);
1734eaea34b2SPaolo Abeni 	size_t len = total_len, align = tun->align, linear;
1735f43798c2SRusty Russell 	struct virtio_net_hdr gso = { 0 };
1736608b9977SPaolo Abeni 	struct tun_pcpu_stats *stats;
173796f8d9ecSJason Wang 	int good_linear;
17380690899bSMichael S. Tsirkin 	int copylen;
17390690899bSMichael S. Tsirkin 	bool zerocopy = false;
17400690899bSMichael S. Tsirkin 	int err;
174196f84061SJason Wang 	u32 rxhash = 0;
17421cfe6e93SJason Wang 	int skb_xdp = 1;
174390e33d45SPetar Penkov 	bool frags = tun_napi_frags_enabled(tun);
17441da177e4SLinus Torvalds 
17451bd4978aSEric Dumazet 	if (!(tun->dev->flags & IFF_UP))
17461bd4978aSEric Dumazet 		return -EIO;
17471bd4978aSEric Dumazet 
174840630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
174915718ea0SDan Carpenter 		if (len < sizeof(pi))
17501da177e4SLinus Torvalds 			return -EINVAL;
175115718ea0SDan Carpenter 		len -= sizeof(pi);
17521da177e4SLinus Torvalds 
1753cbbd26b8SAl Viro 		if (!copy_from_iter_full(&pi, sizeof(pi), from))
17541da177e4SLinus Torvalds 			return -EFAULT;
17551da177e4SLinus Torvalds 	}
17561da177e4SLinus Torvalds 
175740630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR) {
1758e1edab87SWillem de Bruijn 		int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1759e1edab87SWillem de Bruijn 
1760e1edab87SWillem de Bruijn 		if (len < vnet_hdr_sz)
1761f43798c2SRusty Russell 			return -EINVAL;
1762e1edab87SWillem de Bruijn 		len -= vnet_hdr_sz;
1763f43798c2SRusty Russell 
1764cbbd26b8SAl Viro 		if (!copy_from_iter_full(&gso, sizeof(gso), from))
1765f43798c2SRusty Russell 			return -EFAULT;
1766f43798c2SRusty Russell 
17674909122fSHerbert Xu 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
176856f0dcc5SMichael S. Tsirkin 		    tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
176956f0dcc5SMichael S. Tsirkin 			gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
17704909122fSHerbert Xu 
177156f0dcc5SMichael S. Tsirkin 		if (tun16_to_cpu(tun, gso.hdr_len) > len)
1772f43798c2SRusty Russell 			return -EINVAL;
1773e1edab87SWillem de Bruijn 		iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1774f43798c2SRusty Russell 	}
1775f43798c2SRusty Russell 
177640630b82SMichael S. Tsirkin 	if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1777a504b86eSstephen hemminger 		align += NET_IP_ALIGN;
17780eca93bcSHerbert Xu 		if (unlikely(len < ETH_HLEN ||
177956f0dcc5SMichael S. Tsirkin 			     (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1780e01bf1c8SRusty Russell 			return -EINVAL;
1781e01bf1c8SRusty Russell 	}
17821da177e4SLinus Torvalds 
178396f8d9ecSJason Wang 	good_linear = SKB_MAX_HEAD(align);
178496f8d9ecSJason Wang 
178588529176SJason Wang 	if (msg_control) {
1786f5ff53b4SAl Viro 		struct iov_iter i = *from;
1787f5ff53b4SAl Viro 
178888529176SJason Wang 		/* There are 256 bytes to be copied in skb, so there is
178988529176SJason Wang 		 * enough room for skb expand head in case it is used.
17900690899bSMichael S. Tsirkin 		 * The rest of the buffer is mapped from userspace.
17910690899bSMichael S. Tsirkin 		 */
179256f0dcc5SMichael S. Tsirkin 		copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
179396f8d9ecSJason Wang 		if (copylen > good_linear)
179496f8d9ecSJason Wang 			copylen = good_linear;
17953dd5c330SJason Wang 		linear = copylen;
1796f5ff53b4SAl Viro 		iov_iter_advance(&i, copylen);
1797f5ff53b4SAl Viro 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
179888529176SJason Wang 			zerocopy = true;
179988529176SJason Wang 	}
180088529176SJason Wang 
180190e33d45SPetar Penkov 	if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
18021cfe6e93SJason Wang 		/* For the packet that is not easy to be processed
18031cfe6e93SJason Wang 		 * (e.g gso or jumbo packet), we will do it at after
18041cfe6e93SJason Wang 		 * skb was created with generic XDP routine.
18051cfe6e93SJason Wang 		 */
18061cfe6e93SJason Wang 		skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
180766ccbc9cSJason Wang 		if (IS_ERR(skb)) {
180866ccbc9cSJason Wang 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
180966ccbc9cSJason Wang 			return PTR_ERR(skb);
181066ccbc9cSJason Wang 		}
1811761876c8SJason Wang 		if (!skb)
1812761876c8SJason Wang 			return total_len;
181366ccbc9cSJason Wang 	} else {
181488529176SJason Wang 		if (!zerocopy) {
18150690899bSMichael S. Tsirkin 			copylen = len;
181656f0dcc5SMichael S. Tsirkin 			if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
181796f8d9ecSJason Wang 				linear = good_linear;
181896f8d9ecSJason Wang 			else
181956f0dcc5SMichael S. Tsirkin 				linear = tun16_to_cpu(tun, gso.hdr_len);
18203dd5c330SJason Wang 		}
18210690899bSMichael S. Tsirkin 
182290e33d45SPetar Penkov 		if (frags) {
182390e33d45SPetar Penkov 			mutex_lock(&tfile->napi_mutex);
182490e33d45SPetar Penkov 			skb = tun_napi_alloc_frags(tfile, copylen, from);
182590e33d45SPetar Penkov 			/* tun_napi_alloc_frags() enforces a layout for the skb.
182690e33d45SPetar Penkov 			 * If zerocopy is enabled, then this layout will be
182790e33d45SPetar Penkov 			 * overwritten by zerocopy_sg_from_iter().
182890e33d45SPetar Penkov 			 */
182990e33d45SPetar Penkov 			zerocopy = false;
183090e33d45SPetar Penkov 		} else {
183190e33d45SPetar Penkov 			skb = tun_alloc_skb(tfile, align, copylen, linear,
183290e33d45SPetar Penkov 					    noblock);
183390e33d45SPetar Penkov 		}
183490e33d45SPetar Penkov 
183533dccbb0SHerbert Xu 		if (IS_ERR(skb)) {
183633dccbb0SHerbert Xu 			if (PTR_ERR(skb) != -EAGAIN)
1837608b9977SPaolo Abeni 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
183890e33d45SPetar Penkov 			if (frags)
183990e33d45SPetar Penkov 				mutex_unlock(&tfile->napi_mutex);
184033dccbb0SHerbert Xu 			return PTR_ERR(skb);
18411da177e4SLinus Torvalds 		}
18421da177e4SLinus Torvalds 
18430690899bSMichael S. Tsirkin 		if (zerocopy)
1844f5ff53b4SAl Viro 			err = zerocopy_sg_from_iter(skb, from);
1845af1cc7a2SJason Wang 		else
1846f5ff53b4SAl Viro 			err = skb_copy_datagram_from_iter(skb, 0, from, len);
18470690899bSMichael S. Tsirkin 
18480690899bSMichael S. Tsirkin 		if (err) {
1849608b9977SPaolo Abeni 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
18508f22757eSDave Jones 			kfree_skb(skb);
185190e33d45SPetar Penkov 			if (frags) {
185290e33d45SPetar Penkov 				tfile->napi.skb = NULL;
185390e33d45SPetar Penkov 				mutex_unlock(&tfile->napi_mutex);
185490e33d45SPetar Penkov 			}
185590e33d45SPetar Penkov 
18561da177e4SLinus Torvalds 			return -EFAULT;
18578f22757eSDave Jones 		}
185866ccbc9cSJason Wang 	}
18591da177e4SLinus Torvalds 
18603e9e40e7SJarno Rajahalme 	if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1861df10db98SPaolo Abeni 		this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1862df10db98SPaolo Abeni 		kfree_skb(skb);
186390e33d45SPetar Penkov 		if (frags) {
186490e33d45SPetar Penkov 			tfile->napi.skb = NULL;
186590e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
186690e33d45SPetar Penkov 		}
186790e33d45SPetar Penkov 
1868df10db98SPaolo Abeni 		return -EINVAL;
1869df10db98SPaolo Abeni 	}
1870df10db98SPaolo Abeni 
18711da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
187240630b82SMichael S. Tsirkin 	case IFF_TUN:
187340630b82SMichael S. Tsirkin 		if (tun->flags & IFF_NO_PI) {
18742580c4c1SAlexander Potapenko 			u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
18752580c4c1SAlexander Potapenko 
18762580c4c1SAlexander Potapenko 			switch (ip_version) {
18772580c4c1SAlexander Potapenko 			case 4:
1878f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IP);
1879f09f7ee2SAng Way Chuang 				break;
18802580c4c1SAlexander Potapenko 			case 6:
1881f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IPV6);
1882f09f7ee2SAng Way Chuang 				break;
1883f09f7ee2SAng Way Chuang 			default:
1884608b9977SPaolo Abeni 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
1885f09f7ee2SAng Way Chuang 				kfree_skb(skb);
1886f09f7ee2SAng Way Chuang 				return -EINVAL;
1887f09f7ee2SAng Way Chuang 			}
1888f09f7ee2SAng Way Chuang 		}
1889f09f7ee2SAng Way Chuang 
1890459a98edSArnaldo Carvalho de Melo 		skb_reset_mac_header(skb);
18911da177e4SLinus Torvalds 		skb->protocol = pi.proto;
18924c13eb66SArnaldo Carvalho de Melo 		skb->dev = tun->dev;
18931da177e4SLinus Torvalds 		break;
189440630b82SMichael S. Tsirkin 	case IFF_TAP:
189590e33d45SPetar Penkov 		if (!frags)
18961da177e4SLinus Torvalds 			skb->protocol = eth_type_trans(skb, tun->dev);
18971da177e4SLinus Torvalds 		break;
18986403eab1SJoe Perches 	}
18991da177e4SLinus Torvalds 
19000690899bSMichael S. Tsirkin 	/* copy skb_ubuf_info for callback when skb has no error */
19010690899bSMichael S. Tsirkin 	if (zerocopy) {
19020690899bSMichael S. Tsirkin 		skb_shinfo(skb)->destructor_arg = msg_control;
19030690899bSMichael S. Tsirkin 		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1904c9af6db4SPravin B Shelar 		skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1905af1cc7a2SJason Wang 	} else if (msg_control) {
1906af1cc7a2SJason Wang 		struct ubuf_info *uarg = msg_control;
1907af1cc7a2SJason Wang 		uarg->callback(uarg, false);
19080690899bSMichael S. Tsirkin 	}
19090690899bSMichael S. Tsirkin 
191072f65107SVlad Yasevich 	skb_reset_network_header(skb);
191140893fd0SJason Wang 	skb_probe_transport_header(skb, 0);
191238502af7SJason Wang 
19131cfe6e93SJason Wang 	if (skb_xdp) {
1914761876c8SJason Wang 		struct bpf_prog *xdp_prog;
1915761876c8SJason Wang 		int ret;
1916761876c8SJason Wang 
1917761876c8SJason Wang 		rcu_read_lock();
1918761876c8SJason Wang 		xdp_prog = rcu_dereference(tun->xdp_prog);
1919761876c8SJason Wang 		if (xdp_prog) {
1920761876c8SJason Wang 			ret = do_xdp_generic(xdp_prog, skb);
1921761876c8SJason Wang 			if (ret != XDP_PASS) {
1922761876c8SJason Wang 				rcu_read_unlock();
1923761876c8SJason Wang 				return total_len;
1924761876c8SJason Wang 			}
1925761876c8SJason Wang 		}
1926761876c8SJason Wang 		rcu_read_unlock();
1927761876c8SJason Wang 	}
1928761876c8SJason Wang 
192996f84061SJason Wang 	rcu_read_lock();
193096f84061SJason Wang 	if (!rcu_dereference(tun->steering_prog))
1931feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
193296f84061SJason Wang 	rcu_read_unlock();
193394317099SPetar Penkov 
193490e33d45SPetar Penkov 	if (frags) {
193590e33d45SPetar Penkov 		/* Exercise flow dissector code path. */
193690e33d45SPetar Penkov 		u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
193790e33d45SPetar Penkov 
1938010f245bSEric Dumazet 		if (unlikely(headlen > skb_headlen(skb))) {
193990e33d45SPetar Penkov 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
194090e33d45SPetar Penkov 			napi_free_frags(&tfile->napi);
194190e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
194290e33d45SPetar Penkov 			WARN_ON(1);
194390e33d45SPetar Penkov 			return -ENOMEM;
194490e33d45SPetar Penkov 		}
194590e33d45SPetar Penkov 
194690e33d45SPetar Penkov 		local_bh_disable();
194790e33d45SPetar Penkov 		napi_gro_frags(&tfile->napi);
194890e33d45SPetar Penkov 		local_bh_enable();
194990e33d45SPetar Penkov 		mutex_unlock(&tfile->napi_mutex);
1950aec72f33SEric Dumazet 	} else if (tfile->napi_enabled) {
195194317099SPetar Penkov 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
195294317099SPetar Penkov 		int queue_len;
195394317099SPetar Penkov 
195494317099SPetar Penkov 		spin_lock_bh(&queue->lock);
195594317099SPetar Penkov 		__skb_queue_tail(queue, skb);
195694317099SPetar Penkov 		queue_len = skb_queue_len(queue);
195794317099SPetar Penkov 		spin_unlock(&queue->lock);
195894317099SPetar Penkov 
195994317099SPetar Penkov 		if (!more || queue_len > NAPI_POLL_WEIGHT)
196094317099SPetar Penkov 			napi_schedule(&tfile->napi);
196194317099SPetar Penkov 
196294317099SPetar Penkov 		local_bh_enable();
196394317099SPetar Penkov 	} else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
19645503fcecSJason Wang 		tun_rx_batched(tun, tfile, skb, more);
196594317099SPetar Penkov 	} else {
19661da177e4SLinus Torvalds 		netif_rx_ni(skb);
196794317099SPetar Penkov 	}
19681da177e4SLinus Torvalds 
1969608b9977SPaolo Abeni 	stats = get_cpu_ptr(tun->pcpu_stats);
1970608b9977SPaolo Abeni 	u64_stats_update_begin(&stats->syncp);
1971608b9977SPaolo Abeni 	stats->rx_packets++;
1972608b9977SPaolo Abeni 	stats->rx_bytes += len;
1973608b9977SPaolo Abeni 	u64_stats_update_end(&stats->syncp);
1974608b9977SPaolo Abeni 	put_cpu_ptr(stats);
19751da177e4SLinus Torvalds 
197696f84061SJason Wang 	if (rxhash)
19779e85722dSJason Wang 		tun_flow_update(tun, rxhash, tfile);
197896f84061SJason Wang 
19790690899bSMichael S. Tsirkin 	return total_len;
19801da177e4SLinus Torvalds }
19811da177e4SLinus Torvalds 
1982f5ff53b4SAl Viro static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
19831da177e4SLinus Torvalds {
198433dccbb0SHerbert Xu 	struct file *file = iocb->ki_filp;
198554f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
19869484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
1987631ab46bSEric W. Biederman 	ssize_t result;
19881da177e4SLinus Torvalds 
19891da177e4SLinus Torvalds 	if (!tun)
19901da177e4SLinus Torvalds 		return -EBADFD;
19911da177e4SLinus Torvalds 
19925503fcecSJason Wang 	result = tun_get_user(tun, tfile, NULL, from,
19935503fcecSJason Wang 			      file->f_flags & O_NONBLOCK, false);
1994631ab46bSEric W. Biederman 
1995631ab46bSEric W. Biederman 	tun_put(tun);
1996631ab46bSEric W. Biederman 	return result;
19971da177e4SLinus Torvalds }
19981da177e4SLinus Torvalds 
1999fc72d1d5SJason Wang static ssize_t tun_put_user_xdp(struct tun_struct *tun,
2000fc72d1d5SJason Wang 				struct tun_file *tfile,
2001*1ffcbc85SJesper Dangaard Brouer 				struct xdp_frame *xdp_frame,
2002fc72d1d5SJason Wang 				struct iov_iter *iter)
2003fc72d1d5SJason Wang {
2004fc72d1d5SJason Wang 	int vnet_hdr_sz = 0;
2005*1ffcbc85SJesper Dangaard Brouer 	size_t size = xdp_frame->len;
2006fc72d1d5SJason Wang 	struct tun_pcpu_stats *stats;
2007fc72d1d5SJason Wang 	size_t ret;
2008fc72d1d5SJason Wang 
2009fc72d1d5SJason Wang 	if (tun->flags & IFF_VNET_HDR) {
2010fc72d1d5SJason Wang 		struct virtio_net_hdr gso = { 0 };
2011fc72d1d5SJason Wang 
2012fc72d1d5SJason Wang 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2013fc72d1d5SJason Wang 		if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
2014fc72d1d5SJason Wang 			return -EINVAL;
2015fc72d1d5SJason Wang 		if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
2016fc72d1d5SJason Wang 			     sizeof(gso)))
2017fc72d1d5SJason Wang 			return -EFAULT;
2018fc72d1d5SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2019fc72d1d5SJason Wang 	}
2020fc72d1d5SJason Wang 
2021*1ffcbc85SJesper Dangaard Brouer 	ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
2022fc72d1d5SJason Wang 
2023fc72d1d5SJason Wang 	stats = get_cpu_ptr(tun->pcpu_stats);
2024fc72d1d5SJason Wang 	u64_stats_update_begin(&stats->syncp);
2025fc72d1d5SJason Wang 	stats->tx_packets++;
2026fc72d1d5SJason Wang 	stats->tx_bytes += ret;
2027fc72d1d5SJason Wang 	u64_stats_update_end(&stats->syncp);
2028fc72d1d5SJason Wang 	put_cpu_ptr(tun->pcpu_stats);
2029fc72d1d5SJason Wang 
2030fc72d1d5SJason Wang 	return ret;
2031fc72d1d5SJason Wang }
2032fc72d1d5SJason Wang 
20331da177e4SLinus Torvalds /* Put packet to the user space buffer */
20346f7c156cSstephen hemminger static ssize_t tun_put_user(struct tun_struct *tun,
203554f968d6SJason Wang 			    struct tun_file *tfile,
20361da177e4SLinus Torvalds 			    struct sk_buff *skb,
2037e0b46d0eSHerbert Xu 			    struct iov_iter *iter)
20381da177e4SLinus Torvalds {
20391da177e4SLinus Torvalds 	struct tun_pi pi = { 0, skb->protocol };
2040608b9977SPaolo Abeni 	struct tun_pcpu_stats *stats;
2041e0b46d0eSHerbert Xu 	ssize_t total;
20428c847d25SJason Wang 	int vlan_offset = 0;
2043a8f9bfdfSHerbert Xu 	int vlan_hlen = 0;
20442eb783c4SHerbert Xu 	int vnet_hdr_sz = 0;
2045a8f9bfdfSHerbert Xu 
2046df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb))
2047a8f9bfdfSHerbert Xu 		vlan_hlen = VLAN_HLEN;
20481da177e4SLinus Torvalds 
204940630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR)
2050e1edab87SWillem de Bruijn 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
20511da177e4SLinus Torvalds 
2052e0b46d0eSHerbert Xu 	total = skb->len + vlan_hlen + vnet_hdr_sz;
2053e0b46d0eSHerbert Xu 
205440630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
2055e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < sizeof(pi))
20561da177e4SLinus Torvalds 			return -EINVAL;
20571da177e4SLinus Torvalds 
2058e0b46d0eSHerbert Xu 		total += sizeof(pi);
2059e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < total) {
20601da177e4SLinus Torvalds 			/* Packet will be striped */
20611da177e4SLinus Torvalds 			pi.flags |= TUN_PKT_STRIP;
20621da177e4SLinus Torvalds 		}
20631da177e4SLinus Torvalds 
2064e0b46d0eSHerbert Xu 		if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
20651da177e4SLinus Torvalds 			return -EFAULT;
20661da177e4SLinus Torvalds 	}
20671da177e4SLinus Torvalds 
20682eb783c4SHerbert Xu 	if (vnet_hdr_sz) {
20699403cd7cSJarno Rajahalme 		struct virtio_net_hdr gso;
207034166093SMike Rapoport 
2071e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < vnet_hdr_sz)
2072f43798c2SRusty Russell 			return -EINVAL;
2073f43798c2SRusty Russell 
20743e9e40e7SJarno Rajahalme 		if (virtio_net_hdr_from_skb(skb, &gso,
20756391a448SJason Wang 					    tun_is_little_endian(tun), true)) {
2076f43798c2SRusty Russell 			struct skb_shared_info *sinfo = skb_shinfo(skb);
20776b8a66eeSJoe Perches 			pr_err("unexpected GSO type: "
2078ef3db4a5SMichael S. Tsirkin 			       "0x%x, gso_size %d, hdr_len %d\n",
207956f0dcc5SMichael S. Tsirkin 			       sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
208056f0dcc5SMichael S. Tsirkin 			       tun16_to_cpu(tun, gso.hdr_len));
2081ef3db4a5SMichael S. Tsirkin 			print_hex_dump(KERN_ERR, "tun: ",
2082ef3db4a5SMichael S. Tsirkin 				       DUMP_PREFIX_NONE,
2083ef3db4a5SMichael S. Tsirkin 				       16, 1, skb->head,
208456f0dcc5SMichael S. Tsirkin 				       min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
2085ef3db4a5SMichael S. Tsirkin 			WARN_ON_ONCE(1);
2086ef3db4a5SMichael S. Tsirkin 			return -EINVAL;
2087ef3db4a5SMichael S. Tsirkin 		}
2088f43798c2SRusty Russell 
2089e0b46d0eSHerbert Xu 		if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
2090f43798c2SRusty Russell 			return -EFAULT;
20918c847d25SJason Wang 
20928c847d25SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2093f43798c2SRusty Russell 	}
2094f43798c2SRusty Russell 
2095a8f9bfdfSHerbert Xu 	if (vlan_hlen) {
2096e0b46d0eSHerbert Xu 		int ret;
2097aff3d70aSJason Wang 		struct veth veth;
20981da177e4SLinus Torvalds 
20996680ec68SJason Wang 		veth.h_vlan_proto = skb->vlan_proto;
2100df8a39deSJiri Pirko 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
21011da177e4SLinus Torvalds 
21026680ec68SJason Wang 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
21036680ec68SJason Wang 
2104e0b46d0eSHerbert Xu 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
2105e0b46d0eSHerbert Xu 		if (ret || !iov_iter_count(iter))
21066680ec68SJason Wang 			goto done;
21076680ec68SJason Wang 
2108e0b46d0eSHerbert Xu 		ret = copy_to_iter(&veth, sizeof(veth), iter);
2109e0b46d0eSHerbert Xu 		if (ret != sizeof(veth) || !iov_iter_count(iter))
21106680ec68SJason Wang 			goto done;
21116680ec68SJason Wang 	}
21126680ec68SJason Wang 
2113e0b46d0eSHerbert Xu 	skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
21146680ec68SJason Wang 
21156680ec68SJason Wang done:
2116608b9977SPaolo Abeni 	/* caller is in process context, */
2117608b9977SPaolo Abeni 	stats = get_cpu_ptr(tun->pcpu_stats);
2118608b9977SPaolo Abeni 	u64_stats_update_begin(&stats->syncp);
2119608b9977SPaolo Abeni 	stats->tx_packets++;
2120608b9977SPaolo Abeni 	stats->tx_bytes += skb->len + vlan_hlen;
2121608b9977SPaolo Abeni 	u64_stats_update_end(&stats->syncp);
2122608b9977SPaolo Abeni 	put_cpu_ptr(tun->pcpu_stats);
21231da177e4SLinus Torvalds 
21241da177e4SLinus Torvalds 	return total;
21251da177e4SLinus Torvalds }
21261da177e4SLinus Torvalds 
2127fc72d1d5SJason Wang static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
21281576d986SJason Wang {
21291576d986SJason Wang 	DECLARE_WAITQUEUE(wait, current);
2130fc72d1d5SJason Wang 	void *ptr = NULL;
2131f48cc6b2SJason Wang 	int error = 0;
21321576d986SJason Wang 
2133fc72d1d5SJason Wang 	ptr = ptr_ring_consume(&tfile->tx_ring);
2134fc72d1d5SJason Wang 	if (ptr)
21351576d986SJason Wang 		goto out;
21361576d986SJason Wang 	if (noblock) {
2137f48cc6b2SJason Wang 		error = -EAGAIN;
21381576d986SJason Wang 		goto out;
21391576d986SJason Wang 	}
21401576d986SJason Wang 
21411576d986SJason Wang 	add_wait_queue(&tfile->wq.wait, &wait);
21421576d986SJason Wang 	current->state = TASK_INTERRUPTIBLE;
21431576d986SJason Wang 
21441576d986SJason Wang 	while (1) {
2145fc72d1d5SJason Wang 		ptr = ptr_ring_consume(&tfile->tx_ring);
2146fc72d1d5SJason Wang 		if (ptr)
21471576d986SJason Wang 			break;
21481576d986SJason Wang 		if (signal_pending(current)) {
2149f48cc6b2SJason Wang 			error = -ERESTARTSYS;
21501576d986SJason Wang 			break;
21511576d986SJason Wang 		}
21521576d986SJason Wang 		if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
2153f48cc6b2SJason Wang 			error = -EFAULT;
21541576d986SJason Wang 			break;
21551576d986SJason Wang 		}
21561576d986SJason Wang 
21571576d986SJason Wang 		schedule();
21581576d986SJason Wang 	}
21591576d986SJason Wang 
21601576d986SJason Wang 	current->state = TASK_RUNNING;
21611576d986SJason Wang 	remove_wait_queue(&tfile->wq.wait, &wait);
21621576d986SJason Wang 
21631576d986SJason Wang out:
2164f48cc6b2SJason Wang 	*err = error;
2165fc72d1d5SJason Wang 	return ptr;
21661576d986SJason Wang }
21671576d986SJason Wang 
216854f968d6SJason Wang static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
21699b067034SAl Viro 			   struct iov_iter *to,
2170fc72d1d5SJason Wang 			   int noblock, void *ptr)
21711da177e4SLinus Torvalds {
21729b067034SAl Viro 	ssize_t ret;
21731576d986SJason Wang 	int err;
21741da177e4SLinus Torvalds 
21753872baf6SRami Rosen 	tun_debug(KERN_INFO, tun, "tun_do_read\n");
21761da177e4SLinus Torvalds 
2177c33ee15bSWei Xu 	if (!iov_iter_count(to)) {
2178fc72d1d5SJason Wang 		tun_ptr_free(ptr);
21799b067034SAl Viro 		return 0;
2180c33ee15bSWei Xu 	}
21811da177e4SLinus Torvalds 
2182fc72d1d5SJason Wang 	if (!ptr) {
21831576d986SJason Wang 		/* Read frames from ring */
2184fc72d1d5SJason Wang 		ptr = tun_ring_recv(tfile, noblock, &err);
2185fc72d1d5SJason Wang 		if (!ptr)
2186957f094fSAlex Gartrell 			return err;
2187ac77cfd4SJason Wang 	}
2188e0b46d0eSHerbert Xu 
2189*1ffcbc85SJesper Dangaard Brouer 	if (tun_is_xdp_frame(ptr)) {
2190*1ffcbc85SJesper Dangaard Brouer 		struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2191fc72d1d5SJason Wang 
2192*1ffcbc85SJesper Dangaard Brouer 		ret = tun_put_user_xdp(tun, tfile, xdpf, to);
2193*1ffcbc85SJesper Dangaard Brouer 		xdp_return_frame(xdpf->data, &xdpf->mem);
2194fc72d1d5SJason Wang 	} else {
2195fc72d1d5SJason Wang 		struct sk_buff *skb = ptr;
2196fc72d1d5SJason Wang 
21979b067034SAl Viro 		ret = tun_put_user(tun, tfile, skb, to);
2198f51a5e82SJason Wang 		if (unlikely(ret < 0))
21991da177e4SLinus Torvalds 			kfree_skb(skb);
2200f51a5e82SJason Wang 		else
2201f51a5e82SJason Wang 			consume_skb(skb);
2202fc72d1d5SJason Wang 	}
22031da177e4SLinus Torvalds 
220405c2828cSMichael S. Tsirkin 	return ret;
220505c2828cSMichael S. Tsirkin }
220605c2828cSMichael S. Tsirkin 
22079b067034SAl Viro static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
220805c2828cSMichael S. Tsirkin {
220905c2828cSMichael S. Tsirkin 	struct file *file = iocb->ki_filp;
221005c2828cSMichael S. Tsirkin 	struct tun_file *tfile = file->private_data;
22119484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
22129b067034SAl Viro 	ssize_t len = iov_iter_count(to), ret;
221305c2828cSMichael S. Tsirkin 
221405c2828cSMichael S. Tsirkin 	if (!tun)
221505c2828cSMichael S. Tsirkin 		return -EBADFD;
2216ac77cfd4SJason Wang 	ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
221742404c09SDavid S. Miller 	ret = min_t(ssize_t, ret, len);
2218d0b7da8aSZhi Yong Wu 	if (ret > 0)
2219d0b7da8aSZhi Yong Wu 		iocb->ki_pos = ret;
2220631ab46bSEric W. Biederman 	tun_put(tun);
22211da177e4SLinus Torvalds 	return ret;
22221da177e4SLinus Torvalds }
22231da177e4SLinus Torvalds 
2224cd5681d7SJason Wang static void tun_prog_free(struct rcu_head *rcu)
222596f84061SJason Wang {
2226cd5681d7SJason Wang 	struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
222796f84061SJason Wang 
222896f84061SJason Wang 	bpf_prog_destroy(prog->prog);
222996f84061SJason Wang 	kfree(prog);
223096f84061SJason Wang }
223196f84061SJason Wang 
22329d6474e4SJason Wang static int __tun_set_ebpf(struct tun_struct *tun,
22339d6474e4SJason Wang 			  struct tun_prog __rcu **prog_p,
223496f84061SJason Wang 			  struct bpf_prog *prog)
223596f84061SJason Wang {
2236cd5681d7SJason Wang 	struct tun_prog *old, *new = NULL;
223796f84061SJason Wang 
223896f84061SJason Wang 	if (prog) {
223996f84061SJason Wang 		new = kmalloc(sizeof(*new), GFP_KERNEL);
224096f84061SJason Wang 		if (!new)
224196f84061SJason Wang 			return -ENOMEM;
224296f84061SJason Wang 		new->prog = prog;
224396f84061SJason Wang 	}
224496f84061SJason Wang 
2245124da8f6SJason Wang 	spin_lock_bh(&tun->lock);
2246cd5681d7SJason Wang 	old = rcu_dereference_protected(*prog_p,
2247124da8f6SJason Wang 					lockdep_is_held(&tun->lock));
2248cd5681d7SJason Wang 	rcu_assign_pointer(*prog_p, new);
2249124da8f6SJason Wang 	spin_unlock_bh(&tun->lock);
225096f84061SJason Wang 
225196f84061SJason Wang 	if (old)
2252cd5681d7SJason Wang 		call_rcu(&old->rcu, tun_prog_free);
225396f84061SJason Wang 
225496f84061SJason Wang 	return 0;
225596f84061SJason Wang }
225696f84061SJason Wang 
225796442e42SJason Wang static void tun_free_netdev(struct net_device *dev)
225896442e42SJason Wang {
225996442e42SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
226096442e42SJason Wang 
22614008e97fSJason Wang 	BUG_ON(!(list_empty(&tun->disabled)));
2262608b9977SPaolo Abeni 	free_percpu(tun->pcpu_stats);
226396442e42SJason Wang 	tun_flow_uninit(tun);
22645dbbaf2dSPaul Moore 	security_tun_dev_free_security(tun->security);
2265cd5681d7SJason Wang 	__tun_set_ebpf(tun, &tun->steering_prog, NULL);
2266aff3d70aSJason Wang 	__tun_set_ebpf(tun, &tun->filter_prog, NULL);
226796442e42SJason Wang }
226896442e42SJason Wang 
22691da177e4SLinus Torvalds static void tun_setup(struct net_device *dev)
22701da177e4SLinus Torvalds {
22711da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
22721da177e4SLinus Torvalds 
22730625c883SEric W. Biederman 	tun->owner = INVALID_UID;
22740625c883SEric W. Biederman 	tun->group = INVALID_GID;
22751da177e4SLinus Torvalds 
22761da177e4SLinus Torvalds 	dev->ethtool_ops = &tun_ethtool_ops;
2277cf124db5SDavid S. Miller 	dev->needs_free_netdev = true;
2278cf124db5SDavid S. Miller 	dev->priv_destructor = tun_free_netdev;
2279016adb72SJason Wang 	/* We prefer our own queue length */
2280016adb72SJason Wang 	dev->tx_queue_len = TUN_READQ_SIZE;
22811da177e4SLinus Torvalds }
22821da177e4SLinus Torvalds 
2283f019a7a5SEric W. Biederman /* Trivial set of netlink ops to allow deleting tun or tap
2284f019a7a5SEric W. Biederman  * device with netlink.
2285f019a7a5SEric W. Biederman  */
2286a8b8a889SMatthias Schiffer static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2287a8b8a889SMatthias Schiffer 			struct netlink_ext_ack *extack)
2288f019a7a5SEric W. Biederman {
2289f019a7a5SEric W. Biederman 	return -EINVAL;
2290f019a7a5SEric W. Biederman }
2291f019a7a5SEric W. Biederman 
22921ec010e7SSabrina Dubroca static size_t tun_get_size(const struct net_device *dev)
22931ec010e7SSabrina Dubroca {
22941ec010e7SSabrina Dubroca 	BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
22951ec010e7SSabrina Dubroca 	BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
22961ec010e7SSabrina Dubroca 
22971ec010e7SSabrina Dubroca 	return nla_total_size(sizeof(uid_t)) + /* OWNER */
22981ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(gid_t)) + /* GROUP */
22991ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* TYPE */
23001ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* PI */
23011ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* VNET_HDR */
23021ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* PERSIST */
23031ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
23041ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
23051ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
23061ec010e7SSabrina Dubroca 	       0;
23071ec010e7SSabrina Dubroca }
23081ec010e7SSabrina Dubroca 
23091ec010e7SSabrina Dubroca static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
23101ec010e7SSabrina Dubroca {
23111ec010e7SSabrina Dubroca 	struct tun_struct *tun = netdev_priv(dev);
23121ec010e7SSabrina Dubroca 
23131ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
23141ec010e7SSabrina Dubroca 		goto nla_put_failure;
23151ec010e7SSabrina Dubroca 	if (uid_valid(tun->owner) &&
23161ec010e7SSabrina Dubroca 	    nla_put_u32(skb, IFLA_TUN_OWNER,
23171ec010e7SSabrina Dubroca 			from_kuid_munged(current_user_ns(), tun->owner)))
23181ec010e7SSabrina Dubroca 		goto nla_put_failure;
23191ec010e7SSabrina Dubroca 	if (gid_valid(tun->group) &&
23201ec010e7SSabrina Dubroca 	    nla_put_u32(skb, IFLA_TUN_GROUP,
23211ec010e7SSabrina Dubroca 			from_kgid_munged(current_user_ns(), tun->group)))
23221ec010e7SSabrina Dubroca 		goto nla_put_failure;
23231ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
23241ec010e7SSabrina Dubroca 		goto nla_put_failure;
23251ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
23261ec010e7SSabrina Dubroca 		goto nla_put_failure;
23271ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
23281ec010e7SSabrina Dubroca 		goto nla_put_failure;
23291ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
23301ec010e7SSabrina Dubroca 		       !!(tun->flags & IFF_MULTI_QUEUE)))
23311ec010e7SSabrina Dubroca 		goto nla_put_failure;
23321ec010e7SSabrina Dubroca 	if (tun->flags & IFF_MULTI_QUEUE) {
23331ec010e7SSabrina Dubroca 		if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
23341ec010e7SSabrina Dubroca 			goto nla_put_failure;
23351ec010e7SSabrina Dubroca 		if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
23361ec010e7SSabrina Dubroca 				tun->numdisabled))
23371ec010e7SSabrina Dubroca 			goto nla_put_failure;
23381ec010e7SSabrina Dubroca 	}
23391ec010e7SSabrina Dubroca 
23401ec010e7SSabrina Dubroca 	return 0;
23411ec010e7SSabrina Dubroca 
23421ec010e7SSabrina Dubroca nla_put_failure:
23431ec010e7SSabrina Dubroca 	return -EMSGSIZE;
23441ec010e7SSabrina Dubroca }
23451ec010e7SSabrina Dubroca 
2346f019a7a5SEric W. Biederman static struct rtnl_link_ops tun_link_ops __read_mostly = {
2347f019a7a5SEric W. Biederman 	.kind		= DRV_NAME,
2348f019a7a5SEric W. Biederman 	.priv_size	= sizeof(struct tun_struct),
2349f019a7a5SEric W. Biederman 	.setup		= tun_setup,
2350f019a7a5SEric W. Biederman 	.validate	= tun_validate,
23511ec010e7SSabrina Dubroca 	.get_size       = tun_get_size,
23521ec010e7SSabrina Dubroca 	.fill_info      = tun_fill_info,
2353f019a7a5SEric W. Biederman };
2354f019a7a5SEric W. Biederman 
235533dccbb0SHerbert Xu static void tun_sock_write_space(struct sock *sk)
235633dccbb0SHerbert Xu {
235754f968d6SJason Wang 	struct tun_file *tfile;
235843815482SEric Dumazet 	wait_queue_head_t *wqueue;
235933dccbb0SHerbert Xu 
236033dccbb0SHerbert Xu 	if (!sock_writeable(sk))
236133dccbb0SHerbert Xu 		return;
236233dccbb0SHerbert Xu 
23639cd3e072SEric Dumazet 	if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
236433dccbb0SHerbert Xu 		return;
236533dccbb0SHerbert Xu 
236643815482SEric Dumazet 	wqueue = sk_sleep(sk);
236743815482SEric Dumazet 	if (wqueue && waitqueue_active(wqueue))
2368a9a08845SLinus Torvalds 		wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
2369a9a08845SLinus Torvalds 						EPOLLWRNORM | EPOLLWRBAND);
2370c722c625SHerbert Xu 
237154f968d6SJason Wang 	tfile = container_of(sk, struct tun_file, sk);
237254f968d6SJason Wang 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
237333dccbb0SHerbert Xu }
237433dccbb0SHerbert Xu 
23751b784140SYing Xue static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
237605c2828cSMichael S. Tsirkin {
237754f968d6SJason Wang 	int ret;
237854f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
23799484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
238054f968d6SJason Wang 
238154f968d6SJason Wang 	if (!tun)
238254f968d6SJason Wang 		return -EBADFD;
2383f5ff53b4SAl Viro 
2384c0371da6SAl Viro 	ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
23855503fcecSJason Wang 			   m->msg_flags & MSG_DONTWAIT,
23865503fcecSJason Wang 			   m->msg_flags & MSG_MORE);
238754f968d6SJason Wang 	tun_put(tun);
238854f968d6SJason Wang 	return ret;
238905c2828cSMichael S. Tsirkin }
239005c2828cSMichael S. Tsirkin 
23911b784140SYing Xue static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
239205c2828cSMichael S. Tsirkin 		       int flags)
239305c2828cSMichael S. Tsirkin {
239454f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
23959484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2396fc72d1d5SJason Wang 	void *ptr = m->msg_control;
239705c2828cSMichael S. Tsirkin 	int ret;
239854f968d6SJason Wang 
2399c33ee15bSWei Xu 	if (!tun) {
2400c33ee15bSWei Xu 		ret = -EBADFD;
2401fc72d1d5SJason Wang 		goto out_free;
2402c33ee15bSWei Xu 	}
240354f968d6SJason Wang 
2404eda29772SRichard Cochran 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
24053811ae76SGao feng 		ret = -EINVAL;
2406c33ee15bSWei Xu 		goto out_put_tun;
24073811ae76SGao feng 	}
2408eda29772SRichard Cochran 	if (flags & MSG_ERRQUEUE) {
2409eda29772SRichard Cochran 		ret = sock_recv_errqueue(sock->sk, m, total_len,
2410eda29772SRichard Cochran 					 SOL_PACKET, TUN_TX_TIMESTAMP);
2411eda29772SRichard Cochran 		goto out;
2412eda29772SRichard Cochran 	}
2413fc72d1d5SJason Wang 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
241487897931SAlex Gartrell 	if (ret > (ssize_t)total_len) {
241542404c09SDavid S. Miller 		m->msg_flags |= MSG_TRUNC;
241642404c09SDavid S. Miller 		ret = flags & MSG_TRUNC ? ret : total_len;
241742404c09SDavid S. Miller 	}
24183811ae76SGao feng out:
241954f968d6SJason Wang 	tun_put(tun);
242005c2828cSMichael S. Tsirkin 	return ret;
2421c33ee15bSWei Xu 
2422c33ee15bSWei Xu out_put_tun:
2423c33ee15bSWei Xu 	tun_put(tun);
2424fc72d1d5SJason Wang out_free:
2425fc72d1d5SJason Wang 	tun_ptr_free(ptr);
2426c33ee15bSWei Xu 	return ret;
242705c2828cSMichael S. Tsirkin }
242805c2828cSMichael S. Tsirkin 
2429fc72d1d5SJason Wang static int tun_ptr_peek_len(void *ptr)
2430fc72d1d5SJason Wang {
2431fc72d1d5SJason Wang 	if (likely(ptr)) {
2432*1ffcbc85SJesper Dangaard Brouer 		if (tun_is_xdp_frame(ptr)) {
2433*1ffcbc85SJesper Dangaard Brouer 			struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2434fc72d1d5SJason Wang 
2435*1ffcbc85SJesper Dangaard Brouer 			return xdpf->len;
2436fc72d1d5SJason Wang 		}
2437fc72d1d5SJason Wang 		return __skb_array_len_with_tag(ptr);
2438fc72d1d5SJason Wang 	} else {
2439fc72d1d5SJason Wang 		return 0;
2440fc72d1d5SJason Wang 	}
2441fc72d1d5SJason Wang }
2442fc72d1d5SJason Wang 
24431576d986SJason Wang static int tun_peek_len(struct socket *sock)
24441576d986SJason Wang {
24451576d986SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
24461576d986SJason Wang 	struct tun_struct *tun;
24471576d986SJason Wang 	int ret = 0;
24481576d986SJason Wang 
24499484dc74Syuan linyu 	tun = tun_get(tfile);
24501576d986SJason Wang 	if (!tun)
24511576d986SJason Wang 		return 0;
24521576d986SJason Wang 
2453fc72d1d5SJason Wang 	ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
24541576d986SJason Wang 	tun_put(tun);
24551576d986SJason Wang 
24561576d986SJason Wang 	return ret;
24571576d986SJason Wang }
24581576d986SJason Wang 
245905c2828cSMichael S. Tsirkin /* Ops structure to mimic raw sockets with tun */
246005c2828cSMichael S. Tsirkin static const struct proto_ops tun_socket_ops = {
24611576d986SJason Wang 	.peek_len = tun_peek_len,
246205c2828cSMichael S. Tsirkin 	.sendmsg = tun_sendmsg,
246305c2828cSMichael S. Tsirkin 	.recvmsg = tun_recvmsg,
246405c2828cSMichael S. Tsirkin };
246505c2828cSMichael S. Tsirkin 
246633dccbb0SHerbert Xu static struct proto tun_proto = {
246733dccbb0SHerbert Xu 	.name		= "tun",
246833dccbb0SHerbert Xu 	.owner		= THIS_MODULE,
246954f968d6SJason Wang 	.obj_size	= sizeof(struct tun_file),
247033dccbb0SHerbert Xu };
2471f019a7a5SEric W. Biederman 
2472980c9e8cSDavid Woodhouse static int tun_flags(struct tun_struct *tun)
2473980c9e8cSDavid Woodhouse {
2474031f5e03SMichael S. Tsirkin 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2475980c9e8cSDavid Woodhouse }
2476980c9e8cSDavid Woodhouse 
2477980c9e8cSDavid Woodhouse static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2478980c9e8cSDavid Woodhouse 			      char *buf)
2479980c9e8cSDavid Woodhouse {
2480980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2481980c9e8cSDavid Woodhouse 	return sprintf(buf, "0x%x\n", tun_flags(tun));
2482980c9e8cSDavid Woodhouse }
2483980c9e8cSDavid Woodhouse 
2484980c9e8cSDavid Woodhouse static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2485980c9e8cSDavid Woodhouse 			      char *buf)
2486980c9e8cSDavid Woodhouse {
2487980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
24880625c883SEric W. Biederman 	return uid_valid(tun->owner)?
24890625c883SEric W. Biederman 		sprintf(buf, "%u\n",
24900625c883SEric W. Biederman 			from_kuid_munged(current_user_ns(), tun->owner)):
24910625c883SEric W. Biederman 		sprintf(buf, "-1\n");
2492980c9e8cSDavid Woodhouse }
2493980c9e8cSDavid Woodhouse 
2494980c9e8cSDavid Woodhouse static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2495980c9e8cSDavid Woodhouse 			      char *buf)
2496980c9e8cSDavid Woodhouse {
2497980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
24980625c883SEric W. Biederman 	return gid_valid(tun->group) ?
24990625c883SEric W. Biederman 		sprintf(buf, "%u\n",
25000625c883SEric W. Biederman 			from_kgid_munged(current_user_ns(), tun->group)):
25010625c883SEric W. Biederman 		sprintf(buf, "-1\n");
2502980c9e8cSDavid Woodhouse }
2503980c9e8cSDavid Woodhouse 
2504980c9e8cSDavid Woodhouse static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2505980c9e8cSDavid Woodhouse static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2506980c9e8cSDavid Woodhouse static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2507980c9e8cSDavid Woodhouse 
2508c4d33e24STakashi Iwai static struct attribute *tun_dev_attrs[] = {
2509c4d33e24STakashi Iwai 	&dev_attr_tun_flags.attr,
2510c4d33e24STakashi Iwai 	&dev_attr_owner.attr,
2511c4d33e24STakashi Iwai 	&dev_attr_group.attr,
2512c4d33e24STakashi Iwai 	NULL
2513c4d33e24STakashi Iwai };
2514c4d33e24STakashi Iwai 
2515c4d33e24STakashi Iwai static const struct attribute_group tun_attr_group = {
2516c4d33e24STakashi Iwai 	.attrs = tun_dev_attrs
2517c4d33e24STakashi Iwai };
2518c4d33e24STakashi Iwai 
2519d647a591SPavel Emelyanov static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
25201da177e4SLinus Torvalds {
25211da177e4SLinus Torvalds 	struct tun_struct *tun;
252254f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
25231da177e4SLinus Torvalds 	struct net_device *dev;
25241da177e4SLinus Torvalds 	int err;
25251da177e4SLinus Torvalds 
25267c0c3b1aSJason Wang 	if (tfile->detached)
25277c0c3b1aSJason Wang 		return -EINVAL;
25287c0c3b1aSJason Wang 
252990e33d45SPetar Penkov 	if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
253090e33d45SPetar Penkov 		if (!capable(CAP_NET_ADMIN))
253190e33d45SPetar Penkov 			return -EPERM;
253290e33d45SPetar Penkov 
253390e33d45SPetar Penkov 		if (!(ifr->ifr_flags & IFF_NAPI) ||
253490e33d45SPetar Penkov 		    (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
253590e33d45SPetar Penkov 			return -EINVAL;
253690e33d45SPetar Penkov 	}
253790e33d45SPetar Penkov 
253874a3e5a7SEric W. Biederman 	dev = __dev_get_by_name(net, ifr->ifr_name);
253974a3e5a7SEric W. Biederman 	if (dev) {
2540f85ba780SDavid Woodhouse 		if (ifr->ifr_flags & IFF_TUN_EXCL)
2541f85ba780SDavid Woodhouse 			return -EBUSY;
254274a3e5a7SEric W. Biederman 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
254374a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
254474a3e5a7SEric W. Biederman 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
254574a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
254674a3e5a7SEric W. Biederman 		else
254774a3e5a7SEric W. Biederman 			return -EINVAL;
254874a3e5a7SEric W. Biederman 
25498e6d91aeSJason Wang 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
255040630b82SMichael S. Tsirkin 		    !!(tun->flags & IFF_MULTI_QUEUE))
25518e6d91aeSJason Wang 			return -EINVAL;
25528e6d91aeSJason Wang 
2553cde8b15fSJason Wang 		if (tun_not_capable(tun))
25542b980dbdSPaul Moore 			return -EPERM;
25555dbbaf2dSPaul Moore 		err = security_tun_dev_open(tun->security);
25562b980dbdSPaul Moore 		if (err < 0)
25572b980dbdSPaul Moore 			return err;
25582b980dbdSPaul Moore 
255994317099SPetar Penkov 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
256094317099SPetar Penkov 				 ifr->ifr_flags & IFF_NAPI);
2561a7385ba2SEric W. Biederman 		if (err < 0)
2562a7385ba2SEric W. Biederman 			return err;
25634008e97fSJason Wang 
256440630b82SMichael S. Tsirkin 		if (tun->flags & IFF_MULTI_QUEUE &&
2565e8dbad66SJason Wang 		    (tun->numqueues + tun->numdisabled > 1)) {
2566e8dbad66SJason Wang 			/* One or more queue has already been attached, no need
2567e8dbad66SJason Wang 			 * to initialize the device again.
2568e8dbad66SJason Wang 			 */
256983c1f36fSSabrina Dubroca 			netdev_state_change(dev);
2570e8dbad66SJason Wang 			return 0;
2571e8dbad66SJason Wang 		}
25729fffc5c6SSabrina Dubroca 
25739fffc5c6SSabrina Dubroca 		tun->flags = (tun->flags & ~TUN_FEATURES) |
25749fffc5c6SSabrina Dubroca 			      (ifr->ifr_flags & TUN_FEATURES);
257583c1f36fSSabrina Dubroca 
257683c1f36fSSabrina Dubroca 		netdev_state_change(dev);
257783c1f36fSSabrina Dubroca 	} else {
25781da177e4SLinus Torvalds 		char *name;
25791da177e4SLinus Torvalds 		unsigned long flags = 0;
2580edfb6a14SJason Wang 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2581edfb6a14SJason Wang 			     MAX_TAP_QUEUES : 1;
25821da177e4SLinus Torvalds 
2583c260b772SEric W. Biederman 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2584ca6bb5d7SDavid Woodhouse 			return -EPERM;
25852b980dbdSPaul Moore 		err = security_tun_dev_create();
25862b980dbdSPaul Moore 		if (err < 0)
25872b980dbdSPaul Moore 			return err;
2588ca6bb5d7SDavid Woodhouse 
25891da177e4SLinus Torvalds 		/* Set dev type */
25901da177e4SLinus Torvalds 		if (ifr->ifr_flags & IFF_TUN) {
25911da177e4SLinus Torvalds 			/* TUN device */
259240630b82SMichael S. Tsirkin 			flags |= IFF_TUN;
25931da177e4SLinus Torvalds 			name = "tun%d";
25941da177e4SLinus Torvalds 		} else if (ifr->ifr_flags & IFF_TAP) {
25951da177e4SLinus Torvalds 			/* TAP device */
259640630b82SMichael S. Tsirkin 			flags |= IFF_TAP;
25971da177e4SLinus Torvalds 			name = "tap%d";
25981da177e4SLinus Torvalds 		} else
259936989b90SKusanagi Kouichi 			return -EINVAL;
26001da177e4SLinus Torvalds 
26011da177e4SLinus Torvalds 		if (*ifr->ifr_name)
26021da177e4SLinus Torvalds 			name = ifr->ifr_name;
26031da177e4SLinus Torvalds 
2604c8d68e6bSJason Wang 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2605c835a677STom Gundersen 				       NET_NAME_UNKNOWN, tun_setup, queues,
2606c835a677STom Gundersen 				       queues);
2607edfb6a14SJason Wang 
26081da177e4SLinus Torvalds 		if (!dev)
26091da177e4SLinus Torvalds 			return -ENOMEM;
26100ad646c8SCong Wang 		err = dev_get_valid_name(net, dev, name);
26115c25f65fSJulien Gomes 		if (err < 0)
26120ad646c8SCong Wang 			goto err_free_dev;
26131da177e4SLinus Torvalds 
2614fc54c658SPavel Emelyanov 		dev_net_set(dev, net);
2615f019a7a5SEric W. Biederman 		dev->rtnl_link_ops = &tun_link_ops;
2616fb7589a1SPavel Emelyanov 		dev->ifindex = tfile->ifindex;
2617c4d33e24STakashi Iwai 		dev->sysfs_groups[0] = &tun_attr_group;
2618758e43b7SStephen Hemminger 
26191da177e4SLinus Torvalds 		tun = netdev_priv(dev);
26201da177e4SLinus Torvalds 		tun->dev = dev;
26211da177e4SLinus Torvalds 		tun->flags = flags;
2622f271b2ccSMax Krasnyansky 		tun->txflt.count = 0;
2623d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
26241da177e4SLinus Torvalds 
2625eaea34b2SPaolo Abeni 		tun->align = NET_SKB_PAD;
262654f968d6SJason Wang 		tun->filter_attached = false;
262754f968d6SJason Wang 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
26285503fcecSJason Wang 		tun->rx_batched = 0;
262996f84061SJason Wang 		RCU_INIT_POINTER(tun->steering_prog, NULL);
263033dccbb0SHerbert Xu 
2631608b9977SPaolo Abeni 		tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2632608b9977SPaolo Abeni 		if (!tun->pcpu_stats) {
2633608b9977SPaolo Abeni 			err = -ENOMEM;
2634608b9977SPaolo Abeni 			goto err_free_dev;
2635608b9977SPaolo Abeni 		}
2636608b9977SPaolo Abeni 
263796442e42SJason Wang 		spin_lock_init(&tun->lock);
263896442e42SJason Wang 
26395dbbaf2dSPaul Moore 		err = security_tun_dev_alloc_security(&tun->security);
26405dbbaf2dSPaul Moore 		if (err < 0)
2641608b9977SPaolo Abeni 			goto err_free_stat;
26422b980dbdSPaul Moore 
26431da177e4SLinus Torvalds 		tun_net_init(dev);
2644944a1376SPavel Emelyanov 		tun_flow_init(tun);
264596442e42SJason Wang 
264688255375SMichał Mirosław 		dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
26476680ec68SJason Wang 				   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
26486680ec68SJason Wang 				   NETIF_F_HW_VLAN_STAG_TX;
26492a2bbf17SPaolo Abeni 		dev->features = dev->hw_features | NETIF_F_LLTX;
26506671b224SFernando Luis Vazquez Cao 		dev->vlan_features = dev->features &
26516671b224SFernando Luis Vazquez Cao 				     ~(NETIF_F_HW_VLAN_CTAG_TX |
26526671b224SFernando Luis Vazquez Cao 				       NETIF_F_HW_VLAN_STAG_TX);
265388255375SMichał Mirosław 
26549fffc5c6SSabrina Dubroca 		tun->flags = (tun->flags & ~TUN_FEATURES) |
26559fffc5c6SSabrina Dubroca 			      (ifr->ifr_flags & TUN_FEATURES);
26569fffc5c6SSabrina Dubroca 
26574008e97fSJason Wang 		INIT_LIST_HEAD(&tun->disabled);
265894317099SPetar Penkov 		err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI);
2659eb0fb363SJason Wang 		if (err < 0)
2660662ca437SJason Wang 			goto err_free_flow;
2661eb0fb363SJason Wang 
26621da177e4SLinus Torvalds 		err = register_netdevice(tun->dev);
26631da177e4SLinus Torvalds 		if (err < 0)
2664662ca437SJason Wang 			goto err_detach;
2665af668b3cSMichael S. Tsirkin 	}
2666980c9e8cSDavid Woodhouse 
2667eb0fb363SJason Wang 	netif_carrier_on(tun->dev);
26681da177e4SLinus Torvalds 
26696b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_set_iff\n");
26701da177e4SLinus Torvalds 
2671e35259a9SMax Krasnyansky 	/* Make sure persistent devices do not get stuck in
2672e35259a9SMax Krasnyansky 	 * xoff state.
2673e35259a9SMax Krasnyansky 	 */
2674e35259a9SMax Krasnyansky 	if (netif_running(tun->dev))
2675c8d68e6bSJason Wang 		netif_tx_wake_all_queues(tun->dev);
2676e35259a9SMax Krasnyansky 
26771da177e4SLinus Torvalds 	strcpy(ifr->ifr_name, tun->dev->name);
26781da177e4SLinus Torvalds 	return 0;
26791da177e4SLinus Torvalds 
2680662ca437SJason Wang err_detach:
2681662ca437SJason Wang 	tun_detach_all(dev);
2682ff244c6bSEric Dumazet 	/* register_netdevice() already called tun_free_netdev() */
2683ff244c6bSEric Dumazet 	goto err_free_dev;
2684ff244c6bSEric Dumazet 
2685662ca437SJason Wang err_free_flow:
2686662ca437SJason Wang 	tun_flow_uninit(tun);
2687662ca437SJason Wang 	security_tun_dev_free_security(tun->security);
2688608b9977SPaolo Abeni err_free_stat:
2689608b9977SPaolo Abeni 	free_percpu(tun->pcpu_stats);
26901da177e4SLinus Torvalds err_free_dev:
26911da177e4SLinus Torvalds 	free_netdev(dev);
26921da177e4SLinus Torvalds 	return err;
26931da177e4SLinus Torvalds }
26941da177e4SLinus Torvalds 
26959ce99cf6SRami Rosen static void tun_get_iff(struct net *net, struct tun_struct *tun,
2696876bfd4dSHerbert Xu 		       struct ifreq *ifr)
2697e3b99556SMark McLoughlin {
26986b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2699e3b99556SMark McLoughlin 
2700e3b99556SMark McLoughlin 	strcpy(ifr->ifr_name, tun->dev->name);
2701e3b99556SMark McLoughlin 
2702980c9e8cSDavid Woodhouse 	ifr->ifr_flags = tun_flags(tun);
2703e3b99556SMark McLoughlin 
2704e3b99556SMark McLoughlin }
2705e3b99556SMark McLoughlin 
27065228ddc9SRusty Russell /* This is like a cut-down ethtool ops, except done via tun fd so no
27075228ddc9SRusty Russell  * privs required. */
270888255375SMichał Mirosław static int set_offload(struct tun_struct *tun, unsigned long arg)
27095228ddc9SRusty Russell {
2710c8f44affSMichał Mirosław 	netdev_features_t features = 0;
27115228ddc9SRusty Russell 
27125228ddc9SRusty Russell 	if (arg & TUN_F_CSUM) {
271388255375SMichał Mirosław 		features |= NETIF_F_HW_CSUM;
27145228ddc9SRusty Russell 		arg &= ~TUN_F_CSUM;
27155228ddc9SRusty Russell 
27165228ddc9SRusty Russell 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
27175228ddc9SRusty Russell 			if (arg & TUN_F_TSO_ECN) {
27185228ddc9SRusty Russell 				features |= NETIF_F_TSO_ECN;
27195228ddc9SRusty Russell 				arg &= ~TUN_F_TSO_ECN;
27205228ddc9SRusty Russell 			}
27215228ddc9SRusty Russell 			if (arg & TUN_F_TSO4)
27225228ddc9SRusty Russell 				features |= NETIF_F_TSO;
27235228ddc9SRusty Russell 			if (arg & TUN_F_TSO6)
27245228ddc9SRusty Russell 				features |= NETIF_F_TSO6;
27255228ddc9SRusty Russell 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
27265228ddc9SRusty Russell 		}
27270c19f846SWillem de Bruijn 
27280c19f846SWillem de Bruijn 		arg &= ~TUN_F_UFO;
27295228ddc9SRusty Russell 	}
27305228ddc9SRusty Russell 
27315228ddc9SRusty Russell 	/* This gives the user a way to test for new features in future by
27325228ddc9SRusty Russell 	 * trying to set them. */
27335228ddc9SRusty Russell 	if (arg)
27345228ddc9SRusty Russell 		return -EINVAL;
27355228ddc9SRusty Russell 
273688255375SMichał Mirosław 	tun->set_features = features;
273709050957SYaroslav Isakov 	tun->dev->wanted_features &= ~TUN_USER_FEATURES;
273809050957SYaroslav Isakov 	tun->dev->wanted_features |= features;
273988255375SMichał Mirosław 	netdev_update_features(tun->dev);
27405228ddc9SRusty Russell 
27415228ddc9SRusty Russell 	return 0;
27425228ddc9SRusty Russell }
27435228ddc9SRusty Russell 
2744c8d68e6bSJason Wang static void tun_detach_filter(struct tun_struct *tun, int n)
2745c8d68e6bSJason Wang {
2746c8d68e6bSJason Wang 	int i;
2747c8d68e6bSJason Wang 	struct tun_file *tfile;
2748c8d68e6bSJason Wang 
2749c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
2750b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
27518ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
27528ced425eSHannes Frederic Sowa 		sk_detach_filter(tfile->socket.sk);
27538ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2754c8d68e6bSJason Wang 	}
2755c8d68e6bSJason Wang 
2756c8d68e6bSJason Wang 	tun->filter_attached = false;
2757c8d68e6bSJason Wang }
2758c8d68e6bSJason Wang 
2759c8d68e6bSJason Wang static int tun_attach_filter(struct tun_struct *tun)
2760c8d68e6bSJason Wang {
2761c8d68e6bSJason Wang 	int i, ret = 0;
2762c8d68e6bSJason Wang 	struct tun_file *tfile;
2763c8d68e6bSJason Wang 
2764c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2765b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
27668ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
27678ced425eSHannes Frederic Sowa 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
27688ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2769c8d68e6bSJason Wang 		if (ret) {
2770c8d68e6bSJason Wang 			tun_detach_filter(tun, i);
2771c8d68e6bSJason Wang 			return ret;
2772c8d68e6bSJason Wang 		}
2773c8d68e6bSJason Wang 	}
2774c8d68e6bSJason Wang 
2775c8d68e6bSJason Wang 	tun->filter_attached = true;
2776c8d68e6bSJason Wang 	return ret;
2777c8d68e6bSJason Wang }
2778c8d68e6bSJason Wang 
2779c8d68e6bSJason Wang static void tun_set_sndbuf(struct tun_struct *tun)
2780c8d68e6bSJason Wang {
2781c8d68e6bSJason Wang 	struct tun_file *tfile;
2782c8d68e6bSJason Wang 	int i;
2783c8d68e6bSJason Wang 
2784c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2785b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
2786c8d68e6bSJason Wang 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2787c8d68e6bSJason Wang 	}
2788c8d68e6bSJason Wang }
2789c8d68e6bSJason Wang 
2790cde8b15fSJason Wang static int tun_set_queue(struct file *file, struct ifreq *ifr)
2791cde8b15fSJason Wang {
2792cde8b15fSJason Wang 	struct tun_file *tfile = file->private_data;
2793cde8b15fSJason Wang 	struct tun_struct *tun;
2794cde8b15fSJason Wang 	int ret = 0;
2795cde8b15fSJason Wang 
2796cde8b15fSJason Wang 	rtnl_lock();
2797cde8b15fSJason Wang 
2798cde8b15fSJason Wang 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
27994008e97fSJason Wang 		tun = tfile->detached;
28005dbbaf2dSPaul Moore 		if (!tun) {
2801cde8b15fSJason Wang 			ret = -EINVAL;
28025dbbaf2dSPaul Moore 			goto unlock;
28035dbbaf2dSPaul Moore 		}
28045dbbaf2dSPaul Moore 		ret = security_tun_dev_attach_queue(tun->security);
28055dbbaf2dSPaul Moore 		if (ret < 0)
28065dbbaf2dSPaul Moore 			goto unlock;
280794317099SPetar Penkov 		ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI);
28084008e97fSJason Wang 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2809b8deabd3SJason Wang 		tun = rtnl_dereference(tfile->tun);
281040630b82SMichael S. Tsirkin 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
28114008e97fSJason Wang 			ret = -EINVAL;
2812cde8b15fSJason Wang 		else
28134008e97fSJason Wang 			__tun_detach(tfile, false);
28144008e97fSJason Wang 	} else
2815cde8b15fSJason Wang 		ret = -EINVAL;
2816cde8b15fSJason Wang 
281783c1f36fSSabrina Dubroca 	if (ret >= 0)
281883c1f36fSSabrina Dubroca 		netdev_state_change(tun->dev);
281983c1f36fSSabrina Dubroca 
28205dbbaf2dSPaul Moore unlock:
2821cde8b15fSJason Wang 	rtnl_unlock();
2822cde8b15fSJason Wang 	return ret;
2823cde8b15fSJason Wang }
2824cde8b15fSJason Wang 
2825cd5681d7SJason Wang static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog **prog_p,
2826cd5681d7SJason Wang 			void __user *data)
282796f84061SJason Wang {
282896f84061SJason Wang 	struct bpf_prog *prog;
282996f84061SJason Wang 	int fd;
283096f84061SJason Wang 
283196f84061SJason Wang 	if (copy_from_user(&fd, data, sizeof(fd)))
283296f84061SJason Wang 		return -EFAULT;
283396f84061SJason Wang 
283496f84061SJason Wang 	if (fd == -1) {
283596f84061SJason Wang 		prog = NULL;
283696f84061SJason Wang 	} else {
283796f84061SJason Wang 		prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
283896f84061SJason Wang 		if (IS_ERR(prog))
283996f84061SJason Wang 			return PTR_ERR(prog);
284096f84061SJason Wang 	}
284196f84061SJason Wang 
2842cd5681d7SJason Wang 	return __tun_set_ebpf(tun, prog_p, prog);
284396f84061SJason Wang }
284496f84061SJason Wang 
284550857e2aSArnd Bergmann static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
284650857e2aSArnd Bergmann 			    unsigned long arg, int ifreq_len)
28471da177e4SLinus Torvalds {
284836b50babSEric W. Biederman 	struct tun_file *tfile = file->private_data;
2849631ab46bSEric W. Biederman 	struct tun_struct *tun;
28501da177e4SLinus Torvalds 	void __user* argp = (void __user*)arg;
28511da177e4SLinus Torvalds 	struct ifreq ifr;
2852f2780d6dSKirill Tkhai 	struct net *net;
28530625c883SEric W. Biederman 	kuid_t owner;
28540625c883SEric W. Biederman 	kgid_t group;
285533dccbb0SHerbert Xu 	int sndbuf;
2856d9d52b51SMichael S. Tsirkin 	int vnet_hdr_sz;
2857fb7589a1SPavel Emelyanov 	unsigned int ifindex;
28581cf8e410SMichael S. Tsirkin 	int le;
2859f271b2ccSMax Krasnyansky 	int ret;
286083c1f36fSSabrina Dubroca 	bool do_notify = false;
28611da177e4SLinus Torvalds 
2862f2780d6dSKirill Tkhai 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
2863f2780d6dSKirill Tkhai 	    (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
286450857e2aSArnd Bergmann 		if (copy_from_user(&ifr, argp, ifreq_len))
28651da177e4SLinus Torvalds 			return -EFAULT;
28668bbb1813SDavid S. Miller 	} else {
2867a117dacdSMathias Krause 		memset(&ifr, 0, sizeof(ifr));
28688bbb1813SDavid S. Miller 	}
2869631ab46bSEric W. Biederman 	if (cmd == TUNGETFEATURES) {
2870631ab46bSEric W. Biederman 		/* Currently this just means: "what IFF flags are valid?".
2871631ab46bSEric W. Biederman 		 * This is needed because we never checked for invalid flags on
2872031f5e03SMichael S. Tsirkin 		 * TUNSETIFF.
2873031f5e03SMichael S. Tsirkin 		 */
2874031f5e03SMichael S. Tsirkin 		return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
2875631ab46bSEric W. Biederman 				(unsigned int __user*)argp);
2876cde8b15fSJason Wang 	} else if (cmd == TUNSETQUEUE)
2877cde8b15fSJason Wang 		return tun_set_queue(file, &ifr);
2878631ab46bSEric W. Biederman 
2879c8d68e6bSJason Wang 	ret = 0;
2880876bfd4dSHerbert Xu 	rtnl_lock();
2881876bfd4dSHerbert Xu 
28829484dc74Syuan linyu 	tun = tun_get(tfile);
2883f2780d6dSKirill Tkhai 	net = sock_net(&tfile->sk);
28840f16bc13SGao Feng 	if (cmd == TUNSETIFF) {
28850f16bc13SGao Feng 		ret = -EEXIST;
28860f16bc13SGao Feng 		if (tun)
28870f16bc13SGao Feng 			goto unlock;
28880f16bc13SGao Feng 
28891da177e4SLinus Torvalds 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
28901da177e4SLinus Torvalds 
2891f2780d6dSKirill Tkhai 		ret = tun_set_iff(net, file, &ifr);
28921da177e4SLinus Torvalds 
2893876bfd4dSHerbert Xu 		if (ret)
2894876bfd4dSHerbert Xu 			goto unlock;
28951da177e4SLinus Torvalds 
289650857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2897876bfd4dSHerbert Xu 			ret = -EFAULT;
2898876bfd4dSHerbert Xu 		goto unlock;
28991da177e4SLinus Torvalds 	}
2900fb7589a1SPavel Emelyanov 	if (cmd == TUNSETIFINDEX) {
2901fb7589a1SPavel Emelyanov 		ret = -EPERM;
2902fb7589a1SPavel Emelyanov 		if (tun)
2903fb7589a1SPavel Emelyanov 			goto unlock;
2904fb7589a1SPavel Emelyanov 
2905fb7589a1SPavel Emelyanov 		ret = -EFAULT;
2906fb7589a1SPavel Emelyanov 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
2907fb7589a1SPavel Emelyanov 			goto unlock;
2908fb7589a1SPavel Emelyanov 
2909fb7589a1SPavel Emelyanov 		ret = 0;
2910fb7589a1SPavel Emelyanov 		tfile->ifindex = ifindex;
2911fb7589a1SPavel Emelyanov 		goto unlock;
2912fb7589a1SPavel Emelyanov 	}
2913f2780d6dSKirill Tkhai 	if (cmd == SIOCGSKNS) {
2914f2780d6dSKirill Tkhai 		ret = -EPERM;
2915f2780d6dSKirill Tkhai 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2916f2780d6dSKirill Tkhai 			goto unlock;
2917f2780d6dSKirill Tkhai 
2918f2780d6dSKirill Tkhai 		ret = open_related_ns(&net->ns, get_net_ns);
2919f2780d6dSKirill Tkhai 		goto unlock;
2920f2780d6dSKirill Tkhai 	}
29211da177e4SLinus Torvalds 
2922876bfd4dSHerbert Xu 	ret = -EBADFD;
29231da177e4SLinus Torvalds 	if (!tun)
2924876bfd4dSHerbert Xu 		goto unlock;
29251da177e4SLinus Torvalds 
29261e588338SJason Wang 	tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
29271da177e4SLinus Torvalds 
2928631ab46bSEric W. Biederman 	ret = 0;
29291da177e4SLinus Torvalds 	switch (cmd) {
2930e3b99556SMark McLoughlin 	case TUNGETIFF:
29319ce99cf6SRami Rosen 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2932e3b99556SMark McLoughlin 
29333d407a80SPavel Emelyanov 		if (tfile->detached)
29343d407a80SPavel Emelyanov 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
2935849c9b6fSPavel Emelyanov 		if (!tfile->socket.sk->sk_filter)
2936849c9b6fSPavel Emelyanov 			ifr.ifr_flags |= IFF_NOFILTER;
29373d407a80SPavel Emelyanov 
293850857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2939631ab46bSEric W. Biederman 			ret = -EFAULT;
2940e3b99556SMark McLoughlin 		break;
2941e3b99556SMark McLoughlin 
29421da177e4SLinus Torvalds 	case TUNSETNOCSUM:
29431da177e4SLinus Torvalds 		/* Disable/Enable checksum */
29441da177e4SLinus Torvalds 
294588255375SMichał Mirosław 		/* [unimplemented] */
294688255375SMichał Mirosław 		tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
29476b8a66eeSJoe Perches 			  arg ? "disabled" : "enabled");
29481da177e4SLinus Torvalds 		break;
29491da177e4SLinus Torvalds 
29501da177e4SLinus Torvalds 	case TUNSETPERSIST:
295154f968d6SJason Wang 		/* Disable/Enable persist mode. Keep an extra reference to the
295254f968d6SJason Wang 		 * module to prevent the module being unprobed.
295354f968d6SJason Wang 		 */
295440630b82SMichael S. Tsirkin 		if (arg && !(tun->flags & IFF_PERSIST)) {
295540630b82SMichael S. Tsirkin 			tun->flags |= IFF_PERSIST;
295654f968d6SJason Wang 			__module_get(THIS_MODULE);
295783c1f36fSSabrina Dubroca 			do_notify = true;
2958dd38bd85SJason Wang 		}
295940630b82SMichael S. Tsirkin 		if (!arg && (tun->flags & IFF_PERSIST)) {
296040630b82SMichael S. Tsirkin 			tun->flags &= ~IFF_PERSIST;
296154f968d6SJason Wang 			module_put(THIS_MODULE);
296283c1f36fSSabrina Dubroca 			do_notify = true;
296354f968d6SJason Wang 		}
29641da177e4SLinus Torvalds 
29656b8a66eeSJoe Perches 		tun_debug(KERN_INFO, tun, "persist %s\n",
29666b8a66eeSJoe Perches 			  arg ? "enabled" : "disabled");
29671da177e4SLinus Torvalds 		break;
29681da177e4SLinus Torvalds 
29691da177e4SLinus Torvalds 	case TUNSETOWNER:
29701da177e4SLinus Torvalds 		/* Set owner of the device */
29710625c883SEric W. Biederman 		owner = make_kuid(current_user_ns(), arg);
29720625c883SEric W. Biederman 		if (!uid_valid(owner)) {
29730625c883SEric W. Biederman 			ret = -EINVAL;
29740625c883SEric W. Biederman 			break;
29750625c883SEric W. Biederman 		}
29760625c883SEric W. Biederman 		tun->owner = owner;
297783c1f36fSSabrina Dubroca 		do_notify = true;
29781e588338SJason Wang 		tun_debug(KERN_INFO, tun, "owner set to %u\n",
29790625c883SEric W. Biederman 			  from_kuid(&init_user_ns, tun->owner));
29801da177e4SLinus Torvalds 		break;
29811da177e4SLinus Torvalds 
29828c644623SGuido Guenther 	case TUNSETGROUP:
29838c644623SGuido Guenther 		/* Set group of the device */
29840625c883SEric W. Biederman 		group = make_kgid(current_user_ns(), arg);
29850625c883SEric W. Biederman 		if (!gid_valid(group)) {
29860625c883SEric W. Biederman 			ret = -EINVAL;
29870625c883SEric W. Biederman 			break;
29880625c883SEric W. Biederman 		}
29890625c883SEric W. Biederman 		tun->group = group;
299083c1f36fSSabrina Dubroca 		do_notify = true;
29911e588338SJason Wang 		tun_debug(KERN_INFO, tun, "group set to %u\n",
29920625c883SEric W. Biederman 			  from_kgid(&init_user_ns, tun->group));
29938c644623SGuido Guenther 		break;
29948c644623SGuido Guenther 
2995ff4cc3acSMike Kershaw 	case TUNSETLINK:
2996ff4cc3acSMike Kershaw 		/* Only allow setting the type when the interface is down */
2997ff4cc3acSMike Kershaw 		if (tun->dev->flags & IFF_UP) {
29986b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun,
29996b8a66eeSJoe Perches 				  "Linktype set failed because interface is up\n");
300048abfe05SDavid S. Miller 			ret = -EBUSY;
3001ff4cc3acSMike Kershaw 		} else {
3002ff4cc3acSMike Kershaw 			tun->dev->type = (int) arg;
30036b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun, "linktype set to %d\n",
30046b8a66eeSJoe Perches 				  tun->dev->type);
300548abfe05SDavid S. Miller 			ret = 0;
3006ff4cc3acSMike Kershaw 		}
3007631ab46bSEric W. Biederman 		break;
3008ff4cc3acSMike Kershaw 
30091da177e4SLinus Torvalds #ifdef TUN_DEBUG
30101da177e4SLinus Torvalds 	case TUNSETDEBUG:
30111da177e4SLinus Torvalds 		tun->debug = arg;
30121da177e4SLinus Torvalds 		break;
30131da177e4SLinus Torvalds #endif
30145228ddc9SRusty Russell 	case TUNSETOFFLOAD:
301588255375SMichał Mirosław 		ret = set_offload(tun, arg);
3016631ab46bSEric W. Biederman 		break;
30175228ddc9SRusty Russell 
3018f271b2ccSMax Krasnyansky 	case TUNSETTXFILTER:
3019f271b2ccSMax Krasnyansky 		/* Can be set only for TAPs */
3020631ab46bSEric W. Biederman 		ret = -EINVAL;
302140630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3022631ab46bSEric W. Biederman 			break;
3023c0e5a8c2SHarvey Harrison 		ret = update_filter(&tun->txflt, (void __user *)arg);
3024631ab46bSEric W. Biederman 		break;
30251da177e4SLinus Torvalds 
30261da177e4SLinus Torvalds 	case SIOCGIFHWADDR:
3027b595076aSUwe Kleine-König 		/* Get hw address */
3028f271b2ccSMax Krasnyansky 		memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
3029f271b2ccSMax Krasnyansky 		ifr.ifr_hwaddr.sa_family = tun->dev->type;
303050857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3031631ab46bSEric W. Biederman 			ret = -EFAULT;
3032631ab46bSEric W. Biederman 		break;
30331da177e4SLinus Torvalds 
30341da177e4SLinus Torvalds 	case SIOCSIFHWADDR:
3035f271b2ccSMax Krasnyansky 		/* Set hw address */
30366b8a66eeSJoe Perches 		tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
30376b8a66eeSJoe Perches 			  ifr.ifr_hwaddr.sa_data);
303840102371SKim B. Heino 
303940102371SKim B. Heino 		ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
3040631ab46bSEric W. Biederman 		break;
304133dccbb0SHerbert Xu 
304233dccbb0SHerbert Xu 	case TUNGETSNDBUF:
304354f968d6SJason Wang 		sndbuf = tfile->socket.sk->sk_sndbuf;
304433dccbb0SHerbert Xu 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
304533dccbb0SHerbert Xu 			ret = -EFAULT;
304633dccbb0SHerbert Xu 		break;
304733dccbb0SHerbert Xu 
304833dccbb0SHerbert Xu 	case TUNSETSNDBUF:
304933dccbb0SHerbert Xu 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
305033dccbb0SHerbert Xu 			ret = -EFAULT;
305133dccbb0SHerbert Xu 			break;
305233dccbb0SHerbert Xu 		}
305393161922SCraig Gallek 		if (sndbuf <= 0) {
305493161922SCraig Gallek 			ret = -EINVAL;
305593161922SCraig Gallek 			break;
305693161922SCraig Gallek 		}
305733dccbb0SHerbert Xu 
3058c8d68e6bSJason Wang 		tun->sndbuf = sndbuf;
3059c8d68e6bSJason Wang 		tun_set_sndbuf(tun);
306033dccbb0SHerbert Xu 		break;
306133dccbb0SHerbert Xu 
3062d9d52b51SMichael S. Tsirkin 	case TUNGETVNETHDRSZ:
3063d9d52b51SMichael S. Tsirkin 		vnet_hdr_sz = tun->vnet_hdr_sz;
3064d9d52b51SMichael S. Tsirkin 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
3065d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
3066d9d52b51SMichael S. Tsirkin 		break;
3067d9d52b51SMichael S. Tsirkin 
3068d9d52b51SMichael S. Tsirkin 	case TUNSETVNETHDRSZ:
3069d9d52b51SMichael S. Tsirkin 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
3070d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
3071d9d52b51SMichael S. Tsirkin 			break;
3072d9d52b51SMichael S. Tsirkin 		}
3073d9d52b51SMichael S. Tsirkin 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
3074d9d52b51SMichael S. Tsirkin 			ret = -EINVAL;
3075d9d52b51SMichael S. Tsirkin 			break;
3076d9d52b51SMichael S. Tsirkin 		}
3077d9d52b51SMichael S. Tsirkin 
3078d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = vnet_hdr_sz;
3079d9d52b51SMichael S. Tsirkin 		break;
3080d9d52b51SMichael S. Tsirkin 
30811cf8e410SMichael S. Tsirkin 	case TUNGETVNETLE:
30821cf8e410SMichael S. Tsirkin 		le = !!(tun->flags & TUN_VNET_LE);
30831cf8e410SMichael S. Tsirkin 		if (put_user(le, (int __user *)argp))
30841cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
30851cf8e410SMichael S. Tsirkin 		break;
30861cf8e410SMichael S. Tsirkin 
30871cf8e410SMichael S. Tsirkin 	case TUNSETVNETLE:
30881cf8e410SMichael S. Tsirkin 		if (get_user(le, (int __user *)argp)) {
30891cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
30901cf8e410SMichael S. Tsirkin 			break;
30911cf8e410SMichael S. Tsirkin 		}
30921cf8e410SMichael S. Tsirkin 		if (le)
30931cf8e410SMichael S. Tsirkin 			tun->flags |= TUN_VNET_LE;
30941cf8e410SMichael S. Tsirkin 		else
30951cf8e410SMichael S. Tsirkin 			tun->flags &= ~TUN_VNET_LE;
30961cf8e410SMichael S. Tsirkin 		break;
30971cf8e410SMichael S. Tsirkin 
30988b8e658bSGreg Kurz 	case TUNGETVNETBE:
30998b8e658bSGreg Kurz 		ret = tun_get_vnet_be(tun, argp);
31008b8e658bSGreg Kurz 		break;
31018b8e658bSGreg Kurz 
31028b8e658bSGreg Kurz 	case TUNSETVNETBE:
31038b8e658bSGreg Kurz 		ret = tun_set_vnet_be(tun, argp);
31048b8e658bSGreg Kurz 		break;
31058b8e658bSGreg Kurz 
310699405162SMichael S. Tsirkin 	case TUNATTACHFILTER:
310799405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
310899405162SMichael S. Tsirkin 		ret = -EINVAL;
310940630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
311099405162SMichael S. Tsirkin 			break;
311199405162SMichael S. Tsirkin 		ret = -EFAULT;
311254f968d6SJason Wang 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
311399405162SMichael S. Tsirkin 			break;
311499405162SMichael S. Tsirkin 
3115c8d68e6bSJason Wang 		ret = tun_attach_filter(tun);
311699405162SMichael S. Tsirkin 		break;
311799405162SMichael S. Tsirkin 
311899405162SMichael S. Tsirkin 	case TUNDETACHFILTER:
311999405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
312099405162SMichael S. Tsirkin 		ret = -EINVAL;
312140630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
312299405162SMichael S. Tsirkin 			break;
3123c8d68e6bSJason Wang 		ret = 0;
3124c8d68e6bSJason Wang 		tun_detach_filter(tun, tun->numqueues);
312599405162SMichael S. Tsirkin 		break;
312699405162SMichael S. Tsirkin 
312776975e9cSPavel Emelyanov 	case TUNGETFILTER:
312876975e9cSPavel Emelyanov 		ret = -EINVAL;
312940630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
313076975e9cSPavel Emelyanov 			break;
313176975e9cSPavel Emelyanov 		ret = -EFAULT;
313276975e9cSPavel Emelyanov 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
313376975e9cSPavel Emelyanov 			break;
313476975e9cSPavel Emelyanov 		ret = 0;
313576975e9cSPavel Emelyanov 		break;
313676975e9cSPavel Emelyanov 
313796f84061SJason Wang 	case TUNSETSTEERINGEBPF:
3138cd5681d7SJason Wang 		ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
313996f84061SJason Wang 		break;
314096f84061SJason Wang 
3141aff3d70aSJason Wang 	case TUNSETFILTEREBPF:
3142aff3d70aSJason Wang 		ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3143aff3d70aSJason Wang 		break;
3144aff3d70aSJason Wang 
31451da177e4SLinus Torvalds 	default:
3146631ab46bSEric W. Biederman 		ret = -EINVAL;
3147631ab46bSEric W. Biederman 		break;
3148ee289b64SJoe Perches 	}
31491da177e4SLinus Torvalds 
315083c1f36fSSabrina Dubroca 	if (do_notify)
315183c1f36fSSabrina Dubroca 		netdev_state_change(tun->dev);
315283c1f36fSSabrina Dubroca 
3153876bfd4dSHerbert Xu unlock:
3154876bfd4dSHerbert Xu 	rtnl_unlock();
3155876bfd4dSHerbert Xu 	if (tun)
3156631ab46bSEric W. Biederman 		tun_put(tun);
3157631ab46bSEric W. Biederman 	return ret;
31581da177e4SLinus Torvalds }
31591da177e4SLinus Torvalds 
316050857e2aSArnd Bergmann static long tun_chr_ioctl(struct file *file,
316150857e2aSArnd Bergmann 			  unsigned int cmd, unsigned long arg)
316250857e2aSArnd Bergmann {
316350857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
316450857e2aSArnd Bergmann }
316550857e2aSArnd Bergmann 
316650857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
316750857e2aSArnd Bergmann static long tun_chr_compat_ioctl(struct file *file,
316850857e2aSArnd Bergmann 			 unsigned int cmd, unsigned long arg)
316950857e2aSArnd Bergmann {
317050857e2aSArnd Bergmann 	switch (cmd) {
317150857e2aSArnd Bergmann 	case TUNSETIFF:
317250857e2aSArnd Bergmann 	case TUNGETIFF:
317350857e2aSArnd Bergmann 	case TUNSETTXFILTER:
317450857e2aSArnd Bergmann 	case TUNGETSNDBUF:
317550857e2aSArnd Bergmann 	case TUNSETSNDBUF:
317650857e2aSArnd Bergmann 	case SIOCGIFHWADDR:
317750857e2aSArnd Bergmann 	case SIOCSIFHWADDR:
317850857e2aSArnd Bergmann 		arg = (unsigned long)compat_ptr(arg);
317950857e2aSArnd Bergmann 		break;
318050857e2aSArnd Bergmann 	default:
318150857e2aSArnd Bergmann 		arg = (compat_ulong_t)arg;
318250857e2aSArnd Bergmann 		break;
318350857e2aSArnd Bergmann 	}
318450857e2aSArnd Bergmann 
318550857e2aSArnd Bergmann 	/*
318650857e2aSArnd Bergmann 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
318750857e2aSArnd Bergmann 	 * the end of that structure. All fields that are used in this
318850857e2aSArnd Bergmann 	 * driver are compatible though, we don't need to convert the
318950857e2aSArnd Bergmann 	 * contents.
319050857e2aSArnd Bergmann 	 */
319150857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
319250857e2aSArnd Bergmann }
319350857e2aSArnd Bergmann #endif /* CONFIG_COMPAT */
319450857e2aSArnd Bergmann 
31951da177e4SLinus Torvalds static int tun_chr_fasync(int fd, struct file *file, int on)
31961da177e4SLinus Torvalds {
319754f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
31981da177e4SLinus Torvalds 	int ret;
31991da177e4SLinus Torvalds 
320054f968d6SJason Wang 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
32019d319522SJonathan Corbet 		goto out;
32021da177e4SLinus Torvalds 
32031da177e4SLinus Torvalds 	if (on) {
3204e0b93eddSJeff Layton 		__f_setown(file, task_pid(current), PIDTYPE_PID, 0);
320554f968d6SJason Wang 		tfile->flags |= TUN_FASYNC;
32061da177e4SLinus Torvalds 	} else
320754f968d6SJason Wang 		tfile->flags &= ~TUN_FASYNC;
32089d319522SJonathan Corbet 	ret = 0;
32099d319522SJonathan Corbet out:
32109d319522SJonathan Corbet 	return ret;
32111da177e4SLinus Torvalds }
32121da177e4SLinus Torvalds 
32131da177e4SLinus Torvalds static int tun_chr_open(struct inode *inode, struct file * file)
32141da177e4SLinus Torvalds {
3215140e807dSEric W. Biederman 	struct net *net = current->nsproxy->net_ns;
3216631ab46bSEric W. Biederman 	struct tun_file *tfile;
3217deed49fbSThomas Gleixner 
32186b8a66eeSJoe Perches 	DBG1(KERN_INFO, "tunX: tun_chr_open\n");
3219631ab46bSEric W. Biederman 
3220140e807dSEric W. Biederman 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
322111aa9c28SEric W. Biederman 					    &tun_proto, 0);
3222631ab46bSEric W. Biederman 	if (!tfile)
3223631ab46bSEric W. Biederman 		return -ENOMEM;
3224c956674bSMonam Agarwal 	RCU_INIT_POINTER(tfile->tun, NULL);
322554f968d6SJason Wang 	tfile->flags = 0;
3226fb7589a1SPavel Emelyanov 	tfile->ifindex = 0;
322754f968d6SJason Wang 
322854f968d6SJason Wang 	init_waitqueue_head(&tfile->wq.wait);
32299e641bdcSXi Wang 	RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
323054f968d6SJason Wang 
323154f968d6SJason Wang 	tfile->socket.file = file;
323254f968d6SJason Wang 	tfile->socket.ops = &tun_socket_ops;
323354f968d6SJason Wang 
323454f968d6SJason Wang 	sock_init_data(&tfile->socket, &tfile->sk);
323554f968d6SJason Wang 
323654f968d6SJason Wang 	tfile->sk.sk_write_space = tun_sock_write_space;
323754f968d6SJason Wang 	tfile->sk.sk_sndbuf = INT_MAX;
323854f968d6SJason Wang 
3239631ab46bSEric W. Biederman 	file->private_data = tfile;
32404008e97fSJason Wang 	INIT_LIST_HEAD(&tfile->next);
324154f968d6SJason Wang 
324219a6afb2SJason Wang 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
324319a6afb2SJason Wang 
32448565d26bSDavid S. Miller 	memset(&tfile->tx_ring, 0, sizeof(tfile->tx_ring));
32454df0bfc7SCong Wang 
32461da177e4SLinus Torvalds 	return 0;
32471da177e4SLinus Torvalds }
32481da177e4SLinus Torvalds 
32491da177e4SLinus Torvalds static int tun_chr_close(struct inode *inode, struct file *file)
32501da177e4SLinus Torvalds {
3251631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
32521da177e4SLinus Torvalds 
3253c8d68e6bSJason Wang 	tun_detach(tfile, true);
32541da177e4SLinus Torvalds 
32551da177e4SLinus Torvalds 	return 0;
32561da177e4SLinus Torvalds }
32571da177e4SLinus Torvalds 
325893e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
32599484dc74Syuan linyu static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
326093e14b6dSMasatake YAMATO {
32619484dc74Syuan linyu 	struct tun_file *tfile = file->private_data;
326293e14b6dSMasatake YAMATO 	struct tun_struct *tun;
326393e14b6dSMasatake YAMATO 	struct ifreq ifr;
326493e14b6dSMasatake YAMATO 
326593e14b6dSMasatake YAMATO 	memset(&ifr, 0, sizeof(ifr));
326693e14b6dSMasatake YAMATO 
326793e14b6dSMasatake YAMATO 	rtnl_lock();
32689484dc74Syuan linyu 	tun = tun_get(tfile);
326993e14b6dSMasatake YAMATO 	if (tun)
327093e14b6dSMasatake YAMATO 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
327193e14b6dSMasatake YAMATO 	rtnl_unlock();
327293e14b6dSMasatake YAMATO 
327393e14b6dSMasatake YAMATO 	if (tun)
327493e14b6dSMasatake YAMATO 		tun_put(tun);
327593e14b6dSMasatake YAMATO 
3276a3816ab0SJoe Perches 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
327793e14b6dSMasatake YAMATO }
327893e14b6dSMasatake YAMATO #endif
327993e14b6dSMasatake YAMATO 
3280d54b1fdbSArjan van de Ven static const struct file_operations tun_fops = {
32811da177e4SLinus Torvalds 	.owner	= THIS_MODULE,
32821da177e4SLinus Torvalds 	.llseek = no_llseek,
32839b067034SAl Viro 	.read_iter  = tun_chr_read_iter,
3284f5ff53b4SAl Viro 	.write_iter = tun_chr_write_iter,
32851da177e4SLinus Torvalds 	.poll	= tun_chr_poll,
3286876bfd4dSHerbert Xu 	.unlocked_ioctl	= tun_chr_ioctl,
328750857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
328850857e2aSArnd Bergmann 	.compat_ioctl = tun_chr_compat_ioctl,
328950857e2aSArnd Bergmann #endif
32901da177e4SLinus Torvalds 	.open	= tun_chr_open,
32911da177e4SLinus Torvalds 	.release = tun_chr_close,
329293e14b6dSMasatake YAMATO 	.fasync = tun_chr_fasync,
329393e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
329493e14b6dSMasatake YAMATO 	.show_fdinfo = tun_chr_show_fdinfo,
329593e14b6dSMasatake YAMATO #endif
32961da177e4SLinus Torvalds };
32971da177e4SLinus Torvalds 
32981da177e4SLinus Torvalds static struct miscdevice tun_miscdev = {
32991da177e4SLinus Torvalds 	.minor = TUN_MINOR,
33001da177e4SLinus Torvalds 	.name = "tun",
3301e454cea2SKay Sievers 	.nodename = "net/tun",
33021da177e4SLinus Torvalds 	.fops = &tun_fops,
33031da177e4SLinus Torvalds };
33041da177e4SLinus Torvalds 
33051da177e4SLinus Torvalds /* ethtool interface */
33061da177e4SLinus Torvalds 
330729ccc49dSPhilippe Reynes static int tun_get_link_ksettings(struct net_device *dev,
330829ccc49dSPhilippe Reynes 				  struct ethtool_link_ksettings *cmd)
33091da177e4SLinus Torvalds {
331029ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
331129ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
331229ccc49dSPhilippe Reynes 	cmd->base.speed		= SPEED_10;
331329ccc49dSPhilippe Reynes 	cmd->base.duplex	= DUPLEX_FULL;
331429ccc49dSPhilippe Reynes 	cmd->base.port		= PORT_TP;
331529ccc49dSPhilippe Reynes 	cmd->base.phy_address	= 0;
331629ccc49dSPhilippe Reynes 	cmd->base.autoneg	= AUTONEG_DISABLE;
33171da177e4SLinus Torvalds 	return 0;
33181da177e4SLinus Torvalds }
33191da177e4SLinus Torvalds 
33201da177e4SLinus Torvalds static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
33211da177e4SLinus Torvalds {
33221da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
33231da177e4SLinus Torvalds 
332433a5ba14SRick Jones 	strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
332533a5ba14SRick Jones 	strlcpy(info->version, DRV_VERSION, sizeof(info->version));
33261da177e4SLinus Torvalds 
33271da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
332840630b82SMichael S. Tsirkin 	case IFF_TUN:
332933a5ba14SRick Jones 		strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
33301da177e4SLinus Torvalds 		break;
333140630b82SMichael S. Tsirkin 	case IFF_TAP:
333233a5ba14SRick Jones 		strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
33331da177e4SLinus Torvalds 		break;
33341da177e4SLinus Torvalds 	}
33351da177e4SLinus Torvalds }
33361da177e4SLinus Torvalds 
33371da177e4SLinus Torvalds static u32 tun_get_msglevel(struct net_device *dev)
33381da177e4SLinus Torvalds {
33391da177e4SLinus Torvalds #ifdef TUN_DEBUG
33401da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
33411da177e4SLinus Torvalds 	return tun->debug;
33421da177e4SLinus Torvalds #else
33431da177e4SLinus Torvalds 	return -EOPNOTSUPP;
33441da177e4SLinus Torvalds #endif
33451da177e4SLinus Torvalds }
33461da177e4SLinus Torvalds 
33471da177e4SLinus Torvalds static void tun_set_msglevel(struct net_device *dev, u32 value)
33481da177e4SLinus Torvalds {
33491da177e4SLinus Torvalds #ifdef TUN_DEBUG
33501da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
33511da177e4SLinus Torvalds 	tun->debug = value;
33521da177e4SLinus Torvalds #endif
33531da177e4SLinus Torvalds }
33541da177e4SLinus Torvalds 
33555503fcecSJason Wang static int tun_get_coalesce(struct net_device *dev,
33565503fcecSJason Wang 			    struct ethtool_coalesce *ec)
33575503fcecSJason Wang {
33585503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
33595503fcecSJason Wang 
33605503fcecSJason Wang 	ec->rx_max_coalesced_frames = tun->rx_batched;
33615503fcecSJason Wang 
33625503fcecSJason Wang 	return 0;
33635503fcecSJason Wang }
33645503fcecSJason Wang 
33655503fcecSJason Wang static int tun_set_coalesce(struct net_device *dev,
33665503fcecSJason Wang 			    struct ethtool_coalesce *ec)
33675503fcecSJason Wang {
33685503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
33695503fcecSJason Wang 
33705503fcecSJason Wang 	if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
33715503fcecSJason Wang 		tun->rx_batched = NAPI_POLL_WEIGHT;
33725503fcecSJason Wang 	else
33735503fcecSJason Wang 		tun->rx_batched = ec->rx_max_coalesced_frames;
33745503fcecSJason Wang 
33755503fcecSJason Wang 	return 0;
33765503fcecSJason Wang }
33775503fcecSJason Wang 
33787282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops = {
33791da177e4SLinus Torvalds 	.get_drvinfo	= tun_get_drvinfo,
33801da177e4SLinus Torvalds 	.get_msglevel	= tun_get_msglevel,
33811da177e4SLinus Torvalds 	.set_msglevel	= tun_set_msglevel,
3382bee31369SNolan Leake 	.get_link	= ethtool_op_get_link,
3383eda29772SRichard Cochran 	.get_ts_info	= ethtool_op_get_ts_info,
33845503fcecSJason Wang 	.get_coalesce   = tun_get_coalesce,
33855503fcecSJason Wang 	.set_coalesce   = tun_set_coalesce,
338629ccc49dSPhilippe Reynes 	.get_link_ksettings = tun_get_link_ksettings,
33871da177e4SLinus Torvalds };
33881da177e4SLinus Torvalds 
33891576d986SJason Wang static int tun_queue_resize(struct tun_struct *tun)
33901576d986SJason Wang {
33911576d986SJason Wang 	struct net_device *dev = tun->dev;
33921576d986SJason Wang 	struct tun_file *tfile;
33935990a305SJason Wang 	struct ptr_ring **rings;
33941576d986SJason Wang 	int n = tun->numqueues + tun->numdisabled;
33951576d986SJason Wang 	int ret, i;
33961576d986SJason Wang 
33975990a305SJason Wang 	rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
33985990a305SJason Wang 	if (!rings)
33991576d986SJason Wang 		return -ENOMEM;
34001576d986SJason Wang 
34011576d986SJason Wang 	for (i = 0; i < tun->numqueues; i++) {
34021576d986SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
34035990a305SJason Wang 		rings[i] = &tfile->tx_ring;
34041576d986SJason Wang 	}
34051576d986SJason Wang 	list_for_each_entry(tfile, &tun->disabled, next)
34065990a305SJason Wang 		rings[i++] = &tfile->tx_ring;
34071576d986SJason Wang 
34085990a305SJason Wang 	ret = ptr_ring_resize_multiple(rings, n,
34095990a305SJason Wang 				       dev->tx_queue_len, GFP_KERNEL,
3410fc72d1d5SJason Wang 				       tun_ptr_free);
34111576d986SJason Wang 
34125990a305SJason Wang 	kfree(rings);
34131576d986SJason Wang 	return ret;
34141576d986SJason Wang }
34151576d986SJason Wang 
34161576d986SJason Wang static int tun_device_event(struct notifier_block *unused,
34171576d986SJason Wang 			    unsigned long event, void *ptr)
34181576d986SJason Wang {
34191576d986SJason Wang 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
34201576d986SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
34211576d986SJason Wang 
342286dfb4acSCraig Gallek 	if (dev->rtnl_link_ops != &tun_link_ops)
342386dfb4acSCraig Gallek 		return NOTIFY_DONE;
342486dfb4acSCraig Gallek 
34251576d986SJason Wang 	switch (event) {
34261576d986SJason Wang 	case NETDEV_CHANGE_TX_QUEUE_LEN:
34271576d986SJason Wang 		if (tun_queue_resize(tun))
34281576d986SJason Wang 			return NOTIFY_BAD;
34291576d986SJason Wang 		break;
34301576d986SJason Wang 	default:
34311576d986SJason Wang 		break;
34321576d986SJason Wang 	}
34331576d986SJason Wang 
34341576d986SJason Wang 	return NOTIFY_DONE;
34351576d986SJason Wang }
34361576d986SJason Wang 
34371576d986SJason Wang static struct notifier_block tun_notifier_block __read_mostly = {
34381576d986SJason Wang 	.notifier_call	= tun_device_event,
34391576d986SJason Wang };
344079d17604SPavel Emelyanov 
34411da177e4SLinus Torvalds static int __init tun_init(void)
34421da177e4SLinus Torvalds {
34431da177e4SLinus Torvalds 	int ret = 0;
34441da177e4SLinus Torvalds 
34456b8a66eeSJoe Perches 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
34461da177e4SLinus Torvalds 
3447f019a7a5SEric W. Biederman 	ret = rtnl_link_register(&tun_link_ops);
344879d17604SPavel Emelyanov 	if (ret) {
34496b8a66eeSJoe Perches 		pr_err("Can't register link_ops\n");
3450f019a7a5SEric W. Biederman 		goto err_linkops;
345179d17604SPavel Emelyanov 	}
345279d17604SPavel Emelyanov 
34531da177e4SLinus Torvalds 	ret = misc_register(&tun_miscdev);
345479d17604SPavel Emelyanov 	if (ret) {
34556b8a66eeSJoe Perches 		pr_err("Can't register misc device %d\n", TUN_MINOR);
345679d17604SPavel Emelyanov 		goto err_misc;
345779d17604SPavel Emelyanov 	}
34581576d986SJason Wang 
34595edfbd3cSTonghao Zhang 	ret = register_netdevice_notifier(&tun_notifier_block);
34605edfbd3cSTonghao Zhang 	if (ret) {
34615edfbd3cSTonghao Zhang 		pr_err("Can't register netdevice notifier\n");
34625edfbd3cSTonghao Zhang 		goto err_notifier;
34635edfbd3cSTonghao Zhang 	}
34645edfbd3cSTonghao Zhang 
346579d17604SPavel Emelyanov 	return  0;
34665edfbd3cSTonghao Zhang 
34675edfbd3cSTonghao Zhang err_notifier:
34685edfbd3cSTonghao Zhang 	misc_deregister(&tun_miscdev);
346979d17604SPavel Emelyanov err_misc:
3470f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
3471f019a7a5SEric W. Biederman err_linkops:
34721da177e4SLinus Torvalds 	return ret;
34731da177e4SLinus Torvalds }
34741da177e4SLinus Torvalds 
34751da177e4SLinus Torvalds static void tun_cleanup(void)
34761da177e4SLinus Torvalds {
34771da177e4SLinus Torvalds 	misc_deregister(&tun_miscdev);
3478f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
34791576d986SJason Wang 	unregister_netdevice_notifier(&tun_notifier_block);
34801da177e4SLinus Torvalds }
34811da177e4SLinus Torvalds 
348205c2828cSMichael S. Tsirkin /* Get an underlying socket object from tun file.  Returns error unless file is
348305c2828cSMichael S. Tsirkin  * attached to a device.  The returned object works like a packet socket, it
348405c2828cSMichael S. Tsirkin  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
348505c2828cSMichael S. Tsirkin  * holding a reference to the file for as long as the socket is in use. */
348605c2828cSMichael S. Tsirkin struct socket *tun_get_socket(struct file *file)
348705c2828cSMichael S. Tsirkin {
34886e914fc7SJason Wang 	struct tun_file *tfile;
348905c2828cSMichael S. Tsirkin 	if (file->f_op != &tun_fops)
349005c2828cSMichael S. Tsirkin 		return ERR_PTR(-EINVAL);
34916e914fc7SJason Wang 	tfile = file->private_data;
34926e914fc7SJason Wang 	if (!tfile)
349305c2828cSMichael S. Tsirkin 		return ERR_PTR(-EBADFD);
349454f968d6SJason Wang 	return &tfile->socket;
349505c2828cSMichael S. Tsirkin }
349605c2828cSMichael S. Tsirkin EXPORT_SYMBOL_GPL(tun_get_socket);
349705c2828cSMichael S. Tsirkin 
34985990a305SJason Wang struct ptr_ring *tun_get_tx_ring(struct file *file)
349983339c6bSJason Wang {
350083339c6bSJason Wang 	struct tun_file *tfile;
350183339c6bSJason Wang 
350283339c6bSJason Wang 	if (file->f_op != &tun_fops)
350383339c6bSJason Wang 		return ERR_PTR(-EINVAL);
350483339c6bSJason Wang 	tfile = file->private_data;
350583339c6bSJason Wang 	if (!tfile)
350683339c6bSJason Wang 		return ERR_PTR(-EBADFD);
35075990a305SJason Wang 	return &tfile->tx_ring;
350883339c6bSJason Wang }
35095990a305SJason Wang EXPORT_SYMBOL_GPL(tun_get_tx_ring);
351083339c6bSJason Wang 
35111da177e4SLinus Torvalds module_init(tun_init);
35121da177e4SLinus Torvalds module_exit(tun_cleanup);
35131da177e4SLinus Torvalds MODULE_DESCRIPTION(DRV_DESCRIPTION);
35141da177e4SLinus Torvalds MODULE_AUTHOR(DRV_COPYRIGHT);
35151da177e4SLinus Torvalds MODULE_LICENSE("GPL");
35161da177e4SLinus Torvalds MODULE_ALIAS_MISCDEV(TUN_MINOR);
3517578454ffSKay Sievers MODULE_ALIAS("devname:net/tun");
3518