xref: /openbmc/linux/drivers/net/tun.c (revision aa6daacaa113cda96760c8d3157bae937908f6e3)
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>
73735fc405SJesper Dangaard Brouer #include <net/xdp.h>
7493e14b6dSMasatake YAMATO #include <linux/seq_file.h>
75e0b46d0eSHerbert Xu #include <linux/uio.h>
761576d986SJason Wang #include <linux/skb_array.h>
77761876c8SJason Wang #include <linux/bpf.h>
78761876c8SJason Wang #include <linux/bpf_trace.h>
7990e33d45SPetar Penkov #include <linux/mutex.h>
801da177e4SLinus Torvalds 
817c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
82f2780d6dSKirill Tkhai #include <linux/proc_fs.h>
831da177e4SLinus Torvalds 
844e24f2ddSChas Williams static void tun_default_link_ksettings(struct net_device *dev,
854e24f2ddSChas Williams 				       struct ethtool_link_ksettings *cmd);
864e24f2ddSChas Williams 
8714daa021SRusty Russell /* Uncomment to enable debugging */
8814daa021SRusty Russell /* #define TUN_DEBUG 1 */
8914daa021SRusty Russell 
901da177e4SLinus Torvalds #ifdef TUN_DEBUG
911da177e4SLinus Torvalds static int debug;
9214daa021SRusty Russell 
936b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
946b8a66eeSJoe Perches do {								\
956b8a66eeSJoe Perches 	if (tun->debug)						\
966b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
976b8a66eeSJoe Perches } while (0)
986b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
996b8a66eeSJoe Perches do {								\
1006b8a66eeSJoe Perches 	if (debug == 2)						\
1016b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
1026b8a66eeSJoe Perches } while (0)
10314daa021SRusty Russell #else
1046b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
1056b8a66eeSJoe Perches do {								\
1066b8a66eeSJoe Perches 	if (0)							\
1076b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
1086b8a66eeSJoe Perches } while (0)
1096b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
1106b8a66eeSJoe Perches do {								\
1116b8a66eeSJoe Perches 	if (0)							\
1126b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
1136b8a66eeSJoe Perches } while (0)
1141da177e4SLinus Torvalds #endif
1151da177e4SLinus Torvalds 
1167df13219SJason Wang #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
11766ccbc9cSJason Wang 
118031f5e03SMichael S. Tsirkin /* TUN device flags */
119031f5e03SMichael S. Tsirkin 
120031f5e03SMichael S. Tsirkin /* IFF_ATTACH_QUEUE is never stored in device flags,
121031f5e03SMichael S. Tsirkin  * overload it to mean fasync when stored there.
122031f5e03SMichael S. Tsirkin  */
123031f5e03SMichael S. Tsirkin #define TUN_FASYNC	IFF_ATTACH_QUEUE
1241cf8e410SMichael S. Tsirkin /* High bits in flags field are unused. */
1251cf8e410SMichael S. Tsirkin #define TUN_VNET_LE     0x80000000
1268b8e658bSGreg Kurz #define TUN_VNET_BE     0x40000000
127031f5e03SMichael S. Tsirkin 
128031f5e03SMichael S. Tsirkin #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
12990e33d45SPetar Penkov 		      IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
13090e33d45SPetar Penkov 
1310690899bSMichael S. Tsirkin #define GOODCOPY_LEN 128
1320690899bSMichael S. Tsirkin 
133f271b2ccSMax Krasnyansky #define FLT_EXACT_COUNT 8
134f271b2ccSMax Krasnyansky struct tap_filter {
135f271b2ccSMax Krasnyansky 	unsigned int    count;    /* Number of addrs. Zero means disabled */
136f271b2ccSMax Krasnyansky 	u32             mask[2];  /* Mask of the hashed addrs */
137f271b2ccSMax Krasnyansky 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
138f271b2ccSMax Krasnyansky };
139f271b2ccSMax Krasnyansky 
140baf71c5cSPankaj Gupta /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
141baf71c5cSPankaj Gupta  * to max number of VCPUs in guest. */
142baf71c5cSPankaj Gupta #define MAX_TAP_QUEUES 256
143b8732fb7SJason Wang #define MAX_TAP_FLOWS  4096
144c8d68e6bSJason Wang 
14596442e42SJason Wang #define TUN_FLOW_EXPIRE (3 * HZ)
14696442e42SJason Wang 
147608b9977SPaolo Abeni struct tun_pcpu_stats {
148608b9977SPaolo Abeni 	u64 rx_packets;
149608b9977SPaolo Abeni 	u64 rx_bytes;
150608b9977SPaolo Abeni 	u64 tx_packets;
151608b9977SPaolo Abeni 	u64 tx_bytes;
152608b9977SPaolo Abeni 	struct u64_stats_sync syncp;
153608b9977SPaolo Abeni 	u32 rx_dropped;
154608b9977SPaolo Abeni 	u32 tx_dropped;
155608b9977SPaolo Abeni 	u32 rx_frame_errors;
156608b9977SPaolo Abeni };
157608b9977SPaolo Abeni 
15854f968d6SJason Wang /* A tun_file connects an open character device to a tuntap netdevice. It
15992d4ea6eSstephen hemminger  * also contains all socket related structures (except sock_fprog and tap_filter)
16054f968d6SJason Wang  * to serve as one transmit queue for tuntap device. The sock_fprog and
16154f968d6SJason Wang  * tap_filter were kept in tun_struct since they were used for filtering for the
16236fe8c09SRami Rosen  * netdevice not for a specific queue (at least I didn't see the requirement for
16354f968d6SJason Wang  * this).
1646e914fc7SJason Wang  *
1656e914fc7SJason Wang  * RCU usage:
16636fe8c09SRami Rosen  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
1676e914fc7SJason Wang  * other can only be read while rcu_read_lock or rtnl_lock is held.
16854f968d6SJason Wang  */
169631ab46bSEric W. Biederman struct tun_file {
17054f968d6SJason Wang 	struct sock sk;
17154f968d6SJason Wang 	struct socket socket;
17254f968d6SJason Wang 	struct socket_wq wq;
1736e914fc7SJason Wang 	struct tun_struct __rcu *tun;
17454f968d6SJason Wang 	struct fasync_struct *fasync;
17554f968d6SJason Wang 	/* only used for fasnyc */
17654f968d6SJason Wang 	unsigned int flags;
177fb7589a1SPavel Emelyanov 	union {
178c8d68e6bSJason Wang 		u16 queue_index;
179fb7589a1SPavel Emelyanov 		unsigned int ifindex;
180fb7589a1SPavel Emelyanov 	};
18194317099SPetar Penkov 	struct napi_struct napi;
182aec72f33SEric Dumazet 	bool napi_enabled;
183af3fb24eSEric Dumazet 	bool napi_frags_enabled;
18490e33d45SPetar Penkov 	struct mutex napi_mutex;	/* Protects access to the above napi */
1854008e97fSJason Wang 	struct list_head next;
1864008e97fSJason Wang 	struct tun_struct *detached;
1875990a305SJason Wang 	struct ptr_ring tx_ring;
1888bf5c4eeSJesper Dangaard Brouer 	struct xdp_rxq_info xdp_rxq;
189631ab46bSEric W. Biederman };
190631ab46bSEric W. Biederman 
191f9e06c45SJason Wang struct tun_page {
192f9e06c45SJason Wang 	struct page *page;
193f9e06c45SJason Wang 	int count;
194f9e06c45SJason Wang };
195f9e06c45SJason Wang 
19696442e42SJason Wang struct tun_flow_entry {
19796442e42SJason Wang 	struct hlist_node hash_link;
19896442e42SJason Wang 	struct rcu_head rcu;
19996442e42SJason Wang 	struct tun_struct *tun;
20096442e42SJason Wang 
20196442e42SJason Wang 	u32 rxhash;
2029bc88939STom Herbert 	u32 rps_rxhash;
20396442e42SJason Wang 	int queue_index;
20496442e42SJason Wang 	unsigned long updated;
20596442e42SJason Wang };
20696442e42SJason Wang 
20796442e42SJason Wang #define TUN_NUM_FLOW_ENTRIES 1024
208f13b5468SLi RongQing #define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
20996442e42SJason Wang 
210cd5681d7SJason Wang struct tun_prog {
21196f84061SJason Wang 	struct rcu_head rcu;
21296f84061SJason Wang 	struct bpf_prog *prog;
21396f84061SJason Wang };
21496f84061SJason Wang 
21554f968d6SJason Wang /* Since the socket were moved to tun_file, to preserve the behavior of persist
21636fe8c09SRami Rosen  * device, socket filter, sndbuf and vnet header size were restore when the
21754f968d6SJason Wang  * file were attached to a persist device.
21854f968d6SJason Wang  */
21914daa021SRusty Russell struct tun_struct {
220c8d68e6bSJason Wang 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
221c8d68e6bSJason Wang 	unsigned int            numqueues;
222f271b2ccSMax Krasnyansky 	unsigned int 		flags;
2230625c883SEric W. Biederman 	kuid_t			owner;
2240625c883SEric W. Biederman 	kgid_t			group;
22514daa021SRusty Russell 
22614daa021SRusty Russell 	struct net_device	*dev;
227c8f44affSMichał Mirosław 	netdev_features_t	set_features;
22888255375SMichał Mirosław #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
229d591a1f3SDavid S. Miller 			  NETIF_F_TSO6)
230d9d52b51SMichael S. Tsirkin 
231eaea34b2SPaolo Abeni 	int			align;
232d9d52b51SMichael S. Tsirkin 	int			vnet_hdr_sz;
23354f968d6SJason Wang 	int			sndbuf;
23454f968d6SJason Wang 	struct tap_filter	txflt;
23554f968d6SJason Wang 	struct sock_fprog	fprog;
23654f968d6SJason Wang 	/* protected by rtnl lock */
23754f968d6SJason Wang 	bool			filter_attached;
23814daa021SRusty Russell #ifdef TUN_DEBUG
23914daa021SRusty Russell 	int debug;
24014daa021SRusty Russell #endif
24196442e42SJason Wang 	spinlock_t lock;
24296442e42SJason Wang 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
24396442e42SJason Wang 	struct timer_list flow_gc_timer;
24496442e42SJason Wang 	unsigned long ageing_time;
2454008e97fSJason Wang 	unsigned int numdisabled;
2464008e97fSJason Wang 	struct list_head disabled;
2475dbbaf2dSPaul Moore 	void *security;
248b8732fb7SJason Wang 	u32 flow_count;
2495503fcecSJason Wang 	u32 rx_batched;
250608b9977SPaolo Abeni 	struct tun_pcpu_stats __percpu *pcpu_stats;
251761876c8SJason Wang 	struct bpf_prog __rcu *xdp_prog;
252cd5681d7SJason Wang 	struct tun_prog __rcu *steering_prog;
253aff3d70aSJason Wang 	struct tun_prog __rcu *filter_prog;
2544e24f2ddSChas Williams 	struct ethtool_link_ksettings link_ksettings;
25514daa021SRusty Russell };
25614daa021SRusty Russell 
257aff3d70aSJason Wang struct veth {
258aff3d70aSJason Wang 	__be16 h_vlan_proto;
259aff3d70aSJason Wang 	__be16 h_vlan_TCI;
2601da177e4SLinus Torvalds };
2611da177e4SLinus Torvalds 
2621ffcbc85SJesper Dangaard Brouer bool tun_is_xdp_frame(void *ptr)
263fc72d1d5SJason Wang {
264fc72d1d5SJason Wang 	return (unsigned long)ptr & TUN_XDP_FLAG;
265fc72d1d5SJason Wang }
2661ffcbc85SJesper Dangaard Brouer EXPORT_SYMBOL(tun_is_xdp_frame);
267fc72d1d5SJason Wang 
268fc72d1d5SJason Wang void *tun_xdp_to_ptr(void *ptr)
269fc72d1d5SJason Wang {
270fc72d1d5SJason Wang 	return (void *)((unsigned long)ptr | TUN_XDP_FLAG);
271fc72d1d5SJason Wang }
272fc72d1d5SJason Wang EXPORT_SYMBOL(tun_xdp_to_ptr);
273fc72d1d5SJason Wang 
274fc72d1d5SJason Wang void *tun_ptr_to_xdp(void *ptr)
275fc72d1d5SJason Wang {
276fc72d1d5SJason Wang 	return (void *)((unsigned long)ptr & ~TUN_XDP_FLAG);
277fc72d1d5SJason Wang }
278fc72d1d5SJason Wang EXPORT_SYMBOL(tun_ptr_to_xdp);
279fc72d1d5SJason Wang 
28094317099SPetar Penkov static int tun_napi_receive(struct napi_struct *napi, int budget)
28194317099SPetar Penkov {
28294317099SPetar Penkov 	struct tun_file *tfile = container_of(napi, struct tun_file, napi);
28394317099SPetar Penkov 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
28494317099SPetar Penkov 	struct sk_buff_head process_queue;
28594317099SPetar Penkov 	struct sk_buff *skb;
28694317099SPetar Penkov 	int received = 0;
28794317099SPetar Penkov 
28894317099SPetar Penkov 	__skb_queue_head_init(&process_queue);
28994317099SPetar Penkov 
29094317099SPetar Penkov 	spin_lock(&queue->lock);
29194317099SPetar Penkov 	skb_queue_splice_tail_init(queue, &process_queue);
29294317099SPetar Penkov 	spin_unlock(&queue->lock);
29394317099SPetar Penkov 
29494317099SPetar Penkov 	while (received < budget && (skb = __skb_dequeue(&process_queue))) {
29594317099SPetar Penkov 		napi_gro_receive(napi, skb);
29694317099SPetar Penkov 		++received;
29794317099SPetar Penkov 	}
29894317099SPetar Penkov 
29994317099SPetar Penkov 	if (!skb_queue_empty(&process_queue)) {
30094317099SPetar Penkov 		spin_lock(&queue->lock);
30194317099SPetar Penkov 		skb_queue_splice(&process_queue, queue);
30294317099SPetar Penkov 		spin_unlock(&queue->lock);
30394317099SPetar Penkov 	}
30494317099SPetar Penkov 
30594317099SPetar Penkov 	return received;
30694317099SPetar Penkov }
30794317099SPetar Penkov 
30894317099SPetar Penkov static int tun_napi_poll(struct napi_struct *napi, int budget)
30994317099SPetar Penkov {
31094317099SPetar Penkov 	unsigned int received;
31194317099SPetar Penkov 
31294317099SPetar Penkov 	received = tun_napi_receive(napi, budget);
31394317099SPetar Penkov 
31494317099SPetar Penkov 	if (received < budget)
31594317099SPetar Penkov 		napi_complete_done(napi, received);
31694317099SPetar Penkov 
31794317099SPetar Penkov 	return received;
31894317099SPetar Penkov }
31994317099SPetar Penkov 
32094317099SPetar Penkov static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
321af3fb24eSEric Dumazet 			  bool napi_en, bool napi_frags)
32294317099SPetar Penkov {
323aec72f33SEric Dumazet 	tfile->napi_enabled = napi_en;
324af3fb24eSEric Dumazet 	tfile->napi_frags_enabled = napi_en && napi_frags;
32594317099SPetar Penkov 	if (napi_en) {
32694317099SPetar Penkov 		netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
32794317099SPetar Penkov 			       NAPI_POLL_WEIGHT);
32894317099SPetar Penkov 		napi_enable(&tfile->napi);
32994317099SPetar Penkov 	}
33094317099SPetar Penkov }
33194317099SPetar Penkov 
33206e55addSEric Dumazet static void tun_napi_disable(struct tun_file *tfile)
33394317099SPetar Penkov {
334aec72f33SEric Dumazet 	if (tfile->napi_enabled)
33594317099SPetar Penkov 		napi_disable(&tfile->napi);
33694317099SPetar Penkov }
33794317099SPetar Penkov 
33806e55addSEric Dumazet static void tun_napi_del(struct tun_file *tfile)
33994317099SPetar Penkov {
340aec72f33SEric Dumazet 	if (tfile->napi_enabled)
34194317099SPetar Penkov 		netif_napi_del(&tfile->napi);
34294317099SPetar Penkov }
34394317099SPetar Penkov 
344af3fb24eSEric Dumazet static bool tun_napi_frags_enabled(const struct tun_file *tfile)
34590e33d45SPetar Penkov {
346af3fb24eSEric Dumazet 	return tfile->napi_frags_enabled;
34790e33d45SPetar Penkov }
34890e33d45SPetar Penkov 
3498b8e658bSGreg Kurz #ifdef CONFIG_TUN_VNET_CROSS_LE
3508b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3518b8e658bSGreg Kurz {
3528b8e658bSGreg Kurz 	return tun->flags & TUN_VNET_BE ? false :
3538b8e658bSGreg Kurz 		virtio_legacy_is_little_endian();
3548b8e658bSGreg Kurz }
3558b8e658bSGreg Kurz 
3568b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3578b8e658bSGreg Kurz {
3588b8e658bSGreg Kurz 	int be = !!(tun->flags & TUN_VNET_BE);
3598b8e658bSGreg Kurz 
3608b8e658bSGreg Kurz 	if (put_user(be, argp))
3618b8e658bSGreg Kurz 		return -EFAULT;
3628b8e658bSGreg Kurz 
3638b8e658bSGreg Kurz 	return 0;
3648b8e658bSGreg Kurz }
3658b8e658bSGreg Kurz 
3668b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3678b8e658bSGreg Kurz {
3688b8e658bSGreg Kurz 	int be;
3698b8e658bSGreg Kurz 
3708b8e658bSGreg Kurz 	if (get_user(be, argp))
3718b8e658bSGreg Kurz 		return -EFAULT;
3728b8e658bSGreg Kurz 
3738b8e658bSGreg Kurz 	if (be)
3748b8e658bSGreg Kurz 		tun->flags |= TUN_VNET_BE;
3758b8e658bSGreg Kurz 	else
3768b8e658bSGreg Kurz 		tun->flags &= ~TUN_VNET_BE;
3778b8e658bSGreg Kurz 
3788b8e658bSGreg Kurz 	return 0;
3798b8e658bSGreg Kurz }
3808b8e658bSGreg Kurz #else
3818b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
3828b8e658bSGreg Kurz {
3838b8e658bSGreg Kurz 	return virtio_legacy_is_little_endian();
3848b8e658bSGreg Kurz }
3858b8e658bSGreg Kurz 
3868b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
3878b8e658bSGreg Kurz {
3888b8e658bSGreg Kurz 	return -EINVAL;
3898b8e658bSGreg Kurz }
3908b8e658bSGreg Kurz 
3918b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
3928b8e658bSGreg Kurz {
3938b8e658bSGreg Kurz 	return -EINVAL;
3948b8e658bSGreg Kurz }
3958b8e658bSGreg Kurz #endif /* CONFIG_TUN_VNET_CROSS_LE */
3968b8e658bSGreg Kurz 
39725bd55bbSGreg Kurz static inline bool tun_is_little_endian(struct tun_struct *tun)
39825bd55bbSGreg Kurz {
3997d824109SGreg Kurz 	return tun->flags & TUN_VNET_LE ||
4008b8e658bSGreg Kurz 		tun_legacy_is_little_endian(tun);
40125bd55bbSGreg Kurz }
40225bd55bbSGreg Kurz 
40356f0dcc5SMichael S. Tsirkin static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
40456f0dcc5SMichael S. Tsirkin {
40525bd55bbSGreg Kurz 	return __virtio16_to_cpu(tun_is_little_endian(tun), val);
40656f0dcc5SMichael S. Tsirkin }
40756f0dcc5SMichael S. Tsirkin 
40856f0dcc5SMichael S. Tsirkin static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
40956f0dcc5SMichael S. Tsirkin {
41025bd55bbSGreg Kurz 	return __cpu_to_virtio16(tun_is_little_endian(tun), val);
41156f0dcc5SMichael S. Tsirkin }
41256f0dcc5SMichael S. Tsirkin 
41396442e42SJason Wang static inline u32 tun_hashfn(u32 rxhash)
41496442e42SJason Wang {
415f13b5468SLi RongQing 	return rxhash & TUN_MASK_FLOW_ENTRIES;
41696442e42SJason Wang }
41796442e42SJason Wang 
41896442e42SJason Wang static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
41996442e42SJason Wang {
42096442e42SJason Wang 	struct tun_flow_entry *e;
42196442e42SJason Wang 
422b67bfe0dSSasha Levin 	hlist_for_each_entry_rcu(e, head, hash_link) {
42396442e42SJason Wang 		if (e->rxhash == rxhash)
42496442e42SJason Wang 			return e;
42596442e42SJason Wang 	}
42696442e42SJason Wang 	return NULL;
42796442e42SJason Wang }
42896442e42SJason Wang 
42996442e42SJason Wang static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
43096442e42SJason Wang 					      struct hlist_head *head,
43196442e42SJason Wang 					      u32 rxhash, u16 queue_index)
43296442e42SJason Wang {
4339fdc6befSEric Dumazet 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
4349fdc6befSEric Dumazet 
43596442e42SJason Wang 	if (e) {
43696442e42SJason Wang 		tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
43796442e42SJason Wang 			  rxhash, queue_index);
43896442e42SJason Wang 		e->updated = jiffies;
43996442e42SJason Wang 		e->rxhash = rxhash;
4409bc88939STom Herbert 		e->rps_rxhash = 0;
44196442e42SJason Wang 		e->queue_index = queue_index;
44296442e42SJason Wang 		e->tun = tun;
44396442e42SJason Wang 		hlist_add_head_rcu(&e->hash_link, head);
444b8732fb7SJason Wang 		++tun->flow_count;
44596442e42SJason Wang 	}
44696442e42SJason Wang 	return e;
44796442e42SJason Wang }
44896442e42SJason Wang 
44996442e42SJason Wang static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
45096442e42SJason Wang {
45196442e42SJason Wang 	tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
45296442e42SJason Wang 		  e->rxhash, e->queue_index);
45396442e42SJason Wang 	hlist_del_rcu(&e->hash_link);
4549fdc6befSEric Dumazet 	kfree_rcu(e, rcu);
455b8732fb7SJason Wang 	--tun->flow_count;
45696442e42SJason Wang }
45796442e42SJason Wang 
45896442e42SJason Wang static void tun_flow_flush(struct tun_struct *tun)
45996442e42SJason Wang {
46096442e42SJason Wang 	int i;
46196442e42SJason Wang 
46296442e42SJason Wang 	spin_lock_bh(&tun->lock);
46396442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
46496442e42SJason Wang 		struct tun_flow_entry *e;
465b67bfe0dSSasha Levin 		struct hlist_node *n;
46696442e42SJason Wang 
467b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
46896442e42SJason Wang 			tun_flow_delete(tun, e);
46996442e42SJason Wang 	}
47096442e42SJason Wang 	spin_unlock_bh(&tun->lock);
47196442e42SJason Wang }
47296442e42SJason Wang 
47396442e42SJason Wang static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
47496442e42SJason Wang {
47596442e42SJason Wang 	int i;
47696442e42SJason Wang 
47796442e42SJason Wang 	spin_lock_bh(&tun->lock);
47896442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
47996442e42SJason Wang 		struct tun_flow_entry *e;
480b67bfe0dSSasha Levin 		struct hlist_node *n;
48196442e42SJason Wang 
482b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
48396442e42SJason Wang 			if (e->queue_index == queue_index)
48496442e42SJason Wang 				tun_flow_delete(tun, e);
48596442e42SJason Wang 		}
48696442e42SJason Wang 	}
48796442e42SJason Wang 	spin_unlock_bh(&tun->lock);
48896442e42SJason Wang }
48996442e42SJason Wang 
490e99e88a9SKees Cook static void tun_flow_cleanup(struct timer_list *t)
49196442e42SJason Wang {
492e99e88a9SKees Cook 	struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
49396442e42SJason Wang 	unsigned long delay = tun->ageing_time;
49496442e42SJason Wang 	unsigned long next_timer = jiffies + delay;
49596442e42SJason Wang 	unsigned long count = 0;
49696442e42SJason Wang 	int i;
49796442e42SJason Wang 
49896442e42SJason Wang 	tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
49996442e42SJason Wang 
5007dbfb4efSEric Dumazet 	spin_lock(&tun->lock);
50196442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
50296442e42SJason Wang 		struct tun_flow_entry *e;
503b67bfe0dSSasha Levin 		struct hlist_node *n;
50496442e42SJason Wang 
505b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
50696442e42SJason Wang 			unsigned long this_timer;
50781d98fa4SEric Dumazet 
50896442e42SJason Wang 			this_timer = e->updated + delay;
50981d98fa4SEric Dumazet 			if (time_before_eq(this_timer, jiffies)) {
51096442e42SJason Wang 				tun_flow_delete(tun, e);
51181d98fa4SEric Dumazet 				continue;
51281d98fa4SEric Dumazet 			}
51381d98fa4SEric Dumazet 			count++;
51481d98fa4SEric Dumazet 			if (time_before(this_timer, next_timer))
51596442e42SJason Wang 				next_timer = this_timer;
51696442e42SJason Wang 		}
51796442e42SJason Wang 	}
51896442e42SJason Wang 
51996442e42SJason Wang 	if (count)
52096442e42SJason Wang 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
5217dbfb4efSEric Dumazet 	spin_unlock(&tun->lock);
52296442e42SJason Wang }
52396442e42SJason Wang 
52449974420SEric Dumazet static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
5259e85722dSJason Wang 			    struct tun_file *tfile)
52696442e42SJason Wang {
52796442e42SJason Wang 	struct hlist_head *head;
52896442e42SJason Wang 	struct tun_flow_entry *e;
52996442e42SJason Wang 	unsigned long delay = tun->ageing_time;
5309e85722dSJason Wang 	u16 queue_index = tfile->queue_index;
53196442e42SJason Wang 
53296442e42SJason Wang 	if (!rxhash)
53396442e42SJason Wang 		return;
53496442e42SJason Wang 	else
53596442e42SJason Wang 		head = &tun->flows[tun_hashfn(rxhash)];
53696442e42SJason Wang 
53796442e42SJason Wang 	rcu_read_lock();
53896442e42SJason Wang 
53996442e42SJason Wang 	e = tun_flow_find(head, rxhash);
54096442e42SJason Wang 	if (likely(e)) {
54196442e42SJason Wang 		/* TODO: keep queueing to old queue until it's empty? */
54296442e42SJason Wang 		e->queue_index = queue_index;
54396442e42SJason Wang 		e->updated = jiffies;
5449bc88939STom Herbert 		sock_rps_record_flow_hash(e->rps_rxhash);
54596442e42SJason Wang 	} else {
54696442e42SJason Wang 		spin_lock_bh(&tun->lock);
547b8732fb7SJason Wang 		if (!tun_flow_find(head, rxhash) &&
548b8732fb7SJason Wang 		    tun->flow_count < MAX_TAP_FLOWS)
54996442e42SJason Wang 			tun_flow_create(tun, head, rxhash, queue_index);
55096442e42SJason Wang 
55196442e42SJason Wang 		if (!timer_pending(&tun->flow_gc_timer))
55296442e42SJason Wang 			mod_timer(&tun->flow_gc_timer,
55396442e42SJason Wang 				  round_jiffies_up(jiffies + delay));
55496442e42SJason Wang 		spin_unlock_bh(&tun->lock);
55596442e42SJason Wang 	}
55696442e42SJason Wang 
55796442e42SJason Wang 	rcu_read_unlock();
55896442e42SJason Wang }
55996442e42SJason Wang 
5609bc88939STom Herbert /**
5619bc88939STom Herbert  * Save the hash received in the stack receive path and update the
5629bc88939STom Herbert  * flow_hash table accordingly.
5639bc88939STom Herbert  */
5649bc88939STom Herbert static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
5659bc88939STom Herbert {
566567e4b79SEric Dumazet 	if (unlikely(e->rps_rxhash != hash))
5679bc88939STom Herbert 		e->rps_rxhash = hash;
5689bc88939STom Herbert }
5699bc88939STom Herbert 
5704b035271SWang Li /* We try to identify a flow through its rxhash. The reason that
57192d4ea6eSstephen hemminger  * we do not check rxq no. is because some cards(e.g 82599), chooses
572c8d68e6bSJason Wang  * the rxq based on the txq where the last packet of the flow comes. As
573c8d68e6bSJason Wang  * the userspace application move between processors, we may get a
5744b035271SWang Li  * different rxq no. here.
575c8d68e6bSJason Wang  */
57696f84061SJason Wang static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
577c8d68e6bSJason Wang {
57896442e42SJason Wang 	struct tun_flow_entry *e;
579c8d68e6bSJason Wang 	u32 txq = 0;
580c8d68e6bSJason Wang 	u32 numqueues = 0;
581c8d68e6bSJason Wang 
5826aa7de05SMark Rutland 	numqueues = READ_ONCE(tun->numqueues);
583c8d68e6bSJason Wang 
584feec084aSJason Wang 	txq = __skb_get_hash_symmetric(skb);
58596442e42SJason Wang 	e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
5869bc88939STom Herbert 	if (e) {
5879bc88939STom Herbert 		tun_flow_save_rps_rxhash(e, txq);
588fbe4d456SZhi Yong Wu 		txq = e->queue_index;
5894b035271SWang Li 	} else {
590c8d68e6bSJason Wang 		/* use multiply and shift instead of expensive divide */
591c8d68e6bSJason Wang 		txq = ((u64)txq * numqueues) >> 32;
592c8d68e6bSJason Wang 	}
593c8d68e6bSJason Wang 
594c8d68e6bSJason Wang 	return txq;
595c8d68e6bSJason Wang }
596c8d68e6bSJason Wang 
59796f84061SJason Wang static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
59896f84061SJason Wang {
599cd5681d7SJason Wang 	struct tun_prog *prog;
60096f84061SJason Wang 	u16 ret = 0;
60196f84061SJason Wang 
60296f84061SJason Wang 	prog = rcu_dereference(tun->steering_prog);
60396f84061SJason Wang 	if (prog)
60496f84061SJason Wang 		ret = bpf_prog_run_clear_cb(prog->prog, skb);
60596f84061SJason Wang 
60696f84061SJason Wang 	return ret % tun->numqueues;
60796f84061SJason Wang }
60896f84061SJason Wang 
60996f84061SJason Wang static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
6104f49dec9SAlexander Duyck 			    struct net_device *sb_dev,
6114f49dec9SAlexander Duyck 			    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;
6631ffcbc85SJesper Dangaard Brouer 	if (tun_is_xdp_frame(ptr)) {
6641ffcbc85SJesper Dangaard Brouer 		struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
665fc72d1d5SJason Wang 
66603993094SJesper Dangaard Brouer 		xdp_return_frame(xdpf);
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 
684c8d68e6bSJason Wang static void __tun_detach(struct tun_file *tfile, bool clean)
685c8d68e6bSJason Wang {
686c8d68e6bSJason Wang 	struct tun_file *ntfile;
687c8d68e6bSJason Wang 	struct tun_struct *tun;
688c8d68e6bSJason Wang 
689b8deabd3SJason Wang 	tun = rtnl_dereference(tfile->tun);
690b8deabd3SJason Wang 
69194317099SPetar Penkov 	if (tun && clean) {
69206e55addSEric Dumazet 		tun_napi_disable(tfile);
69306e55addSEric Dumazet 		tun_napi_del(tfile);
69494317099SPetar Penkov 	}
69594317099SPetar Penkov 
6969e85722dSJason Wang 	if (tun && !tfile->detached) {
697c8d68e6bSJason Wang 		u16 index = tfile->queue_index;
698c8d68e6bSJason Wang 		BUG_ON(index >= tun->numqueues);
699c8d68e6bSJason Wang 
700c8d68e6bSJason Wang 		rcu_assign_pointer(tun->tfiles[index],
701c8d68e6bSJason Wang 				   tun->tfiles[tun->numqueues - 1]);
702b8deabd3SJason Wang 		ntfile = rtnl_dereference(tun->tfiles[index]);
703c8d68e6bSJason Wang 		ntfile->queue_index = index;
704c8d68e6bSJason Wang 
705c8d68e6bSJason Wang 		--tun->numqueues;
7069e85722dSJason Wang 		if (clean) {
707c956674bSMonam Agarwal 			RCU_INIT_POINTER(tfile->tun, NULL);
708c8d68e6bSJason Wang 			sock_put(&tfile->sk);
7099e85722dSJason Wang 		} else
7104008e97fSJason Wang 			tun_disable_queue(tun, tfile);
711c8d68e6bSJason Wang 
712c8d68e6bSJason Wang 		synchronize_net();
71396442e42SJason Wang 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
714c8d68e6bSJason Wang 		/* Drop read queue */
7154bfb0513SJason Wang 		tun_queue_purge(tfile);
716c8d68e6bSJason Wang 		tun_set_real_num_queues(tun);
717dd38bd85SJason Wang 	} else if (tfile->detached && clean) {
7184008e97fSJason Wang 		tun = tun_enable_queue(tfile);
719dd38bd85SJason Wang 		sock_put(&tfile->sk);
720dd38bd85SJason Wang 	}
721c8d68e6bSJason Wang 
722c8d68e6bSJason Wang 	if (clean) {
723af668b3cSMichael S. Tsirkin 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
724af668b3cSMichael S. Tsirkin 			netif_carrier_off(tun->dev);
725af668b3cSMichael S. Tsirkin 
72640630b82SMichael S. Tsirkin 			if (!(tun->flags & IFF_PERSIST) &&
727af668b3cSMichael S. Tsirkin 			    tun->dev->reg_state == NETREG_REGISTERED)
7284008e97fSJason Wang 				unregister_netdevice(tun->dev);
729af668b3cSMichael S. Tsirkin 		}
730b196d88aSJason Wang 		if (tun)
731b196d88aSJason Wang 			xdp_rxq_info_unreg(&tfile->xdp_rxq);
7327063efd3SJason Wang 		ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
733140e807dSEric W. Biederman 		sock_put(&tfile->sk);
734c8d68e6bSJason Wang 	}
735c8d68e6bSJason Wang }
736c8d68e6bSJason Wang 
737c8d68e6bSJason Wang static void tun_detach(struct tun_file *tfile, bool clean)
738c8d68e6bSJason Wang {
73983c1f36fSSabrina Dubroca 	struct tun_struct *tun;
74083c1f36fSSabrina Dubroca 	struct net_device *dev;
74183c1f36fSSabrina Dubroca 
742c8d68e6bSJason Wang 	rtnl_lock();
74383c1f36fSSabrina Dubroca 	tun = rtnl_dereference(tfile->tun);
74483c1f36fSSabrina Dubroca 	dev = tun ? tun->dev : NULL;
745c8d68e6bSJason Wang 	__tun_detach(tfile, clean);
74683c1f36fSSabrina Dubroca 	if (dev)
74783c1f36fSSabrina Dubroca 		netdev_state_change(dev);
748c8d68e6bSJason Wang 	rtnl_unlock();
749c8d68e6bSJason Wang }
750c8d68e6bSJason Wang 
751c8d68e6bSJason Wang static void tun_detach_all(struct net_device *dev)
752c8d68e6bSJason Wang {
753c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
7544008e97fSJason Wang 	struct tun_file *tfile, *tmp;
755c8d68e6bSJason Wang 	int i, n = tun->numqueues;
756c8d68e6bSJason Wang 
757c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
758b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
759c8d68e6bSJason Wang 		BUG_ON(!tfile);
76006e55addSEric Dumazet 		tun_napi_disable(tfile);
761addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7629e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
763c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
764c8d68e6bSJason Wang 		--tun->numqueues;
765c8d68e6bSJason Wang 	}
7669e85722dSJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
767addf8fc4SJason Wang 		tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
7689e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
769c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
7709e85722dSJason Wang 	}
771c8d68e6bSJason Wang 	BUG_ON(tun->numqueues != 0);
772c8d68e6bSJason Wang 
773c8d68e6bSJason Wang 	synchronize_net();
774c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
775b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
77606e55addSEric Dumazet 		tun_napi_del(tfile);
777c8d68e6bSJason Wang 		/* Drop read queue */
7784bfb0513SJason Wang 		tun_queue_purge(tfile);
779b196d88aSJason Wang 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
780c8d68e6bSJason Wang 		sock_put(&tfile->sk);
781c8d68e6bSJason Wang 	}
7824008e97fSJason Wang 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
7834008e97fSJason Wang 		tun_enable_queue(tfile);
7844bfb0513SJason Wang 		tun_queue_purge(tfile);
785b196d88aSJason Wang 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
7864008e97fSJason Wang 		sock_put(&tfile->sk);
7874008e97fSJason Wang 	}
7884008e97fSJason Wang 	BUG_ON(tun->numdisabled != 0);
789dd38bd85SJason Wang 
79040630b82SMichael S. Tsirkin 	if (tun->flags & IFF_PERSIST)
791dd38bd85SJason Wang 		module_put(THIS_MODULE);
792c8d68e6bSJason Wang }
793c8d68e6bSJason Wang 
79494317099SPetar Penkov static int tun_attach(struct tun_struct *tun, struct file *file,
795af3fb24eSEric Dumazet 		      bool skip_filter, bool napi, bool napi_frags)
796a7385ba2SEric W. Biederman {
797631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
7981576d986SJason Wang 	struct net_device *dev = tun->dev;
79938231b7aSEric W. Biederman 	int err;
800a7385ba2SEric W. Biederman 
8015dbbaf2dSPaul Moore 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
8025dbbaf2dSPaul Moore 	if (err < 0)
8035dbbaf2dSPaul Moore 		goto out;
8045dbbaf2dSPaul Moore 
80538231b7aSEric W. Biederman 	err = -EINVAL;
8069e85722dSJason Wang 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
80738231b7aSEric W. Biederman 		goto out;
80838231b7aSEric W. Biederman 
80938231b7aSEric W. Biederman 	err = -EBUSY;
81040630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
811c8d68e6bSJason Wang 		goto out;
812c8d68e6bSJason Wang 
813c8d68e6bSJason Wang 	err = -E2BIG;
8144008e97fSJason Wang 	if (!tfile->detached &&
8154008e97fSJason Wang 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
81638231b7aSEric W. Biederman 		goto out;
81738231b7aSEric W. Biederman 
81838231b7aSEric W. Biederman 	err = 0;
81954f968d6SJason Wang 
82092d4ea6eSstephen hemminger 	/* Re-attach the filter to persist device */
821849c9b6fSPavel Emelyanov 	if (!skip_filter && (tun->filter_attached == true)) {
8228ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
8238ced425eSHannes Frederic Sowa 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
8248ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
82554f968d6SJason Wang 		if (!err)
82654f968d6SJason Wang 			goto out;
82754f968d6SJason Wang 	}
8281576d986SJason Wang 
8291576d986SJason Wang 	if (!tfile->detached &&
830b196d88aSJason Wang 	    ptr_ring_resize(&tfile->tx_ring, dev->tx_queue_len,
831b196d88aSJason Wang 			    GFP_KERNEL, tun_ptr_free)) {
8321576d986SJason Wang 		err = -ENOMEM;
8331576d986SJason Wang 		goto out;
8341576d986SJason Wang 	}
8351576d986SJason Wang 
836c8d68e6bSJason Wang 	tfile->queue_index = tun->numqueues;
837addf8fc4SJason Wang 	tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
8388bf5c4eeSJesper Dangaard Brouer 
8398bf5c4eeSJesper Dangaard Brouer 	if (tfile->detached) {
8408bf5c4eeSJesper Dangaard Brouer 		/* Re-attach detached tfile, updating XDP queue_index */
8418bf5c4eeSJesper Dangaard Brouer 		WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
8428bf5c4eeSJesper Dangaard Brouer 
8438bf5c4eeSJesper Dangaard Brouer 		if (tfile->xdp_rxq.queue_index    != tfile->queue_index)
8448bf5c4eeSJesper Dangaard Brouer 			tfile->xdp_rxq.queue_index = tfile->queue_index;
8458bf5c4eeSJesper Dangaard Brouer 	} else {
8468bf5c4eeSJesper Dangaard Brouer 		/* Setup XDP RX-queue info, for new tfile getting attached */
8478bf5c4eeSJesper Dangaard Brouer 		err = xdp_rxq_info_reg(&tfile->xdp_rxq,
8488bf5c4eeSJesper Dangaard Brouer 				       tun->dev, tfile->queue_index);
8498bf5c4eeSJesper Dangaard Brouer 		if (err < 0)
8508bf5c4eeSJesper Dangaard Brouer 			goto out;
8518d5d8852SJesper Dangaard Brouer 		err = xdp_rxq_info_reg_mem_model(&tfile->xdp_rxq,
8528d5d8852SJesper Dangaard Brouer 						 MEM_TYPE_PAGE_SHARED, NULL);
8538d5d8852SJesper Dangaard Brouer 		if (err < 0) {
8548d5d8852SJesper Dangaard Brouer 			xdp_rxq_info_unreg(&tfile->xdp_rxq);
8558d5d8852SJesper Dangaard Brouer 			goto out;
8568d5d8852SJesper Dangaard Brouer 		}
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);
868af3fb24eSEric Dumazet 		tun_napi_init(tun, tfile, napi, napi_frags);
86994317099SPetar Penkov 	}
8704008e97fSJason Wang 
871e4a2a304SJason Wang 	if (rtnl_dereference(tun->xdp_prog))
872e4a2a304SJason Wang 		sock_set_flag(&tfile->sk, SOCK_XDP);
873e4a2a304SJason Wang 
874c8d68e6bSJason Wang 	tun_set_real_num_queues(tun);
875c8d68e6bSJason Wang 
876c8d68e6bSJason Wang 	/* device is allowed to go away first, so no need to hold extra
877c8d68e6bSJason Wang 	 * refcnt.
878c8d68e6bSJason Wang 	 */
879a7385ba2SEric W. Biederman 
88038231b7aSEric W. Biederman out:
88138231b7aSEric W. Biederman 	return err;
882a7385ba2SEric W. Biederman }
883a7385ba2SEric W. Biederman 
8849484dc74Syuan linyu static struct tun_struct *tun_get(struct tun_file *tfile)
885631ab46bSEric W. Biederman {
8866e914fc7SJason Wang 	struct tun_struct *tun;
887c70f1829SEric W. Biederman 
8886e914fc7SJason Wang 	rcu_read_lock();
8896e914fc7SJason Wang 	tun = rcu_dereference(tfile->tun);
8906e914fc7SJason Wang 	if (tun)
8916e914fc7SJason Wang 		dev_hold(tun->dev);
8926e914fc7SJason Wang 	rcu_read_unlock();
893c70f1829SEric W. Biederman 
894c70f1829SEric W. Biederman 	return tun;
895631ab46bSEric W. Biederman }
896631ab46bSEric W. Biederman 
897631ab46bSEric W. Biederman static void tun_put(struct tun_struct *tun)
898631ab46bSEric W. Biederman {
8996e914fc7SJason Wang 	dev_put(tun->dev);
900631ab46bSEric W. Biederman }
901631ab46bSEric W. Biederman 
9026b8a66eeSJoe Perches /* TAP filtering */
903f271b2ccSMax Krasnyansky static void addr_hash_set(u32 *mask, const u8 *addr)
904f271b2ccSMax Krasnyansky {
905f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
906f271b2ccSMax Krasnyansky 	mask[n >> 5] |= (1 << (n & 31));
907f271b2ccSMax Krasnyansky }
908f271b2ccSMax Krasnyansky 
909f271b2ccSMax Krasnyansky static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
910f271b2ccSMax Krasnyansky {
911f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
912f271b2ccSMax Krasnyansky 	return mask[n >> 5] & (1 << (n & 31));
913f271b2ccSMax Krasnyansky }
914f271b2ccSMax Krasnyansky 
915f271b2ccSMax Krasnyansky static int update_filter(struct tap_filter *filter, void __user *arg)
916f271b2ccSMax Krasnyansky {
917f271b2ccSMax Krasnyansky 	struct { u8 u[ETH_ALEN]; } *addr;
918f271b2ccSMax Krasnyansky 	struct tun_filter uf;
919f271b2ccSMax Krasnyansky 	int err, alen, n, nexact;
920f271b2ccSMax Krasnyansky 
921f271b2ccSMax Krasnyansky 	if (copy_from_user(&uf, arg, sizeof(uf)))
922f271b2ccSMax Krasnyansky 		return -EFAULT;
923f271b2ccSMax Krasnyansky 
924f271b2ccSMax Krasnyansky 	if (!uf.count) {
925f271b2ccSMax Krasnyansky 		/* Disabled */
926f271b2ccSMax Krasnyansky 		filter->count = 0;
927f271b2ccSMax Krasnyansky 		return 0;
928f271b2ccSMax Krasnyansky 	}
929f271b2ccSMax Krasnyansky 
930f271b2ccSMax Krasnyansky 	alen = ETH_ALEN * uf.count;
93128e8190dSMarkus Elfring 	addr = memdup_user(arg + sizeof(uf), alen);
93228e8190dSMarkus Elfring 	if (IS_ERR(addr))
93328e8190dSMarkus Elfring 		return PTR_ERR(addr);
934f271b2ccSMax Krasnyansky 
935f271b2ccSMax Krasnyansky 	/* The filter is updated without holding any locks. Which is
936f271b2ccSMax Krasnyansky 	 * perfectly safe. We disable it first and in the worst
937f271b2ccSMax Krasnyansky 	 * case we'll accept a few undesired packets. */
938f271b2ccSMax Krasnyansky 	filter->count = 0;
939f271b2ccSMax Krasnyansky 	wmb();
940f271b2ccSMax Krasnyansky 
941f271b2ccSMax Krasnyansky 	/* Use first set of addresses as an exact filter */
942f271b2ccSMax Krasnyansky 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
943f271b2ccSMax Krasnyansky 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
944f271b2ccSMax Krasnyansky 
945f271b2ccSMax Krasnyansky 	nexact = n;
946f271b2ccSMax Krasnyansky 
947cfbf84fcSAlex Williamson 	/* Remaining multicast addresses are hashed,
948cfbf84fcSAlex Williamson 	 * unicast will leave the filter disabled. */
949f271b2ccSMax Krasnyansky 	memset(filter->mask, 0, sizeof(filter->mask));
950cfbf84fcSAlex Williamson 	for (; n < uf.count; n++) {
951cfbf84fcSAlex Williamson 		if (!is_multicast_ether_addr(addr[n].u)) {
952cfbf84fcSAlex Williamson 			err = 0; /* no filter */
9533b8d2a69SMarkus Elfring 			goto free_addr;
954cfbf84fcSAlex Williamson 		}
955f271b2ccSMax Krasnyansky 		addr_hash_set(filter->mask, addr[n].u);
956cfbf84fcSAlex Williamson 	}
957f271b2ccSMax Krasnyansky 
958f271b2ccSMax Krasnyansky 	/* For ALLMULTI just set the mask to all ones.
959f271b2ccSMax Krasnyansky 	 * This overrides the mask populated above. */
960f271b2ccSMax Krasnyansky 	if ((uf.flags & TUN_FLT_ALLMULTI))
961f271b2ccSMax Krasnyansky 		memset(filter->mask, ~0, sizeof(filter->mask));
962f271b2ccSMax Krasnyansky 
963f271b2ccSMax Krasnyansky 	/* Now enable the filter */
964f271b2ccSMax Krasnyansky 	wmb();
965f271b2ccSMax Krasnyansky 	filter->count = nexact;
966f271b2ccSMax Krasnyansky 
967f271b2ccSMax Krasnyansky 	/* Return the number of exact filters */
968f271b2ccSMax Krasnyansky 	err = nexact;
9693b8d2a69SMarkus Elfring free_addr:
970f271b2ccSMax Krasnyansky 	kfree(addr);
971f271b2ccSMax Krasnyansky 	return err;
972f271b2ccSMax Krasnyansky }
973f271b2ccSMax Krasnyansky 
974f271b2ccSMax Krasnyansky /* Returns: 0 - drop, !=0 - accept */
975f271b2ccSMax Krasnyansky static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
976f271b2ccSMax Krasnyansky {
977f271b2ccSMax Krasnyansky 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
978f271b2ccSMax Krasnyansky 	 * at this point. */
979f271b2ccSMax Krasnyansky 	struct ethhdr *eh = (struct ethhdr *) skb->data;
980f271b2ccSMax Krasnyansky 	int i;
981f271b2ccSMax Krasnyansky 
982f271b2ccSMax Krasnyansky 	/* Exact match */
983f271b2ccSMax Krasnyansky 	for (i = 0; i < filter->count; i++)
9842e42e474SJoe Perches 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
985f271b2ccSMax Krasnyansky 			return 1;
986f271b2ccSMax Krasnyansky 
987f271b2ccSMax Krasnyansky 	/* Inexact match (multicast only) */
988f271b2ccSMax Krasnyansky 	if (is_multicast_ether_addr(eh->h_dest))
989f271b2ccSMax Krasnyansky 		return addr_hash_test(filter->mask, eh->h_dest);
990f271b2ccSMax Krasnyansky 
991f271b2ccSMax Krasnyansky 	return 0;
992f271b2ccSMax Krasnyansky }
993f271b2ccSMax Krasnyansky 
994f271b2ccSMax Krasnyansky /*
995f271b2ccSMax Krasnyansky  * Checks whether the packet is accepted or not.
996f271b2ccSMax Krasnyansky  * Returns: 0 - drop, !=0 - accept
997f271b2ccSMax Krasnyansky  */
998f271b2ccSMax Krasnyansky static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
999f271b2ccSMax Krasnyansky {
1000f271b2ccSMax Krasnyansky 	if (!filter->count)
1001f271b2ccSMax Krasnyansky 		return 1;
1002f271b2ccSMax Krasnyansky 
1003f271b2ccSMax Krasnyansky 	return run_filter(filter, skb);
1004f271b2ccSMax Krasnyansky }
1005f271b2ccSMax Krasnyansky 
10061da177e4SLinus Torvalds /* Network device part of the driver */
10071da177e4SLinus Torvalds 
10081da177e4SLinus Torvalds static const struct ethtool_ops tun_ethtool_ops;
10091da177e4SLinus Torvalds 
1010c70f1829SEric W. Biederman /* Net device detach from fd. */
1011c70f1829SEric W. Biederman static void tun_net_uninit(struct net_device *dev)
1012c70f1829SEric W. Biederman {
1013c8d68e6bSJason Wang 	tun_detach_all(dev);
1014c70f1829SEric W. Biederman }
1015c70f1829SEric W. Biederman 
10161da177e4SLinus Torvalds /* Net device open. */
10171da177e4SLinus Torvalds static int tun_net_open(struct net_device *dev)
10181da177e4SLinus Torvalds {
1019b20e2d54SHannes Frederic Sowa 	struct tun_struct *tun = netdev_priv(dev);
1020b20e2d54SHannes Frederic Sowa 	int i;
1021b20e2d54SHannes Frederic Sowa 
1022c8d68e6bSJason Wang 	netif_tx_start_all_queues(dev);
1023b20e2d54SHannes Frederic Sowa 
1024b20e2d54SHannes Frederic Sowa 	for (i = 0; i < tun->numqueues; i++) {
1025b20e2d54SHannes Frederic Sowa 		struct tun_file *tfile;
1026b20e2d54SHannes Frederic Sowa 
1027b20e2d54SHannes Frederic Sowa 		tfile = rtnl_dereference(tun->tfiles[i]);
1028b20e2d54SHannes Frederic Sowa 		tfile->socket.sk->sk_write_space(tfile->socket.sk);
1029b20e2d54SHannes Frederic Sowa 	}
1030b20e2d54SHannes Frederic Sowa 
10311da177e4SLinus Torvalds 	return 0;
10321da177e4SLinus Torvalds }
10331da177e4SLinus Torvalds 
10341da177e4SLinus Torvalds /* Net device close. */
10351da177e4SLinus Torvalds static int tun_net_close(struct net_device *dev)
10361da177e4SLinus Torvalds {
1037c8d68e6bSJason Wang 	netif_tx_stop_all_queues(dev);
10381da177e4SLinus Torvalds 	return 0;
10391da177e4SLinus Torvalds }
10401da177e4SLinus Torvalds 
10411da177e4SLinus Torvalds /* Net device start xmit */
104296f84061SJason Wang static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
10431da177e4SLinus Torvalds {
10443df97ba8SJason Wang #ifdef CONFIG_RPS
104596f84061SJason Wang 	if (tun->numqueues == 1 && static_key_false(&rps_needed)) {
10469bc88939STom Herbert 		/* Select queue was not called for the skbuff, so we extract the
10479bc88939STom Herbert 		 * RPS hash and save it into the flow_table here.
10489bc88939STom Herbert 		 */
10494b035271SWang Li 		struct tun_flow_entry *e;
10509bc88939STom Herbert 		__u32 rxhash;
10519bc88939STom Herbert 
1052feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
10534b035271SWang Li 		e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash);
10549bc88939STom Herbert 		if (e)
10559bc88939STom Herbert 			tun_flow_save_rps_rxhash(e, rxhash);
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);
110581c89507SBjørn Mork 	if (len == 0 || pskb_trim(skb, len))
1106aff3d70aSJason Wang 		goto drop;
1107aff3d70aSJason Wang 
11081f8b977aSWillem de Bruijn 	if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
11097bf66305SJason Wang 		goto drop;
11107bf66305SJason Wang 
11117b996243SSoheil Hassas Yeganeh 	skb_tx_timestamp(skb);
1112eda29772SRichard Cochran 
11130110d6f2SMichael S. Tsirkin 	/* Orphan the skb - required as we might hang on to it
11147bf66305SJason Wang 	 * for indefinite time.
11157bf66305SJason Wang 	 */
11160110d6f2SMichael S. Tsirkin 	skb_orphan(skb);
11170110d6f2SMichael S. Tsirkin 
1118f8af75f3SEric Dumazet 	nf_reset(skb);
1119f8af75f3SEric Dumazet 
11205990a305SJason Wang 	if (ptr_ring_produce(&tfile->tx_ring, skb))
11211576d986SJason Wang 		goto drop;
11221da177e4SLinus Torvalds 
11231da177e4SLinus Torvalds 	/* Notify and wake up reader process */
112454f968d6SJason Wang 	if (tfile->flags & TUN_FASYNC)
112554f968d6SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
11269e641bdcSXi Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
11276e914fc7SJason Wang 
11286e914fc7SJason Wang 	rcu_read_unlock();
11296ed10654SPatrick McHardy 	return NETDEV_TX_OK;
11301da177e4SLinus Torvalds 
11311da177e4SLinus Torvalds drop:
1132608b9977SPaolo Abeni 	this_cpu_inc(tun->pcpu_stats->tx_dropped);
1133149d36f7SMichael S. Tsirkin 	skb_tx_error(skb);
11341da177e4SLinus Torvalds 	kfree_skb(skb);
11356e914fc7SJason Wang 	rcu_read_unlock();
1136baeababbSJason Wang 	return NET_XMIT_DROP;
11371da177e4SLinus Torvalds }
11381da177e4SLinus Torvalds 
1139f271b2ccSMax Krasnyansky static void tun_net_mclist(struct net_device *dev)
11401da177e4SLinus Torvalds {
1141f271b2ccSMax Krasnyansky 	/*
1142f271b2ccSMax Krasnyansky 	 * This callback is supposed to deal with mc filter in
1143f271b2ccSMax Krasnyansky 	 * _rx_ path and has nothing to do with the _tx_ path.
1144f271b2ccSMax Krasnyansky 	 * In rx path we always accept everything userspace gives us.
1145f271b2ccSMax Krasnyansky 	 */
11461da177e4SLinus Torvalds }
11471da177e4SLinus Torvalds 
1148c8f44affSMichał Mirosław static netdev_features_t tun_net_fix_features(struct net_device *dev,
1149c8f44affSMichał Mirosław 	netdev_features_t features)
115088255375SMichał Mirosław {
115188255375SMichał Mirosław 	struct tun_struct *tun = netdev_priv(dev);
115288255375SMichał Mirosław 
115388255375SMichał Mirosław 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
115488255375SMichał Mirosław }
1155eaea34b2SPaolo Abeni 
1156eaea34b2SPaolo Abeni static void tun_set_headroom(struct net_device *dev, int new_hr)
1157eaea34b2SPaolo Abeni {
1158eaea34b2SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1159eaea34b2SPaolo Abeni 
1160eaea34b2SPaolo Abeni 	if (new_hr < NET_SKB_PAD)
1161eaea34b2SPaolo Abeni 		new_hr = NET_SKB_PAD;
1162eaea34b2SPaolo Abeni 
1163eaea34b2SPaolo Abeni 	tun->align = new_hr;
1164eaea34b2SPaolo Abeni }
1165eaea34b2SPaolo Abeni 
1166bc1f4470Sstephen hemminger static void
1167608b9977SPaolo Abeni tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1168608b9977SPaolo Abeni {
1169608b9977SPaolo Abeni 	u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1170608b9977SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
1171608b9977SPaolo Abeni 	struct tun_pcpu_stats *p;
1172608b9977SPaolo Abeni 	int i;
1173608b9977SPaolo Abeni 
1174608b9977SPaolo Abeni 	for_each_possible_cpu(i) {
1175608b9977SPaolo Abeni 		u64 rxpackets, rxbytes, txpackets, txbytes;
1176608b9977SPaolo Abeni 		unsigned int start;
1177608b9977SPaolo Abeni 
1178608b9977SPaolo Abeni 		p = per_cpu_ptr(tun->pcpu_stats, i);
1179608b9977SPaolo Abeni 		do {
1180608b9977SPaolo Abeni 			start = u64_stats_fetch_begin(&p->syncp);
1181608b9977SPaolo Abeni 			rxpackets	= p->rx_packets;
1182608b9977SPaolo Abeni 			rxbytes		= p->rx_bytes;
1183608b9977SPaolo Abeni 			txpackets	= p->tx_packets;
1184608b9977SPaolo Abeni 			txbytes		= p->tx_bytes;
1185608b9977SPaolo Abeni 		} while (u64_stats_fetch_retry(&p->syncp, start));
1186608b9977SPaolo Abeni 
1187608b9977SPaolo Abeni 		stats->rx_packets	+= rxpackets;
1188608b9977SPaolo Abeni 		stats->rx_bytes		+= rxbytes;
1189608b9977SPaolo Abeni 		stats->tx_packets	+= txpackets;
1190608b9977SPaolo Abeni 		stats->tx_bytes		+= txbytes;
1191608b9977SPaolo Abeni 
1192608b9977SPaolo Abeni 		/* u32 counters */
1193608b9977SPaolo Abeni 		rx_dropped	+= p->rx_dropped;
1194608b9977SPaolo Abeni 		rx_frame_errors	+= p->rx_frame_errors;
1195608b9977SPaolo Abeni 		tx_dropped	+= p->tx_dropped;
1196608b9977SPaolo Abeni 	}
1197608b9977SPaolo Abeni 	stats->rx_dropped  = rx_dropped;
1198608b9977SPaolo Abeni 	stats->rx_frame_errors = rx_frame_errors;
1199608b9977SPaolo Abeni 	stats->tx_dropped = tx_dropped;
1200608b9977SPaolo Abeni }
1201608b9977SPaolo Abeni 
1202761876c8SJason Wang static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1203761876c8SJason Wang 		       struct netlink_ext_ack *extack)
1204761876c8SJason Wang {
1205761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1206e4a2a304SJason Wang 	struct tun_file *tfile;
1207761876c8SJason Wang 	struct bpf_prog *old_prog;
1208e4a2a304SJason Wang 	int i;
1209761876c8SJason Wang 
1210761876c8SJason Wang 	old_prog = rtnl_dereference(tun->xdp_prog);
1211761876c8SJason Wang 	rcu_assign_pointer(tun->xdp_prog, prog);
1212761876c8SJason Wang 	if (old_prog)
1213761876c8SJason Wang 		bpf_prog_put(old_prog);
1214761876c8SJason Wang 
1215e4a2a304SJason Wang 	for (i = 0; i < tun->numqueues; i++) {
1216e4a2a304SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1217e4a2a304SJason Wang 		if (prog)
1218e4a2a304SJason Wang 			sock_set_flag(&tfile->sk, SOCK_XDP);
1219e4a2a304SJason Wang 		else
1220e4a2a304SJason Wang 			sock_reset_flag(&tfile->sk, SOCK_XDP);
1221e4a2a304SJason Wang 	}
1222e4a2a304SJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
1223e4a2a304SJason Wang 		if (prog)
1224e4a2a304SJason Wang 			sock_set_flag(&tfile->sk, SOCK_XDP);
1225e4a2a304SJason Wang 		else
1226e4a2a304SJason Wang 			sock_reset_flag(&tfile->sk, SOCK_XDP);
1227e4a2a304SJason Wang 	}
1228e4a2a304SJason Wang 
1229761876c8SJason Wang 	return 0;
1230761876c8SJason Wang }
1231761876c8SJason Wang 
1232761876c8SJason Wang static u32 tun_xdp_query(struct net_device *dev)
1233761876c8SJason Wang {
1234761876c8SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1235761876c8SJason Wang 	const struct bpf_prog *xdp_prog;
1236761876c8SJason Wang 
1237761876c8SJason Wang 	xdp_prog = rtnl_dereference(tun->xdp_prog);
1238761876c8SJason Wang 	if (xdp_prog)
1239761876c8SJason Wang 		return xdp_prog->aux->id;
1240761876c8SJason Wang 
1241761876c8SJason Wang 	return 0;
1242761876c8SJason Wang }
1243761876c8SJason Wang 
1244f4e63525SJakub Kicinski static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1245761876c8SJason Wang {
1246761876c8SJason Wang 	switch (xdp->command) {
1247761876c8SJason Wang 	case XDP_SETUP_PROG:
1248761876c8SJason Wang 		return tun_xdp_set(dev, xdp->prog, xdp->extack);
1249761876c8SJason Wang 	case XDP_QUERY_PROG:
1250761876c8SJason Wang 		xdp->prog_id = tun_xdp_query(dev);
1251761876c8SJason Wang 		return 0;
1252761876c8SJason Wang 	default:
1253761876c8SJason Wang 		return -EINVAL;
1254761876c8SJason Wang 	}
1255761876c8SJason Wang }
1256761876c8SJason Wang 
1257758e43b7SStephen Hemminger static const struct net_device_ops tun_netdev_ops = {
1258c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1259758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1260758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
126100829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
126288255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1263c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
1264eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1265608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
1266758e43b7SStephen Hemminger };
1267758e43b7SStephen Hemminger 
12680c9d917bSJesper Dangaard Brouer static void __tun_xdp_flush_tfile(struct tun_file *tfile)
12690c9d917bSJesper Dangaard Brouer {
12700c9d917bSJesper Dangaard Brouer 	/* Notify and wake up reader process */
12710c9d917bSJesper Dangaard Brouer 	if (tfile->flags & TUN_FASYNC)
12720c9d917bSJesper Dangaard Brouer 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
12730c9d917bSJesper Dangaard Brouer 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
12740c9d917bSJesper Dangaard Brouer }
12750c9d917bSJesper Dangaard Brouer 
127642b33468SJesper Dangaard Brouer static int tun_xdp_xmit(struct net_device *dev, int n,
127742b33468SJesper Dangaard Brouer 			struct xdp_frame **frames, u32 flags)
1278fc72d1d5SJason Wang {
1279fc72d1d5SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
1280fc72d1d5SJason Wang 	struct tun_file *tfile;
1281fc72d1d5SJason Wang 	u32 numqueues;
1282735fc405SJesper Dangaard Brouer 	int drops = 0;
1283735fc405SJesper Dangaard Brouer 	int cnt = n;
1284735fc405SJesper Dangaard Brouer 	int i;
1285fc72d1d5SJason Wang 
12860c9d917bSJesper Dangaard Brouer 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
128742b33468SJesper Dangaard Brouer 		return -EINVAL;
128842b33468SJesper Dangaard Brouer 
1289fc72d1d5SJason Wang 	rcu_read_lock();
1290fc72d1d5SJason Wang 
1291fc72d1d5SJason Wang 	numqueues = READ_ONCE(tun->numqueues);
1292fc72d1d5SJason Wang 	if (!numqueues) {
1293735fc405SJesper Dangaard Brouer 		rcu_read_unlock();
1294735fc405SJesper Dangaard Brouer 		return -ENXIO; /* Caller will free/return all frames */
1295fc72d1d5SJason Wang 	}
1296fc72d1d5SJason Wang 
1297fc72d1d5SJason Wang 	tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1298fc72d1d5SJason Wang 					    numqueues]);
1299735fc405SJesper Dangaard Brouer 
1300735fc405SJesper Dangaard Brouer 	spin_lock(&tfile->tx_ring.producer_lock);
1301735fc405SJesper Dangaard Brouer 	for (i = 0; i < n; i++) {
1302735fc405SJesper Dangaard Brouer 		struct xdp_frame *xdp = frames[i];
1303fc72d1d5SJason Wang 		/* Encode the XDP flag into lowest bit for consumer to differ
1304fc72d1d5SJason Wang 		 * XDP buffer from sk_buff.
1305fc72d1d5SJason Wang 		 */
1306735fc405SJesper Dangaard Brouer 		void *frame = tun_xdp_to_ptr(xdp);
1307fc72d1d5SJason Wang 
1308735fc405SJesper Dangaard Brouer 		if (__ptr_ring_produce(&tfile->tx_ring, frame)) {
1309735fc405SJesper Dangaard Brouer 			this_cpu_inc(tun->pcpu_stats->tx_dropped);
1310735fc405SJesper Dangaard Brouer 			xdp_return_frame_rx_napi(xdp);
1311735fc405SJesper Dangaard Brouer 			drops++;
1312735fc405SJesper Dangaard Brouer 		}
1313735fc405SJesper Dangaard Brouer 	}
1314735fc405SJesper Dangaard Brouer 	spin_unlock(&tfile->tx_ring.producer_lock);
1315735fc405SJesper Dangaard Brouer 
13160c9d917bSJesper Dangaard Brouer 	if (flags & XDP_XMIT_FLUSH)
13170c9d917bSJesper Dangaard Brouer 		__tun_xdp_flush_tfile(tfile);
13180c9d917bSJesper Dangaard Brouer 
1319fc72d1d5SJason Wang 	rcu_read_unlock();
1320735fc405SJesper Dangaard Brouer 	return cnt - drops;
1321fc72d1d5SJason Wang }
1322fc72d1d5SJason Wang 
132344fa2dbdSJesper Dangaard Brouer static int tun_xdp_tx(struct net_device *dev, struct xdp_buff *xdp)
132444fa2dbdSJesper Dangaard Brouer {
132544fa2dbdSJesper Dangaard Brouer 	struct xdp_frame *frame = convert_to_xdp_frame(xdp);
132644fa2dbdSJesper Dangaard Brouer 
132744fa2dbdSJesper Dangaard Brouer 	if (unlikely(!frame))
132844fa2dbdSJesper Dangaard Brouer 		return -EOVERFLOW;
132944fa2dbdSJesper Dangaard Brouer 
133042421a56SJesper Dangaard Brouer 	return tun_xdp_xmit(dev, 1, &frame, XDP_XMIT_FLUSH);
1331fc72d1d5SJason Wang }
1332fc72d1d5SJason Wang 
1333758e43b7SStephen Hemminger static const struct net_device_ops tap_netdev_ops = {
1334c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
1335758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
1336758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
133700829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
133888255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
1339afc4b13dSJiri Pirko 	.ndo_set_rx_mode	= tun_net_mclist,
1340758e43b7SStephen Hemminger 	.ndo_set_mac_address	= eth_mac_addr,
1341758e43b7SStephen Hemminger 	.ndo_validate_addr	= eth_validate_addr,
1342c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
13435e52796aSToshiaki Makita 	.ndo_features_check	= passthru_features_check,
1344eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
1345608b9977SPaolo Abeni 	.ndo_get_stats64	= tun_net_get_stats64,
1346f4e63525SJakub Kicinski 	.ndo_bpf		= tun_xdp,
1347fc72d1d5SJason Wang 	.ndo_xdp_xmit		= tun_xdp_xmit,
1348758e43b7SStephen Hemminger };
1349758e43b7SStephen Hemminger 
1350944a1376SPavel Emelyanov static void tun_flow_init(struct tun_struct *tun)
135196442e42SJason Wang {
135296442e42SJason Wang 	int i;
135396442e42SJason Wang 
135496442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
135596442e42SJason Wang 		INIT_HLIST_HEAD(&tun->flows[i]);
135696442e42SJason Wang 
135796442e42SJason Wang 	tun->ageing_time = TUN_FLOW_EXPIRE;
1358e99e88a9SKees Cook 	timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1359e99e88a9SKees Cook 	mod_timer(&tun->flow_gc_timer,
1360e99e88a9SKees Cook 		  round_jiffies_up(jiffies + tun->ageing_time));
136196442e42SJason Wang }
136296442e42SJason Wang 
136396442e42SJason Wang static void tun_flow_uninit(struct tun_struct *tun)
136496442e42SJason Wang {
136596442e42SJason Wang 	del_timer_sync(&tun->flow_gc_timer);
136696442e42SJason Wang 	tun_flow_flush(tun);
136796442e42SJason Wang }
136896442e42SJason Wang 
136991572088SJarod Wilson #define MIN_MTU 68
137091572088SJarod Wilson #define MAX_MTU 65535
137191572088SJarod Wilson 
13721da177e4SLinus Torvalds /* Initialize net device. */
13731da177e4SLinus Torvalds static void tun_net_init(struct net_device *dev)
13741da177e4SLinus Torvalds {
13751da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
13761da177e4SLinus Torvalds 
13771da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
137840630b82SMichael S. Tsirkin 	case IFF_TUN:
1379758e43b7SStephen Hemminger 		dev->netdev_ops = &tun_netdev_ops;
1380758e43b7SStephen Hemminger 
13811da177e4SLinus Torvalds 		/* Point-to-Point TUN Device */
13821da177e4SLinus Torvalds 		dev->hard_header_len = 0;
13831da177e4SLinus Torvalds 		dev->addr_len = 0;
13841da177e4SLinus Torvalds 		dev->mtu = 1500;
13851da177e4SLinus Torvalds 
13861da177e4SLinus Torvalds 		/* Zero header length */
13871da177e4SLinus Torvalds 		dev->type = ARPHRD_NONE;
13881da177e4SLinus Torvalds 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
13891da177e4SLinus Torvalds 		break;
13901da177e4SLinus Torvalds 
139140630b82SMichael S. Tsirkin 	case IFF_TAP:
13927a0a9608SKusanagi Kouichi 		dev->netdev_ops = &tap_netdev_ops;
13931da177e4SLinus Torvalds 		/* Ethernet TAP Device */
13941da177e4SLinus Torvalds 		ether_setup(dev);
1395550fd08cSNeil Horman 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1396a676847bSstephen hemminger 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
139736226a8dSBrian Braunstein 
1398f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
139936226a8dSBrian Braunstein 
14001da177e4SLinus Torvalds 		break;
14011da177e4SLinus Torvalds 	}
140291572088SJarod Wilson 
140391572088SJarod Wilson 	dev->min_mtu = MIN_MTU;
140491572088SJarod Wilson 	dev->max_mtu = MAX_MTU - dev->hard_header_len;
14051da177e4SLinus Torvalds }
14061da177e4SLinus Torvalds 
14072f3ab622SJason Wang static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
14082f3ab622SJason Wang {
14092f3ab622SJason Wang 	struct sock *sk = tfile->socket.sk;
14102f3ab622SJason Wang 
14112f3ab622SJason Wang 	return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
14122f3ab622SJason Wang }
14132f3ab622SJason Wang 
14141da177e4SLinus Torvalds /* Character device part */
14151da177e4SLinus Torvalds 
14161da177e4SLinus Torvalds /* Poll */
1417afc9a42bSAl Viro static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
14181da177e4SLinus Torvalds {
1419b2430de3SEric W. Biederman 	struct tun_file *tfile = file->private_data;
14209484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
14213c8a9c63SMariusz Kozlowski 	struct sock *sk;
1422afc9a42bSAl Viro 	__poll_t mask = 0;
14231da177e4SLinus Torvalds 
14241da177e4SLinus Torvalds 	if (!tun)
1425a9a08845SLinus Torvalds 		return EPOLLERR;
14261da177e4SLinus Torvalds 
142754f968d6SJason Wang 	sk = tfile->socket.sk;
14283c8a9c63SMariusz Kozlowski 
14296b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
14301da177e4SLinus Torvalds 
14319e641bdcSXi Wang 	poll_wait(file, sk_sleep(sk), wait);
14321da177e4SLinus Torvalds 
14335990a305SJason Wang 	if (!ptr_ring_empty(&tfile->tx_ring))
1434a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
14351da177e4SLinus Torvalds 
14362f3ab622SJason Wang 	/* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
14372f3ab622SJason Wang 	 * guarantee EPOLLOUT to be raised by either here or
14382f3ab622SJason Wang 	 * tun_sock_write_space(). Then process could get notification
14392f3ab622SJason Wang 	 * after it writes to a down device and meets -EIO.
14402f3ab622SJason Wang 	 */
14412f3ab622SJason Wang 	if (tun_sock_writeable(tun, tfile) ||
14429cd3e072SEric Dumazet 	    (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
14432f3ab622SJason Wang 	     tun_sock_writeable(tun, tfile)))
1444a9a08845SLinus Torvalds 		mask |= EPOLLOUT | EPOLLWRNORM;
144533dccbb0SHerbert Xu 
1446c70f1829SEric W. Biederman 	if (tun->dev->reg_state != NETREG_REGISTERED)
1447a9a08845SLinus Torvalds 		mask = EPOLLERR;
1448c70f1829SEric W. Biederman 
1449631ab46bSEric W. Biederman 	tun_put(tun);
14501da177e4SLinus Torvalds 	return mask;
14511da177e4SLinus Torvalds }
14521da177e4SLinus Torvalds 
145390e33d45SPetar Penkov static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
145490e33d45SPetar Penkov 					    size_t len,
145590e33d45SPetar Penkov 					    const struct iov_iter *it)
145690e33d45SPetar Penkov {
145790e33d45SPetar Penkov 	struct sk_buff *skb;
145890e33d45SPetar Penkov 	size_t linear;
145990e33d45SPetar Penkov 	int err;
146090e33d45SPetar Penkov 	int i;
146190e33d45SPetar Penkov 
146290e33d45SPetar Penkov 	if (it->nr_segs > MAX_SKB_FRAGS + 1)
146390e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
146490e33d45SPetar Penkov 
146590e33d45SPetar Penkov 	local_bh_disable();
146690e33d45SPetar Penkov 	skb = napi_get_frags(&tfile->napi);
146790e33d45SPetar Penkov 	local_bh_enable();
146890e33d45SPetar Penkov 	if (!skb)
146990e33d45SPetar Penkov 		return ERR_PTR(-ENOMEM);
147090e33d45SPetar Penkov 
147190e33d45SPetar Penkov 	linear = iov_iter_single_seg_count(it);
147290e33d45SPetar Penkov 	err = __skb_grow(skb, linear);
147390e33d45SPetar Penkov 	if (err)
147490e33d45SPetar Penkov 		goto free;
147590e33d45SPetar Penkov 
147690e33d45SPetar Penkov 	skb->len = len;
147790e33d45SPetar Penkov 	skb->data_len = len - linear;
147890e33d45SPetar Penkov 	skb->truesize += skb->data_len;
147990e33d45SPetar Penkov 
148090e33d45SPetar Penkov 	for (i = 1; i < it->nr_segs; i++) {
148190e33d45SPetar Penkov 		size_t fragsz = it->iov[i].iov_len;
1482*aa6daacaSEric Dumazet 		struct page *page;
1483*aa6daacaSEric Dumazet 		void *frag;
148490e33d45SPetar Penkov 
148590e33d45SPetar Penkov 		if (fragsz == 0 || fragsz > PAGE_SIZE) {
148690e33d45SPetar Penkov 			err = -EINVAL;
148790e33d45SPetar Penkov 			goto free;
148890e33d45SPetar Penkov 		}
1489*aa6daacaSEric Dumazet 		frag = netdev_alloc_frag(fragsz);
1490*aa6daacaSEric Dumazet 		if (!frag) {
149190e33d45SPetar Penkov 			err = -ENOMEM;
149290e33d45SPetar Penkov 			goto free;
149390e33d45SPetar Penkov 		}
1494*aa6daacaSEric Dumazet 		page = virt_to_head_page(frag);
1495*aa6daacaSEric Dumazet 		skb_fill_page_desc(skb, i - 1, page,
1496*aa6daacaSEric Dumazet 				   frag - page_address(page), fragsz);
149790e33d45SPetar Penkov 	}
149890e33d45SPetar Penkov 
149990e33d45SPetar Penkov 	return skb;
150090e33d45SPetar Penkov free:
150190e33d45SPetar Penkov 	/* frees skb and all frags allocated with napi_alloc_frag() */
150290e33d45SPetar Penkov 	napi_free_frags(&tfile->napi);
150390e33d45SPetar Penkov 	return ERR_PTR(err);
150490e33d45SPetar Penkov }
150590e33d45SPetar Penkov 
1506f42157cbSRusty Russell /* prepad is the amount to reserve at front.  len is length after that.
1507f42157cbSRusty Russell  * linear is a hint as to how much to copy (usually headers). */
150854f968d6SJason Wang static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
150933dccbb0SHerbert Xu 				     size_t prepad, size_t len,
151033dccbb0SHerbert Xu 				     size_t linear, int noblock)
1511f42157cbSRusty Russell {
151254f968d6SJason Wang 	struct sock *sk = tfile->socket.sk;
1513f42157cbSRusty Russell 	struct sk_buff *skb;
151433dccbb0SHerbert Xu 	int err;
1515f42157cbSRusty Russell 
1516f42157cbSRusty Russell 	/* Under a page?  Don't bother with paged skb. */
15170eca93bcSHerbert Xu 	if (prepad + len < PAGE_SIZE || !linear)
151833dccbb0SHerbert Xu 		linear = len;
1519f42157cbSRusty Russell 
152033dccbb0SHerbert Xu 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
152128d64271SEric Dumazet 				   &err, 0);
1522f42157cbSRusty Russell 	if (!skb)
152333dccbb0SHerbert Xu 		return ERR_PTR(err);
1524f42157cbSRusty Russell 
1525f42157cbSRusty Russell 	skb_reserve(skb, prepad);
1526f42157cbSRusty Russell 	skb_put(skb, linear);
152733dccbb0SHerbert Xu 	skb->data_len = len - linear;
152833dccbb0SHerbert Xu 	skb->len += len - linear;
1529f42157cbSRusty Russell 
1530f42157cbSRusty Russell 	return skb;
1531f42157cbSRusty Russell }
1532f42157cbSRusty Russell 
15335503fcecSJason Wang static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
15345503fcecSJason Wang 			   struct sk_buff *skb, int more)
15355503fcecSJason Wang {
15365503fcecSJason Wang 	struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
15375503fcecSJason Wang 	struct sk_buff_head process_queue;
15385503fcecSJason Wang 	u32 rx_batched = tun->rx_batched;
15395503fcecSJason Wang 	bool rcv = false;
15405503fcecSJason Wang 
15415503fcecSJason Wang 	if (!rx_batched || (!more && skb_queue_empty(queue))) {
15425503fcecSJason Wang 		local_bh_disable();
15435503fcecSJason Wang 		netif_receive_skb(skb);
15445503fcecSJason Wang 		local_bh_enable();
15455503fcecSJason Wang 		return;
15465503fcecSJason Wang 	}
15475503fcecSJason Wang 
15485503fcecSJason Wang 	spin_lock(&queue->lock);
15495503fcecSJason Wang 	if (!more || skb_queue_len(queue) == rx_batched) {
15505503fcecSJason Wang 		__skb_queue_head_init(&process_queue);
15515503fcecSJason Wang 		skb_queue_splice_tail_init(queue, &process_queue);
15525503fcecSJason Wang 		rcv = true;
15535503fcecSJason Wang 	} else {
15545503fcecSJason Wang 		__skb_queue_tail(queue, skb);
15555503fcecSJason Wang 	}
15565503fcecSJason Wang 	spin_unlock(&queue->lock);
15575503fcecSJason Wang 
15585503fcecSJason Wang 	if (rcv) {
15595503fcecSJason Wang 		struct sk_buff *nskb;
15605503fcecSJason Wang 
15615503fcecSJason Wang 		local_bh_disable();
15625503fcecSJason Wang 		while ((nskb = __skb_dequeue(&process_queue)))
15635503fcecSJason Wang 			netif_receive_skb(nskb);
15645503fcecSJason Wang 		netif_receive_skb(skb);
15655503fcecSJason Wang 		local_bh_enable();
15665503fcecSJason Wang 	}
15675503fcecSJason Wang }
15685503fcecSJason Wang 
156966ccbc9cSJason Wang static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
157066ccbc9cSJason Wang 			      int len, int noblock, bool zerocopy)
157166ccbc9cSJason Wang {
157266ccbc9cSJason Wang 	if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
157366ccbc9cSJason Wang 		return false;
157466ccbc9cSJason Wang 
157566ccbc9cSJason Wang 	if (tfile->socket.sk->sk_sndbuf != INT_MAX)
157666ccbc9cSJason Wang 		return false;
157766ccbc9cSJason Wang 
157866ccbc9cSJason Wang 	if (!noblock)
157966ccbc9cSJason Wang 		return false;
158066ccbc9cSJason Wang 
158166ccbc9cSJason Wang 	if (zerocopy)
158266ccbc9cSJason Wang 		return false;
158366ccbc9cSJason Wang 
158466ccbc9cSJason Wang 	if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
158566ccbc9cSJason Wang 	    SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
158666ccbc9cSJason Wang 		return false;
158766ccbc9cSJason Wang 
158866ccbc9cSJason Wang 	return true;
158966ccbc9cSJason Wang }
159066ccbc9cSJason Wang 
1591ac1f1f6cSJason Wang static struct sk_buff *__tun_build_skb(struct page_frag *alloc_frag, char *buf,
15928ae1aff0SJason Wang 				       int buflen, int len, int pad)
1593ac1f1f6cSJason Wang {
1594ac1f1f6cSJason Wang 	struct sk_buff *skb = build_skb(buf, buflen);
1595ac1f1f6cSJason Wang 
1596ac1f1f6cSJason Wang 	if (!skb)
1597ac1f1f6cSJason Wang 		return ERR_PTR(-ENOMEM);
1598ac1f1f6cSJason Wang 
15998ae1aff0SJason Wang 	skb_reserve(skb, pad);
1600ac1f1f6cSJason Wang 	skb_put(skb, len);
1601ac1f1f6cSJason Wang 
1602ac1f1f6cSJason Wang 	get_page(alloc_frag->page);
1603ac1f1f6cSJason Wang 	alloc_frag->offset += buflen;
1604ac1f1f6cSJason Wang 
1605ac1f1f6cSJason Wang 	return skb;
1606ac1f1f6cSJason Wang }
1607ac1f1f6cSJason Wang 
16088ae1aff0SJason Wang static int tun_xdp_act(struct tun_struct *tun, struct bpf_prog *xdp_prog,
16098ae1aff0SJason Wang 		       struct xdp_buff *xdp, u32 act)
16108ae1aff0SJason Wang {
16118ae1aff0SJason Wang 	int err;
16128ae1aff0SJason Wang 
16138ae1aff0SJason Wang 	switch (act) {
16148ae1aff0SJason Wang 	case XDP_REDIRECT:
16158ae1aff0SJason Wang 		err = xdp_do_redirect(tun->dev, xdp, xdp_prog);
16168ae1aff0SJason Wang 		if (err)
16178ae1aff0SJason Wang 			return err;
16188ae1aff0SJason Wang 		break;
16198ae1aff0SJason Wang 	case XDP_TX:
16208ae1aff0SJason Wang 		err = tun_xdp_tx(tun->dev, xdp);
16218ae1aff0SJason Wang 		if (err < 0)
16228ae1aff0SJason Wang 			return err;
16238ae1aff0SJason Wang 		break;
16248ae1aff0SJason Wang 	case XDP_PASS:
16258ae1aff0SJason Wang 		break;
16268ae1aff0SJason Wang 	default:
16278ae1aff0SJason Wang 		bpf_warn_invalid_xdp_action(act);
16288ae1aff0SJason Wang 		/* fall through */
16298ae1aff0SJason Wang 	case XDP_ABORTED:
16308ae1aff0SJason Wang 		trace_xdp_exception(tun->dev, xdp_prog, act);
16318ae1aff0SJason Wang 		/* fall through */
16328ae1aff0SJason Wang 	case XDP_DROP:
16338ae1aff0SJason Wang 		this_cpu_inc(tun->pcpu_stats->rx_dropped);
16348ae1aff0SJason Wang 		break;
16358ae1aff0SJason Wang 	}
16368ae1aff0SJason Wang 
16378ae1aff0SJason Wang 	return act;
16388ae1aff0SJason Wang }
16398ae1aff0SJason Wang 
1640761876c8SJason Wang static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1641761876c8SJason Wang 				     struct tun_file *tfile,
164266ccbc9cSJason Wang 				     struct iov_iter *from,
1643761876c8SJason Wang 				     struct virtio_net_hdr *hdr,
16441cfe6e93SJason Wang 				     int len, int *skb_xdp)
164566ccbc9cSJason Wang {
16460bbd7dadSEric Dumazet 	struct page_frag *alloc_frag = &current->task_frag;
1647761876c8SJason Wang 	struct bpf_prog *xdp_prog;
16487df13219SJason Wang 	int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
164966ccbc9cSJason Wang 	char *buf;
165066ccbc9cSJason Wang 	size_t copied;
16518ae1aff0SJason Wang 	int pad = TUN_RX_PAD;
16528ae1aff0SJason Wang 	int err = 0;
16537df13219SJason Wang 
16547df13219SJason Wang 	rcu_read_lock();
16557df13219SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
16567df13219SJason Wang 	if (xdp_prog)
16574f23aff8SJason Wang 		pad += XDP_PACKET_HEADROOM;
16587df13219SJason Wang 	buflen += SKB_DATA_ALIGN(len + pad);
16597df13219SJason Wang 	rcu_read_unlock();
166066ccbc9cSJason Wang 
166163b9ab65SJason Wang 	alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
166266ccbc9cSJason Wang 	if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
166366ccbc9cSJason Wang 		return ERR_PTR(-ENOMEM);
166466ccbc9cSJason Wang 
166566ccbc9cSJason Wang 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
166666ccbc9cSJason Wang 	copied = copy_page_from_iter(alloc_frag->page,
16677df13219SJason Wang 				     alloc_frag->offset + pad,
166866ccbc9cSJason Wang 				     len, from);
166966ccbc9cSJason Wang 	if (copied != len)
167066ccbc9cSJason Wang 		return ERR_PTR(-EFAULT);
167166ccbc9cSJason Wang 
16727df13219SJason Wang 	/* There's a small window that XDP may be set after the check
16737df13219SJason Wang 	 * of xdp_prog above, this should be rare and for simplicity
16747df13219SJason Wang 	 * we do XDP on skb in case the headroom is not enough.
16757df13219SJason Wang 	 */
1676ac1f1f6cSJason Wang 	if (hdr->gso_type || !xdp_prog) {
16771cfe6e93SJason Wang 		*skb_xdp = 1;
16788ae1aff0SJason Wang 		return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
1679ac1f1f6cSJason Wang 	}
1680ac1f1f6cSJason Wang 
16811cfe6e93SJason Wang 	*skb_xdp = 0;
168266ccbc9cSJason Wang 
16836547e387SToshiaki Makita 	local_bh_disable();
1684761876c8SJason Wang 	rcu_read_lock();
1685761876c8SJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
16868ae1aff0SJason Wang 	if (xdp_prog) {
1687761876c8SJason Wang 		struct xdp_buff xdp;
1688761876c8SJason Wang 		u32 act;
1689761876c8SJason Wang 
1690761876c8SJason Wang 		xdp.data_hard_start = buf;
16917df13219SJason Wang 		xdp.data = buf + pad;
1692de8f3a83SDaniel Borkmann 		xdp_set_data_meta_invalid(&xdp);
1693761876c8SJason Wang 		xdp.data_end = xdp.data + len;
16948bf5c4eeSJesper Dangaard Brouer 		xdp.rxq = &tfile->xdp_rxq;
1695761876c8SJason Wang 
16968ae1aff0SJason Wang 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
16978ae1aff0SJason Wang 		if (act == XDP_REDIRECT || act == XDP_TX) {
1698761876c8SJason Wang 			get_page(alloc_frag->page);
1699761876c8SJason Wang 			alloc_frag->offset += buflen;
1700761876c8SJason Wang 		}
17018ae1aff0SJason Wang 		err = tun_xdp_act(tun, xdp_prog, &xdp, act);
17028ae1aff0SJason Wang 		if (err < 0)
17038ae1aff0SJason Wang 			goto err_xdp;
17041a097910SJason Wang 		if (err == XDP_REDIRECT)
17051a097910SJason Wang 			xdp_do_flush_map();
17068ae1aff0SJason Wang 		if (err != XDP_PASS)
17078ae1aff0SJason Wang 			goto out;
17088ae1aff0SJason Wang 
17098ae1aff0SJason Wang 		pad = xdp.data - xdp.data_hard_start;
17108ae1aff0SJason Wang 		len = xdp.data_end - xdp.data;
1711761876c8SJason Wang 	}
1712761876c8SJason Wang 	rcu_read_unlock();
17136547e387SToshiaki Makita 	local_bh_enable();
1714291aeb2bSJason Wang 
17158ae1aff0SJason Wang 	return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
1716761876c8SJason Wang 
17178ae1aff0SJason Wang err_xdp:
1718761876c8SJason Wang 	put_page(alloc_frag->page);
1719f7053b6cSJason Wang out:
1720761876c8SJason Wang 	rcu_read_unlock();
17216547e387SToshiaki Makita 	local_bh_enable();
1722761876c8SJason Wang 	return NULL;
172366ccbc9cSJason Wang }
172466ccbc9cSJason Wang 
17251da177e4SLinus Torvalds /* Get packet from user space buffer */
172654f968d6SJason Wang static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1727f5ff53b4SAl Viro 			    void *msg_control, struct iov_iter *from,
17285503fcecSJason Wang 			    int noblock, bool more)
17291da177e4SLinus Torvalds {
173009640e63SHarvey Harrison 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
17311da177e4SLinus Torvalds 	struct sk_buff *skb;
1732f5ff53b4SAl Viro 	size_t total_len = iov_iter_count(from);
1733eaea34b2SPaolo Abeni 	size_t len = total_len, align = tun->align, linear;
1734f43798c2SRusty Russell 	struct virtio_net_hdr gso = { 0 };
1735608b9977SPaolo Abeni 	struct tun_pcpu_stats *stats;
173696f8d9ecSJason Wang 	int good_linear;
17370690899bSMichael S. Tsirkin 	int copylen;
17380690899bSMichael S. Tsirkin 	bool zerocopy = false;
17390690899bSMichael S. Tsirkin 	int err;
174096f84061SJason Wang 	u32 rxhash = 0;
17411cfe6e93SJason Wang 	int skb_xdp = 1;
1742af3fb24eSEric Dumazet 	bool frags = tun_napi_frags_enabled(tfile);
17431da177e4SLinus Torvalds 
17441bd4978aSEric Dumazet 	if (!(tun->dev->flags & IFF_UP))
17451bd4978aSEric Dumazet 		return -EIO;
17461bd4978aSEric Dumazet 
174740630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
174815718ea0SDan Carpenter 		if (len < sizeof(pi))
17491da177e4SLinus Torvalds 			return -EINVAL;
175015718ea0SDan Carpenter 		len -= sizeof(pi);
17511da177e4SLinus Torvalds 
1752cbbd26b8SAl Viro 		if (!copy_from_iter_full(&pi, sizeof(pi), from))
17531da177e4SLinus Torvalds 			return -EFAULT;
17541da177e4SLinus Torvalds 	}
17551da177e4SLinus Torvalds 
175640630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR) {
1757e1edab87SWillem de Bruijn 		int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1758e1edab87SWillem de Bruijn 
1759e1edab87SWillem de Bruijn 		if (len < vnet_hdr_sz)
1760f43798c2SRusty Russell 			return -EINVAL;
1761e1edab87SWillem de Bruijn 		len -= vnet_hdr_sz;
1762f43798c2SRusty Russell 
1763cbbd26b8SAl Viro 		if (!copy_from_iter_full(&gso, sizeof(gso), from))
1764f43798c2SRusty Russell 			return -EFAULT;
1765f43798c2SRusty Russell 
17664909122fSHerbert Xu 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
176756f0dcc5SMichael S. Tsirkin 		    tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
176856f0dcc5SMichael S. Tsirkin 			gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
17694909122fSHerbert Xu 
177056f0dcc5SMichael S. Tsirkin 		if (tun16_to_cpu(tun, gso.hdr_len) > len)
1771f43798c2SRusty Russell 			return -EINVAL;
1772e1edab87SWillem de Bruijn 		iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1773f43798c2SRusty Russell 	}
1774f43798c2SRusty Russell 
177540630b82SMichael S. Tsirkin 	if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1776a504b86eSstephen hemminger 		align += NET_IP_ALIGN;
17770eca93bcSHerbert Xu 		if (unlikely(len < ETH_HLEN ||
177856f0dcc5SMichael S. Tsirkin 			     (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1779e01bf1c8SRusty Russell 			return -EINVAL;
1780e01bf1c8SRusty Russell 	}
17811da177e4SLinus Torvalds 
178296f8d9ecSJason Wang 	good_linear = SKB_MAX_HEAD(align);
178396f8d9ecSJason Wang 
178488529176SJason Wang 	if (msg_control) {
1785f5ff53b4SAl Viro 		struct iov_iter i = *from;
1786f5ff53b4SAl Viro 
178788529176SJason Wang 		/* There are 256 bytes to be copied in skb, so there is
178888529176SJason Wang 		 * enough room for skb expand head in case it is used.
17890690899bSMichael S. Tsirkin 		 * The rest of the buffer is mapped from userspace.
17900690899bSMichael S. Tsirkin 		 */
179156f0dcc5SMichael S. Tsirkin 		copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
179296f8d9ecSJason Wang 		if (copylen > good_linear)
179396f8d9ecSJason Wang 			copylen = good_linear;
17943dd5c330SJason Wang 		linear = copylen;
1795f5ff53b4SAl Viro 		iov_iter_advance(&i, copylen);
1796f5ff53b4SAl Viro 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
179788529176SJason Wang 			zerocopy = true;
179888529176SJason Wang 	}
179988529176SJason Wang 
180090e33d45SPetar Penkov 	if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
18011cfe6e93SJason Wang 		/* For the packet that is not easy to be processed
18021cfe6e93SJason Wang 		 * (e.g gso or jumbo packet), we will do it at after
18031cfe6e93SJason Wang 		 * skb was created with generic XDP routine.
18041cfe6e93SJason Wang 		 */
18051cfe6e93SJason Wang 		skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
180666ccbc9cSJason Wang 		if (IS_ERR(skb)) {
180766ccbc9cSJason Wang 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
180866ccbc9cSJason Wang 			return PTR_ERR(skb);
180966ccbc9cSJason Wang 		}
1810761876c8SJason Wang 		if (!skb)
1811761876c8SJason Wang 			return total_len;
181266ccbc9cSJason Wang 	} else {
181388529176SJason Wang 		if (!zerocopy) {
18140690899bSMichael S. Tsirkin 			copylen = len;
181556f0dcc5SMichael S. Tsirkin 			if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
181696f8d9ecSJason Wang 				linear = good_linear;
181796f8d9ecSJason Wang 			else
181856f0dcc5SMichael S. Tsirkin 				linear = tun16_to_cpu(tun, gso.hdr_len);
18193dd5c330SJason Wang 		}
18200690899bSMichael S. Tsirkin 
182190e33d45SPetar Penkov 		if (frags) {
182290e33d45SPetar Penkov 			mutex_lock(&tfile->napi_mutex);
182390e33d45SPetar Penkov 			skb = tun_napi_alloc_frags(tfile, copylen, from);
182490e33d45SPetar Penkov 			/* tun_napi_alloc_frags() enforces a layout for the skb.
182590e33d45SPetar Penkov 			 * If zerocopy is enabled, then this layout will be
182690e33d45SPetar Penkov 			 * overwritten by zerocopy_sg_from_iter().
182790e33d45SPetar Penkov 			 */
182890e33d45SPetar Penkov 			zerocopy = false;
182990e33d45SPetar Penkov 		} else {
183090e33d45SPetar Penkov 			skb = tun_alloc_skb(tfile, align, copylen, linear,
183190e33d45SPetar Penkov 					    noblock);
183290e33d45SPetar Penkov 		}
183390e33d45SPetar Penkov 
183433dccbb0SHerbert Xu 		if (IS_ERR(skb)) {
183533dccbb0SHerbert Xu 			if (PTR_ERR(skb) != -EAGAIN)
1836608b9977SPaolo Abeni 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
183790e33d45SPetar Penkov 			if (frags)
183890e33d45SPetar Penkov 				mutex_unlock(&tfile->napi_mutex);
183933dccbb0SHerbert Xu 			return PTR_ERR(skb);
18401da177e4SLinus Torvalds 		}
18411da177e4SLinus Torvalds 
18420690899bSMichael S. Tsirkin 		if (zerocopy)
1843f5ff53b4SAl Viro 			err = zerocopy_sg_from_iter(skb, from);
1844af1cc7a2SJason Wang 		else
1845f5ff53b4SAl Viro 			err = skb_copy_datagram_from_iter(skb, 0, from, len);
18460690899bSMichael S. Tsirkin 
18470690899bSMichael S. Tsirkin 		if (err) {
1848608b9977SPaolo Abeni 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
18498f22757eSDave Jones 			kfree_skb(skb);
185090e33d45SPetar Penkov 			if (frags) {
185190e33d45SPetar Penkov 				tfile->napi.skb = NULL;
185290e33d45SPetar Penkov 				mutex_unlock(&tfile->napi_mutex);
185390e33d45SPetar Penkov 			}
185490e33d45SPetar Penkov 
18551da177e4SLinus Torvalds 			return -EFAULT;
18568f22757eSDave Jones 		}
185766ccbc9cSJason Wang 	}
18581da177e4SLinus Torvalds 
18593e9e40e7SJarno Rajahalme 	if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1860df10db98SPaolo Abeni 		this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1861df10db98SPaolo Abeni 		kfree_skb(skb);
186290e33d45SPetar Penkov 		if (frags) {
186390e33d45SPetar Penkov 			tfile->napi.skb = NULL;
186490e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
186590e33d45SPetar Penkov 		}
186690e33d45SPetar Penkov 
1867df10db98SPaolo Abeni 		return -EINVAL;
1868df10db98SPaolo Abeni 	}
1869df10db98SPaolo Abeni 
18701da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
187140630b82SMichael S. Tsirkin 	case IFF_TUN:
187240630b82SMichael S. Tsirkin 		if (tun->flags & IFF_NO_PI) {
18732580c4c1SAlexander Potapenko 			u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
18742580c4c1SAlexander Potapenko 
18752580c4c1SAlexander Potapenko 			switch (ip_version) {
18762580c4c1SAlexander Potapenko 			case 4:
1877f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IP);
1878f09f7ee2SAng Way Chuang 				break;
18792580c4c1SAlexander Potapenko 			case 6:
1880f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IPV6);
1881f09f7ee2SAng Way Chuang 				break;
1882f09f7ee2SAng Way Chuang 			default:
1883608b9977SPaolo Abeni 				this_cpu_inc(tun->pcpu_stats->rx_dropped);
1884f09f7ee2SAng Way Chuang 				kfree_skb(skb);
1885f09f7ee2SAng Way Chuang 				return -EINVAL;
1886f09f7ee2SAng Way Chuang 			}
1887f09f7ee2SAng Way Chuang 		}
1888f09f7ee2SAng Way Chuang 
1889459a98edSArnaldo Carvalho de Melo 		skb_reset_mac_header(skb);
18901da177e4SLinus Torvalds 		skb->protocol = pi.proto;
18914c13eb66SArnaldo Carvalho de Melo 		skb->dev = tun->dev;
18921da177e4SLinus Torvalds 		break;
189340630b82SMichael S. Tsirkin 	case IFF_TAP:
189490e33d45SPetar Penkov 		if (!frags)
18951da177e4SLinus Torvalds 			skb->protocol = eth_type_trans(skb, tun->dev);
18961da177e4SLinus Torvalds 		break;
18976403eab1SJoe Perches 	}
18981da177e4SLinus Torvalds 
18990690899bSMichael S. Tsirkin 	/* copy skb_ubuf_info for callback when skb has no error */
19000690899bSMichael S. Tsirkin 	if (zerocopy) {
19010690899bSMichael S. Tsirkin 		skb_shinfo(skb)->destructor_arg = msg_control;
19020690899bSMichael S. Tsirkin 		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1903c9af6db4SPravin B Shelar 		skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1904af1cc7a2SJason Wang 	} else if (msg_control) {
1905af1cc7a2SJason Wang 		struct ubuf_info *uarg = msg_control;
1906af1cc7a2SJason Wang 		uarg->callback(uarg, false);
19070690899bSMichael S. Tsirkin 	}
19080690899bSMichael S. Tsirkin 
190972f65107SVlad Yasevich 	skb_reset_network_header(skb);
191040893fd0SJason Wang 	skb_probe_transport_header(skb, 0);
191138502af7SJason Wang 
19121cfe6e93SJason Wang 	if (skb_xdp) {
1913761876c8SJason Wang 		struct bpf_prog *xdp_prog;
1914761876c8SJason Wang 		int ret;
1915761876c8SJason Wang 
19166547e387SToshiaki Makita 		local_bh_disable();
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();
19236547e387SToshiaki Makita 				local_bh_enable();
1924761876c8SJason Wang 				return total_len;
1925761876c8SJason Wang 			}
1926761876c8SJason Wang 		}
1927761876c8SJason Wang 		rcu_read_unlock();
19286547e387SToshiaki Makita 		local_bh_enable();
1929761876c8SJason Wang 	}
1930761876c8SJason Wang 
1931cf1a1e07SPaolo Abeni 	/* Compute the costly rx hash only if needed for flow updates.
1932cf1a1e07SPaolo Abeni 	 * We may get a very small possibility of OOO during switching, not
1933cf1a1e07SPaolo Abeni 	 * worth to optimize.
1934cf1a1e07SPaolo Abeni 	 */
1935cf1a1e07SPaolo Abeni 	if (!rcu_access_pointer(tun->steering_prog) && tun->numqueues > 1 &&
1936cf1a1e07SPaolo Abeni 	    !tfile->detached)
1937feec084aSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
193894317099SPetar Penkov 
193990e33d45SPetar Penkov 	if (frags) {
194090e33d45SPetar Penkov 		/* Exercise flow dissector code path. */
194190e33d45SPetar Penkov 		u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
194290e33d45SPetar Penkov 
1943010f245bSEric Dumazet 		if (unlikely(headlen > skb_headlen(skb))) {
194490e33d45SPetar Penkov 			this_cpu_inc(tun->pcpu_stats->rx_dropped);
194590e33d45SPetar Penkov 			napi_free_frags(&tfile->napi);
194690e33d45SPetar Penkov 			mutex_unlock(&tfile->napi_mutex);
194790e33d45SPetar Penkov 			WARN_ON(1);
194890e33d45SPetar Penkov 			return -ENOMEM;
194990e33d45SPetar Penkov 		}
195090e33d45SPetar Penkov 
195190e33d45SPetar Penkov 		local_bh_disable();
195290e33d45SPetar Penkov 		napi_gro_frags(&tfile->napi);
195390e33d45SPetar Penkov 		local_bh_enable();
195490e33d45SPetar Penkov 		mutex_unlock(&tfile->napi_mutex);
1955aec72f33SEric Dumazet 	} else if (tfile->napi_enabled) {
195694317099SPetar Penkov 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
195794317099SPetar Penkov 		int queue_len;
195894317099SPetar Penkov 
195994317099SPetar Penkov 		spin_lock_bh(&queue->lock);
196094317099SPetar Penkov 		__skb_queue_tail(queue, skb);
196194317099SPetar Penkov 		queue_len = skb_queue_len(queue);
196294317099SPetar Penkov 		spin_unlock(&queue->lock);
196394317099SPetar Penkov 
196494317099SPetar Penkov 		if (!more || queue_len > NAPI_POLL_WEIGHT)
196594317099SPetar Penkov 			napi_schedule(&tfile->napi);
196694317099SPetar Penkov 
196794317099SPetar Penkov 		local_bh_enable();
196894317099SPetar Penkov 	} else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
19695503fcecSJason Wang 		tun_rx_batched(tun, tfile, skb, more);
197094317099SPetar Penkov 	} else {
19711da177e4SLinus Torvalds 		netif_rx_ni(skb);
197294317099SPetar Penkov 	}
19731da177e4SLinus Torvalds 
1974608b9977SPaolo Abeni 	stats = get_cpu_ptr(tun->pcpu_stats);
1975608b9977SPaolo Abeni 	u64_stats_update_begin(&stats->syncp);
1976608b9977SPaolo Abeni 	stats->rx_packets++;
1977608b9977SPaolo Abeni 	stats->rx_bytes += len;
1978608b9977SPaolo Abeni 	u64_stats_update_end(&stats->syncp);
1979608b9977SPaolo Abeni 	put_cpu_ptr(stats);
19801da177e4SLinus Torvalds 
198196f84061SJason Wang 	if (rxhash)
19829e85722dSJason Wang 		tun_flow_update(tun, rxhash, tfile);
198396f84061SJason Wang 
19840690899bSMichael S. Tsirkin 	return total_len;
19851da177e4SLinus Torvalds }
19861da177e4SLinus Torvalds 
1987f5ff53b4SAl Viro static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
19881da177e4SLinus Torvalds {
198933dccbb0SHerbert Xu 	struct file *file = iocb->ki_filp;
199054f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
19919484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
1992631ab46bSEric W. Biederman 	ssize_t result;
19931da177e4SLinus Torvalds 
19941da177e4SLinus Torvalds 	if (!tun)
19951da177e4SLinus Torvalds 		return -EBADFD;
19961da177e4SLinus Torvalds 
19975503fcecSJason Wang 	result = tun_get_user(tun, tfile, NULL, from,
19985503fcecSJason Wang 			      file->f_flags & O_NONBLOCK, false);
1999631ab46bSEric W. Biederman 
2000631ab46bSEric W. Biederman 	tun_put(tun);
2001631ab46bSEric W. Biederman 	return result;
20021da177e4SLinus Torvalds }
20031da177e4SLinus Torvalds 
2004fc72d1d5SJason Wang static ssize_t tun_put_user_xdp(struct tun_struct *tun,
2005fc72d1d5SJason Wang 				struct tun_file *tfile,
20061ffcbc85SJesper Dangaard Brouer 				struct xdp_frame *xdp_frame,
2007fc72d1d5SJason Wang 				struct iov_iter *iter)
2008fc72d1d5SJason Wang {
2009fc72d1d5SJason Wang 	int vnet_hdr_sz = 0;
20101ffcbc85SJesper Dangaard Brouer 	size_t size = xdp_frame->len;
2011fc72d1d5SJason Wang 	struct tun_pcpu_stats *stats;
2012fc72d1d5SJason Wang 	size_t ret;
2013fc72d1d5SJason Wang 
2014fc72d1d5SJason Wang 	if (tun->flags & IFF_VNET_HDR) {
2015fc72d1d5SJason Wang 		struct virtio_net_hdr gso = { 0 };
2016fc72d1d5SJason Wang 
2017fc72d1d5SJason Wang 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2018fc72d1d5SJason Wang 		if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
2019fc72d1d5SJason Wang 			return -EINVAL;
2020fc72d1d5SJason Wang 		if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
2021fc72d1d5SJason Wang 			     sizeof(gso)))
2022fc72d1d5SJason Wang 			return -EFAULT;
2023fc72d1d5SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2024fc72d1d5SJason Wang 	}
2025fc72d1d5SJason Wang 
20261ffcbc85SJesper Dangaard Brouer 	ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
2027fc72d1d5SJason Wang 
2028fc72d1d5SJason Wang 	stats = get_cpu_ptr(tun->pcpu_stats);
2029fc72d1d5SJason Wang 	u64_stats_update_begin(&stats->syncp);
2030fc72d1d5SJason Wang 	stats->tx_packets++;
2031fc72d1d5SJason Wang 	stats->tx_bytes += ret;
2032fc72d1d5SJason Wang 	u64_stats_update_end(&stats->syncp);
2033fc72d1d5SJason Wang 	put_cpu_ptr(tun->pcpu_stats);
2034fc72d1d5SJason Wang 
2035fc72d1d5SJason Wang 	return ret;
2036fc72d1d5SJason Wang }
2037fc72d1d5SJason Wang 
20381da177e4SLinus Torvalds /* Put packet to the user space buffer */
20396f7c156cSstephen hemminger static ssize_t tun_put_user(struct tun_struct *tun,
204054f968d6SJason Wang 			    struct tun_file *tfile,
20411da177e4SLinus Torvalds 			    struct sk_buff *skb,
2042e0b46d0eSHerbert Xu 			    struct iov_iter *iter)
20431da177e4SLinus Torvalds {
20441da177e4SLinus Torvalds 	struct tun_pi pi = { 0, skb->protocol };
2045608b9977SPaolo Abeni 	struct tun_pcpu_stats *stats;
2046e0b46d0eSHerbert Xu 	ssize_t total;
20478c847d25SJason Wang 	int vlan_offset = 0;
2048a8f9bfdfSHerbert Xu 	int vlan_hlen = 0;
20492eb783c4SHerbert Xu 	int vnet_hdr_sz = 0;
2050a8f9bfdfSHerbert Xu 
2051df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb))
2052a8f9bfdfSHerbert Xu 		vlan_hlen = VLAN_HLEN;
20531da177e4SLinus Torvalds 
205440630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR)
2055e1edab87SWillem de Bruijn 		vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
20561da177e4SLinus Torvalds 
2057e0b46d0eSHerbert Xu 	total = skb->len + vlan_hlen + vnet_hdr_sz;
2058e0b46d0eSHerbert Xu 
205940630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
2060e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < sizeof(pi))
20611da177e4SLinus Torvalds 			return -EINVAL;
20621da177e4SLinus Torvalds 
2063e0b46d0eSHerbert Xu 		total += sizeof(pi);
2064e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < total) {
20651da177e4SLinus Torvalds 			/* Packet will be striped */
20661da177e4SLinus Torvalds 			pi.flags |= TUN_PKT_STRIP;
20671da177e4SLinus Torvalds 		}
20681da177e4SLinus Torvalds 
2069e0b46d0eSHerbert Xu 		if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
20701da177e4SLinus Torvalds 			return -EFAULT;
20711da177e4SLinus Torvalds 	}
20721da177e4SLinus Torvalds 
20732eb783c4SHerbert Xu 	if (vnet_hdr_sz) {
20749403cd7cSJarno Rajahalme 		struct virtio_net_hdr gso;
207534166093SMike Rapoport 
2076e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < vnet_hdr_sz)
2077f43798c2SRusty Russell 			return -EINVAL;
2078f43798c2SRusty Russell 
20793e9e40e7SJarno Rajahalme 		if (virtio_net_hdr_from_skb(skb, &gso,
2080fd3a8862SWillem de Bruijn 					    tun_is_little_endian(tun), true,
2081fd3a8862SWillem de Bruijn 					    vlan_hlen)) {
2082f43798c2SRusty Russell 			struct skb_shared_info *sinfo = skb_shinfo(skb);
20836b8a66eeSJoe Perches 			pr_err("unexpected GSO type: "
2084ef3db4a5SMichael S. Tsirkin 			       "0x%x, gso_size %d, hdr_len %d\n",
208556f0dcc5SMichael S. Tsirkin 			       sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
208656f0dcc5SMichael S. Tsirkin 			       tun16_to_cpu(tun, gso.hdr_len));
2087ef3db4a5SMichael S. Tsirkin 			print_hex_dump(KERN_ERR, "tun: ",
2088ef3db4a5SMichael S. Tsirkin 				       DUMP_PREFIX_NONE,
2089ef3db4a5SMichael S. Tsirkin 				       16, 1, skb->head,
209056f0dcc5SMichael S. Tsirkin 				       min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
2091ef3db4a5SMichael S. Tsirkin 			WARN_ON_ONCE(1);
2092ef3db4a5SMichael S. Tsirkin 			return -EINVAL;
2093ef3db4a5SMichael S. Tsirkin 		}
2094f43798c2SRusty Russell 
2095e0b46d0eSHerbert Xu 		if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
2096f43798c2SRusty Russell 			return -EFAULT;
20978c847d25SJason Wang 
20988c847d25SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2099f43798c2SRusty Russell 	}
2100f43798c2SRusty Russell 
2101a8f9bfdfSHerbert Xu 	if (vlan_hlen) {
2102e0b46d0eSHerbert Xu 		int ret;
2103aff3d70aSJason Wang 		struct veth veth;
21041da177e4SLinus Torvalds 
21056680ec68SJason Wang 		veth.h_vlan_proto = skb->vlan_proto;
2106df8a39deSJiri Pirko 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
21071da177e4SLinus Torvalds 
21086680ec68SJason Wang 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
21096680ec68SJason Wang 
2110e0b46d0eSHerbert Xu 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
2111e0b46d0eSHerbert Xu 		if (ret || !iov_iter_count(iter))
21126680ec68SJason Wang 			goto done;
21136680ec68SJason Wang 
2114e0b46d0eSHerbert Xu 		ret = copy_to_iter(&veth, sizeof(veth), iter);
2115e0b46d0eSHerbert Xu 		if (ret != sizeof(veth) || !iov_iter_count(iter))
21166680ec68SJason Wang 			goto done;
21176680ec68SJason Wang 	}
21186680ec68SJason Wang 
2119e0b46d0eSHerbert Xu 	skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
21206680ec68SJason Wang 
21216680ec68SJason Wang done:
2122608b9977SPaolo Abeni 	/* caller is in process context, */
2123608b9977SPaolo Abeni 	stats = get_cpu_ptr(tun->pcpu_stats);
2124608b9977SPaolo Abeni 	u64_stats_update_begin(&stats->syncp);
2125608b9977SPaolo Abeni 	stats->tx_packets++;
2126608b9977SPaolo Abeni 	stats->tx_bytes += skb->len + vlan_hlen;
2127608b9977SPaolo Abeni 	u64_stats_update_end(&stats->syncp);
2128608b9977SPaolo Abeni 	put_cpu_ptr(tun->pcpu_stats);
21291da177e4SLinus Torvalds 
21301da177e4SLinus Torvalds 	return total;
21311da177e4SLinus Torvalds }
21321da177e4SLinus Torvalds 
2133fc72d1d5SJason Wang static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
21341576d986SJason Wang {
21351576d986SJason Wang 	DECLARE_WAITQUEUE(wait, current);
2136fc72d1d5SJason Wang 	void *ptr = NULL;
2137f48cc6b2SJason Wang 	int error = 0;
21381576d986SJason Wang 
2139fc72d1d5SJason Wang 	ptr = ptr_ring_consume(&tfile->tx_ring);
2140fc72d1d5SJason Wang 	if (ptr)
21411576d986SJason Wang 		goto out;
21421576d986SJason Wang 	if (noblock) {
2143f48cc6b2SJason Wang 		error = -EAGAIN;
21441576d986SJason Wang 		goto out;
21451576d986SJason Wang 	}
21461576d986SJason Wang 
21471576d986SJason Wang 	add_wait_queue(&tfile->wq.wait, &wait);
21481576d986SJason Wang 	current->state = TASK_INTERRUPTIBLE;
21491576d986SJason Wang 
21501576d986SJason Wang 	while (1) {
2151fc72d1d5SJason Wang 		ptr = ptr_ring_consume(&tfile->tx_ring);
2152fc72d1d5SJason Wang 		if (ptr)
21531576d986SJason Wang 			break;
21541576d986SJason Wang 		if (signal_pending(current)) {
2155f48cc6b2SJason Wang 			error = -ERESTARTSYS;
21561576d986SJason Wang 			break;
21571576d986SJason Wang 		}
21581576d986SJason Wang 		if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
2159f48cc6b2SJason Wang 			error = -EFAULT;
21601576d986SJason Wang 			break;
21611576d986SJason Wang 		}
21621576d986SJason Wang 
21631576d986SJason Wang 		schedule();
21641576d986SJason Wang 	}
21651576d986SJason Wang 
21661576d986SJason Wang 	current->state = TASK_RUNNING;
21671576d986SJason Wang 	remove_wait_queue(&tfile->wq.wait, &wait);
21681576d986SJason Wang 
21691576d986SJason Wang out:
2170f48cc6b2SJason Wang 	*err = error;
2171fc72d1d5SJason Wang 	return ptr;
21721576d986SJason Wang }
21731576d986SJason Wang 
217454f968d6SJason Wang static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
21759b067034SAl Viro 			   struct iov_iter *to,
2176fc72d1d5SJason Wang 			   int noblock, void *ptr)
21771da177e4SLinus Torvalds {
21789b067034SAl Viro 	ssize_t ret;
21791576d986SJason Wang 	int err;
21801da177e4SLinus Torvalds 
21813872baf6SRami Rosen 	tun_debug(KERN_INFO, tun, "tun_do_read\n");
21821da177e4SLinus Torvalds 
2183c33ee15bSWei Xu 	if (!iov_iter_count(to)) {
2184fc72d1d5SJason Wang 		tun_ptr_free(ptr);
21859b067034SAl Viro 		return 0;
2186c33ee15bSWei Xu 	}
21871da177e4SLinus Torvalds 
2188fc72d1d5SJason Wang 	if (!ptr) {
21891576d986SJason Wang 		/* Read frames from ring */
2190fc72d1d5SJason Wang 		ptr = tun_ring_recv(tfile, noblock, &err);
2191fc72d1d5SJason Wang 		if (!ptr)
2192957f094fSAlex Gartrell 			return err;
2193ac77cfd4SJason Wang 	}
2194e0b46d0eSHerbert Xu 
21951ffcbc85SJesper Dangaard Brouer 	if (tun_is_xdp_frame(ptr)) {
21961ffcbc85SJesper Dangaard Brouer 		struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2197fc72d1d5SJason Wang 
21981ffcbc85SJesper Dangaard Brouer 		ret = tun_put_user_xdp(tun, tfile, xdpf, to);
219903993094SJesper Dangaard Brouer 		xdp_return_frame(xdpf);
2200fc72d1d5SJason Wang 	} else {
2201fc72d1d5SJason Wang 		struct sk_buff *skb = ptr;
2202fc72d1d5SJason Wang 
22039b067034SAl Viro 		ret = tun_put_user(tun, tfile, skb, to);
2204f51a5e82SJason Wang 		if (unlikely(ret < 0))
22051da177e4SLinus Torvalds 			kfree_skb(skb);
2206f51a5e82SJason Wang 		else
2207f51a5e82SJason Wang 			consume_skb(skb);
2208fc72d1d5SJason Wang 	}
22091da177e4SLinus Torvalds 
221005c2828cSMichael S. Tsirkin 	return ret;
221105c2828cSMichael S. Tsirkin }
221205c2828cSMichael S. Tsirkin 
22139b067034SAl Viro static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
221405c2828cSMichael S. Tsirkin {
221505c2828cSMichael S. Tsirkin 	struct file *file = iocb->ki_filp;
221605c2828cSMichael S. Tsirkin 	struct tun_file *tfile = file->private_data;
22179484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
22189b067034SAl Viro 	ssize_t len = iov_iter_count(to), ret;
221905c2828cSMichael S. Tsirkin 
222005c2828cSMichael S. Tsirkin 	if (!tun)
222105c2828cSMichael S. Tsirkin 		return -EBADFD;
2222ac77cfd4SJason Wang 	ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
222342404c09SDavid S. Miller 	ret = min_t(ssize_t, ret, len);
2224d0b7da8aSZhi Yong Wu 	if (ret > 0)
2225d0b7da8aSZhi Yong Wu 		iocb->ki_pos = ret;
2226631ab46bSEric W. Biederman 	tun_put(tun);
22271da177e4SLinus Torvalds 	return ret;
22281da177e4SLinus Torvalds }
22291da177e4SLinus Torvalds 
2230cd5681d7SJason Wang static void tun_prog_free(struct rcu_head *rcu)
223196f84061SJason Wang {
2232cd5681d7SJason Wang 	struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
223396f84061SJason Wang 
223496f84061SJason Wang 	bpf_prog_destroy(prog->prog);
223596f84061SJason Wang 	kfree(prog);
223696f84061SJason Wang }
223796f84061SJason Wang 
22389d6474e4SJason Wang static int __tun_set_ebpf(struct tun_struct *tun,
22399d6474e4SJason Wang 			  struct tun_prog __rcu **prog_p,
224096f84061SJason Wang 			  struct bpf_prog *prog)
224196f84061SJason Wang {
2242cd5681d7SJason Wang 	struct tun_prog *old, *new = NULL;
224396f84061SJason Wang 
224496f84061SJason Wang 	if (prog) {
224596f84061SJason Wang 		new = kmalloc(sizeof(*new), GFP_KERNEL);
224696f84061SJason Wang 		if (!new)
224796f84061SJason Wang 			return -ENOMEM;
224896f84061SJason Wang 		new->prog = prog;
224996f84061SJason Wang 	}
225096f84061SJason Wang 
2251124da8f6SJason Wang 	spin_lock_bh(&tun->lock);
2252cd5681d7SJason Wang 	old = rcu_dereference_protected(*prog_p,
2253124da8f6SJason Wang 					lockdep_is_held(&tun->lock));
2254cd5681d7SJason Wang 	rcu_assign_pointer(*prog_p, new);
2255124da8f6SJason Wang 	spin_unlock_bh(&tun->lock);
225696f84061SJason Wang 
225796f84061SJason Wang 	if (old)
2258cd5681d7SJason Wang 		call_rcu(&old->rcu, tun_prog_free);
225996f84061SJason Wang 
226096f84061SJason Wang 	return 0;
226196f84061SJason Wang }
226296f84061SJason Wang 
226396442e42SJason Wang static void tun_free_netdev(struct net_device *dev)
226496442e42SJason Wang {
226596442e42SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
226696442e42SJason Wang 
22674008e97fSJason Wang 	BUG_ON(!(list_empty(&tun->disabled)));
2268608b9977SPaolo Abeni 	free_percpu(tun->pcpu_stats);
226996442e42SJason Wang 	tun_flow_uninit(tun);
22705dbbaf2dSPaul Moore 	security_tun_dev_free_security(tun->security);
2271cd5681d7SJason Wang 	__tun_set_ebpf(tun, &tun->steering_prog, NULL);
2272aff3d70aSJason Wang 	__tun_set_ebpf(tun, &tun->filter_prog, NULL);
227396442e42SJason Wang }
227496442e42SJason Wang 
22751da177e4SLinus Torvalds static void tun_setup(struct net_device *dev)
22761da177e4SLinus Torvalds {
22771da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
22781da177e4SLinus Torvalds 
22790625c883SEric W. Biederman 	tun->owner = INVALID_UID;
22800625c883SEric W. Biederman 	tun->group = INVALID_GID;
22814e24f2ddSChas Williams 	tun_default_link_ksettings(dev, &tun->link_ksettings);
22821da177e4SLinus Torvalds 
22831da177e4SLinus Torvalds 	dev->ethtool_ops = &tun_ethtool_ops;
2284cf124db5SDavid S. Miller 	dev->needs_free_netdev = true;
2285cf124db5SDavid S. Miller 	dev->priv_destructor = tun_free_netdev;
2286016adb72SJason Wang 	/* We prefer our own queue length */
2287016adb72SJason Wang 	dev->tx_queue_len = TUN_READQ_SIZE;
22881da177e4SLinus Torvalds }
22891da177e4SLinus Torvalds 
2290f019a7a5SEric W. Biederman /* Trivial set of netlink ops to allow deleting tun or tap
2291f019a7a5SEric W. Biederman  * device with netlink.
2292f019a7a5SEric W. Biederman  */
2293a8b8a889SMatthias Schiffer static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2294a8b8a889SMatthias Schiffer 			struct netlink_ext_ack *extack)
2295f019a7a5SEric W. Biederman {
2296df52eab2SSerhey Popovych 	if (!data)
2297df52eab2SSerhey Popovych 		return 0;
2298f019a7a5SEric W. Biederman 	return -EINVAL;
2299f019a7a5SEric W. Biederman }
2300f019a7a5SEric W. Biederman 
23011ec010e7SSabrina Dubroca static size_t tun_get_size(const struct net_device *dev)
23021ec010e7SSabrina Dubroca {
23031ec010e7SSabrina Dubroca 	BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
23041ec010e7SSabrina Dubroca 	BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
23051ec010e7SSabrina Dubroca 
23061ec010e7SSabrina Dubroca 	return nla_total_size(sizeof(uid_t)) + /* OWNER */
23071ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(gid_t)) + /* GROUP */
23081ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* TYPE */
23091ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* PI */
23101ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* VNET_HDR */
23111ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* PERSIST */
23121ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
23131ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
23141ec010e7SSabrina Dubroca 	       nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
23151ec010e7SSabrina Dubroca 	       0;
23161ec010e7SSabrina Dubroca }
23171ec010e7SSabrina Dubroca 
23181ec010e7SSabrina Dubroca static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
23191ec010e7SSabrina Dubroca {
23201ec010e7SSabrina Dubroca 	struct tun_struct *tun = netdev_priv(dev);
23211ec010e7SSabrina Dubroca 
23221ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
23231ec010e7SSabrina Dubroca 		goto nla_put_failure;
23241ec010e7SSabrina Dubroca 	if (uid_valid(tun->owner) &&
23251ec010e7SSabrina Dubroca 	    nla_put_u32(skb, IFLA_TUN_OWNER,
23261ec010e7SSabrina Dubroca 			from_kuid_munged(current_user_ns(), tun->owner)))
23271ec010e7SSabrina Dubroca 		goto nla_put_failure;
23281ec010e7SSabrina Dubroca 	if (gid_valid(tun->group) &&
23291ec010e7SSabrina Dubroca 	    nla_put_u32(skb, IFLA_TUN_GROUP,
23301ec010e7SSabrina Dubroca 			from_kgid_munged(current_user_ns(), tun->group)))
23311ec010e7SSabrina Dubroca 		goto nla_put_failure;
23321ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
23331ec010e7SSabrina Dubroca 		goto nla_put_failure;
23341ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
23351ec010e7SSabrina Dubroca 		goto nla_put_failure;
23361ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
23371ec010e7SSabrina Dubroca 		goto nla_put_failure;
23381ec010e7SSabrina Dubroca 	if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
23391ec010e7SSabrina Dubroca 		       !!(tun->flags & IFF_MULTI_QUEUE)))
23401ec010e7SSabrina Dubroca 		goto nla_put_failure;
23411ec010e7SSabrina Dubroca 	if (tun->flags & IFF_MULTI_QUEUE) {
23421ec010e7SSabrina Dubroca 		if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
23431ec010e7SSabrina Dubroca 			goto nla_put_failure;
23441ec010e7SSabrina Dubroca 		if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
23451ec010e7SSabrina Dubroca 				tun->numdisabled))
23461ec010e7SSabrina Dubroca 			goto nla_put_failure;
23471ec010e7SSabrina Dubroca 	}
23481ec010e7SSabrina Dubroca 
23491ec010e7SSabrina Dubroca 	return 0;
23501ec010e7SSabrina Dubroca 
23511ec010e7SSabrina Dubroca nla_put_failure:
23521ec010e7SSabrina Dubroca 	return -EMSGSIZE;
23531ec010e7SSabrina Dubroca }
23541ec010e7SSabrina Dubroca 
2355f019a7a5SEric W. Biederman static struct rtnl_link_ops tun_link_ops __read_mostly = {
2356f019a7a5SEric W. Biederman 	.kind		= DRV_NAME,
2357f019a7a5SEric W. Biederman 	.priv_size	= sizeof(struct tun_struct),
2358f019a7a5SEric W. Biederman 	.setup		= tun_setup,
2359f019a7a5SEric W. Biederman 	.validate	= tun_validate,
23601ec010e7SSabrina Dubroca 	.get_size       = tun_get_size,
23611ec010e7SSabrina Dubroca 	.fill_info      = tun_fill_info,
2362f019a7a5SEric W. Biederman };
2363f019a7a5SEric W. Biederman 
236433dccbb0SHerbert Xu static void tun_sock_write_space(struct sock *sk)
236533dccbb0SHerbert Xu {
236654f968d6SJason Wang 	struct tun_file *tfile;
236743815482SEric Dumazet 	wait_queue_head_t *wqueue;
236833dccbb0SHerbert Xu 
236933dccbb0SHerbert Xu 	if (!sock_writeable(sk))
237033dccbb0SHerbert Xu 		return;
237133dccbb0SHerbert Xu 
23729cd3e072SEric Dumazet 	if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
237333dccbb0SHerbert Xu 		return;
237433dccbb0SHerbert Xu 
237543815482SEric Dumazet 	wqueue = sk_sleep(sk);
237643815482SEric Dumazet 	if (wqueue && waitqueue_active(wqueue))
2377a9a08845SLinus Torvalds 		wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
2378a9a08845SLinus Torvalds 						EPOLLWRNORM | EPOLLWRBAND);
2379c722c625SHerbert Xu 
238054f968d6SJason Wang 	tfile = container_of(sk, struct tun_file, sk);
238154f968d6SJason Wang 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
238233dccbb0SHerbert Xu }
238333dccbb0SHerbert Xu 
2384f9e06c45SJason Wang static void tun_put_page(struct tun_page *tpage)
2385f9e06c45SJason Wang {
2386f9e06c45SJason Wang 	if (tpage->page)
2387f9e06c45SJason Wang 		__page_frag_cache_drain(tpage->page, tpage->count);
2388f9e06c45SJason Wang }
2389f9e06c45SJason Wang 
2390043d222fSJason Wang static int tun_xdp_one(struct tun_struct *tun,
2391043d222fSJason Wang 		       struct tun_file *tfile,
2392f9e06c45SJason Wang 		       struct xdp_buff *xdp, int *flush,
2393f9e06c45SJason Wang 		       struct tun_page *tpage)
2394043d222fSJason Wang {
2395043d222fSJason Wang 	struct tun_xdp_hdr *hdr = xdp->data_hard_start;
2396043d222fSJason Wang 	struct virtio_net_hdr *gso = &hdr->gso;
2397043d222fSJason Wang 	struct tun_pcpu_stats *stats;
2398043d222fSJason Wang 	struct bpf_prog *xdp_prog;
2399043d222fSJason Wang 	struct sk_buff *skb = NULL;
2400043d222fSJason Wang 	u32 rxhash = 0, act;
2401043d222fSJason Wang 	int buflen = hdr->buflen;
2402043d222fSJason Wang 	int err = 0;
2403043d222fSJason Wang 	bool skb_xdp = false;
2404f9e06c45SJason Wang 	struct page *page;
2405043d222fSJason Wang 
2406043d222fSJason Wang 	xdp_prog = rcu_dereference(tun->xdp_prog);
2407043d222fSJason Wang 	if (xdp_prog) {
2408043d222fSJason Wang 		if (gso->gso_type) {
2409043d222fSJason Wang 			skb_xdp = true;
2410043d222fSJason Wang 			goto build;
2411043d222fSJason Wang 		}
2412043d222fSJason Wang 		xdp_set_data_meta_invalid(xdp);
2413043d222fSJason Wang 		xdp->rxq = &tfile->xdp_rxq;
2414043d222fSJason Wang 
2415043d222fSJason Wang 		act = bpf_prog_run_xdp(xdp_prog, xdp);
2416043d222fSJason Wang 		err = tun_xdp_act(tun, xdp_prog, xdp, act);
2417043d222fSJason Wang 		if (err < 0) {
2418043d222fSJason Wang 			put_page(virt_to_head_page(xdp->data));
2419043d222fSJason Wang 			return err;
2420043d222fSJason Wang 		}
2421043d222fSJason Wang 
2422043d222fSJason Wang 		switch (err) {
2423043d222fSJason Wang 		case XDP_REDIRECT:
2424043d222fSJason Wang 			*flush = true;
2425043d222fSJason Wang 			/* fall through */
2426043d222fSJason Wang 		case XDP_TX:
2427043d222fSJason Wang 			return 0;
2428043d222fSJason Wang 		case XDP_PASS:
2429043d222fSJason Wang 			break;
2430043d222fSJason Wang 		default:
2431f9e06c45SJason Wang 			page = virt_to_head_page(xdp->data);
2432f9e06c45SJason Wang 			if (tpage->page == page) {
2433f9e06c45SJason Wang 				++tpage->count;
2434f9e06c45SJason Wang 			} else {
2435f9e06c45SJason Wang 				tun_put_page(tpage);
2436f9e06c45SJason Wang 				tpage->page = page;
2437f9e06c45SJason Wang 				tpage->count = 1;
2438f9e06c45SJason Wang 			}
2439043d222fSJason Wang 			return 0;
2440043d222fSJason Wang 		}
2441043d222fSJason Wang 	}
2442043d222fSJason Wang 
2443043d222fSJason Wang build:
2444043d222fSJason Wang 	skb = build_skb(xdp->data_hard_start, buflen);
2445043d222fSJason Wang 	if (!skb) {
2446043d222fSJason Wang 		err = -ENOMEM;
2447043d222fSJason Wang 		goto out;
2448043d222fSJason Wang 	}
2449043d222fSJason Wang 
2450043d222fSJason Wang 	skb_reserve(skb, xdp->data - xdp->data_hard_start);
2451043d222fSJason Wang 	skb_put(skb, xdp->data_end - xdp->data);
2452043d222fSJason Wang 
2453043d222fSJason Wang 	if (virtio_net_hdr_to_skb(skb, gso, tun_is_little_endian(tun))) {
2454043d222fSJason Wang 		this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
2455043d222fSJason Wang 		kfree_skb(skb);
2456043d222fSJason Wang 		err = -EINVAL;
2457043d222fSJason Wang 		goto out;
2458043d222fSJason Wang 	}
2459043d222fSJason Wang 
2460043d222fSJason Wang 	skb->protocol = eth_type_trans(skb, tun->dev);
2461043d222fSJason Wang 	skb_reset_network_header(skb);
2462043d222fSJason Wang 	skb_probe_transport_header(skb, 0);
2463043d222fSJason Wang 
2464043d222fSJason Wang 	if (skb_xdp) {
2465043d222fSJason Wang 		err = do_xdp_generic(xdp_prog, skb);
2466043d222fSJason Wang 		if (err != XDP_PASS)
2467043d222fSJason Wang 			goto out;
2468043d222fSJason Wang 	}
2469043d222fSJason Wang 
2470f29eb2a9SPaolo Abeni 	if (!rcu_dereference(tun->steering_prog) && tun->numqueues > 1 &&
2471f29eb2a9SPaolo Abeni 	    !tfile->detached)
2472043d222fSJason Wang 		rxhash = __skb_get_hash_symmetric(skb);
2473043d222fSJason Wang 
2474043d222fSJason Wang 	netif_receive_skb(skb);
2475043d222fSJason Wang 
2476043d222fSJason Wang 	stats = get_cpu_ptr(tun->pcpu_stats);
2477043d222fSJason Wang 	u64_stats_update_begin(&stats->syncp);
2478043d222fSJason Wang 	stats->rx_packets++;
2479043d222fSJason Wang 	stats->rx_bytes += skb->len;
2480043d222fSJason Wang 	u64_stats_update_end(&stats->syncp);
2481043d222fSJason Wang 	put_cpu_ptr(stats);
2482043d222fSJason Wang 
2483043d222fSJason Wang 	if (rxhash)
2484043d222fSJason Wang 		tun_flow_update(tun, rxhash, tfile);
2485043d222fSJason Wang 
2486043d222fSJason Wang out:
2487043d222fSJason Wang 	return err;
2488043d222fSJason Wang }
2489043d222fSJason Wang 
24901b784140SYing Xue static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
249105c2828cSMichael S. Tsirkin {
2492043d222fSJason Wang 	int ret, i;
249354f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
24949484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2495fe8dd45bSJason Wang 	struct tun_msg_ctl *ctl = m->msg_control;
2496043d222fSJason Wang 	struct xdp_buff *xdp;
249754f968d6SJason Wang 
249854f968d6SJason Wang 	if (!tun)
249954f968d6SJason Wang 		return -EBADFD;
2500f5ff53b4SAl Viro 
2501043d222fSJason Wang 	if (ctl && (ctl->type == TUN_MSG_PTR)) {
25026f0271d9SDavid S. Miller 		struct tun_page tpage;
2503043d222fSJason Wang 		int n = ctl->num;
2504043d222fSJason Wang 		int flush = 0;
2505043d222fSJason Wang 
25066f0271d9SDavid S. Miller 		memset(&tpage, 0, sizeof(tpage));
25076f0271d9SDavid S. Miller 
2508043d222fSJason Wang 		local_bh_disable();
2509043d222fSJason Wang 		rcu_read_lock();
2510043d222fSJason Wang 
2511043d222fSJason Wang 		for (i = 0; i < n; i++) {
2512043d222fSJason Wang 			xdp = &((struct xdp_buff *)ctl->ptr)[i];
2513f9e06c45SJason Wang 			tun_xdp_one(tun, tfile, xdp, &flush, &tpage);
2514043d222fSJason Wang 		}
2515043d222fSJason Wang 
2516043d222fSJason Wang 		if (flush)
2517043d222fSJason Wang 			xdp_do_flush_map();
2518043d222fSJason Wang 
2519043d222fSJason Wang 		rcu_read_unlock();
2520043d222fSJason Wang 		local_bh_enable();
2521043d222fSJason Wang 
2522f9e06c45SJason Wang 		tun_put_page(&tpage);
2523f9e06c45SJason Wang 
2524043d222fSJason Wang 		ret = total_len;
2525043d222fSJason Wang 		goto out;
2526043d222fSJason Wang 	}
2527fe8dd45bSJason Wang 
2528fe8dd45bSJason Wang 	ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
25295503fcecSJason Wang 			   m->msg_flags & MSG_DONTWAIT,
25305503fcecSJason Wang 			   m->msg_flags & MSG_MORE);
2531043d222fSJason Wang out:
253254f968d6SJason Wang 	tun_put(tun);
253354f968d6SJason Wang 	return ret;
253405c2828cSMichael S. Tsirkin }
253505c2828cSMichael S. Tsirkin 
25361b784140SYing Xue static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
253705c2828cSMichael S. Tsirkin 		       int flags)
253805c2828cSMichael S. Tsirkin {
253954f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
25409484dc74Syuan linyu 	struct tun_struct *tun = tun_get(tfile);
2541fc72d1d5SJason Wang 	void *ptr = m->msg_control;
254205c2828cSMichael S. Tsirkin 	int ret;
254354f968d6SJason Wang 
2544c33ee15bSWei Xu 	if (!tun) {
2545c33ee15bSWei Xu 		ret = -EBADFD;
2546fc72d1d5SJason Wang 		goto out_free;
2547c33ee15bSWei Xu 	}
254854f968d6SJason Wang 
2549eda29772SRichard Cochran 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
25503811ae76SGao feng 		ret = -EINVAL;
2551c33ee15bSWei Xu 		goto out_put_tun;
25523811ae76SGao feng 	}
2553eda29772SRichard Cochran 	if (flags & MSG_ERRQUEUE) {
2554eda29772SRichard Cochran 		ret = sock_recv_errqueue(sock->sk, m, total_len,
2555eda29772SRichard Cochran 					 SOL_PACKET, TUN_TX_TIMESTAMP);
2556eda29772SRichard Cochran 		goto out;
2557eda29772SRichard Cochran 	}
2558fc72d1d5SJason Wang 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
255987897931SAlex Gartrell 	if (ret > (ssize_t)total_len) {
256042404c09SDavid S. Miller 		m->msg_flags |= MSG_TRUNC;
256142404c09SDavid S. Miller 		ret = flags & MSG_TRUNC ? ret : total_len;
256242404c09SDavid S. Miller 	}
25633811ae76SGao feng out:
256454f968d6SJason Wang 	tun_put(tun);
256505c2828cSMichael S. Tsirkin 	return ret;
2566c33ee15bSWei Xu 
2567c33ee15bSWei Xu out_put_tun:
2568c33ee15bSWei Xu 	tun_put(tun);
2569fc72d1d5SJason Wang out_free:
2570fc72d1d5SJason Wang 	tun_ptr_free(ptr);
2571c33ee15bSWei Xu 	return ret;
257205c2828cSMichael S. Tsirkin }
257305c2828cSMichael S. Tsirkin 
2574fc72d1d5SJason Wang static int tun_ptr_peek_len(void *ptr)
2575fc72d1d5SJason Wang {
2576fc72d1d5SJason Wang 	if (likely(ptr)) {
25771ffcbc85SJesper Dangaard Brouer 		if (tun_is_xdp_frame(ptr)) {
25781ffcbc85SJesper Dangaard Brouer 			struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2579fc72d1d5SJason Wang 
25801ffcbc85SJesper Dangaard Brouer 			return xdpf->len;
2581fc72d1d5SJason Wang 		}
2582fc72d1d5SJason Wang 		return __skb_array_len_with_tag(ptr);
2583fc72d1d5SJason Wang 	} else {
2584fc72d1d5SJason Wang 		return 0;
2585fc72d1d5SJason Wang 	}
2586fc72d1d5SJason Wang }
2587fc72d1d5SJason Wang 
25881576d986SJason Wang static int tun_peek_len(struct socket *sock)
25891576d986SJason Wang {
25901576d986SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
25911576d986SJason Wang 	struct tun_struct *tun;
25921576d986SJason Wang 	int ret = 0;
25931576d986SJason Wang 
25949484dc74Syuan linyu 	tun = tun_get(tfile);
25951576d986SJason Wang 	if (!tun)
25961576d986SJason Wang 		return 0;
25971576d986SJason Wang 
2598fc72d1d5SJason Wang 	ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
25991576d986SJason Wang 	tun_put(tun);
26001576d986SJason Wang 
26011576d986SJason Wang 	return ret;
26021576d986SJason Wang }
26031576d986SJason Wang 
260405c2828cSMichael S. Tsirkin /* Ops structure to mimic raw sockets with tun */
260505c2828cSMichael S. Tsirkin static const struct proto_ops tun_socket_ops = {
26061576d986SJason Wang 	.peek_len = tun_peek_len,
260705c2828cSMichael S. Tsirkin 	.sendmsg = tun_sendmsg,
260805c2828cSMichael S. Tsirkin 	.recvmsg = tun_recvmsg,
260905c2828cSMichael S. Tsirkin };
261005c2828cSMichael S. Tsirkin 
261133dccbb0SHerbert Xu static struct proto tun_proto = {
261233dccbb0SHerbert Xu 	.name		= "tun",
261333dccbb0SHerbert Xu 	.owner		= THIS_MODULE,
261454f968d6SJason Wang 	.obj_size	= sizeof(struct tun_file),
261533dccbb0SHerbert Xu };
2616f019a7a5SEric W. Biederman 
2617980c9e8cSDavid Woodhouse static int tun_flags(struct tun_struct *tun)
2618980c9e8cSDavid Woodhouse {
2619031f5e03SMichael S. Tsirkin 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2620980c9e8cSDavid Woodhouse }
2621980c9e8cSDavid Woodhouse 
2622980c9e8cSDavid Woodhouse static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2623980c9e8cSDavid Woodhouse 			      char *buf)
2624980c9e8cSDavid Woodhouse {
2625980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2626980c9e8cSDavid Woodhouse 	return sprintf(buf, "0x%x\n", tun_flags(tun));
2627980c9e8cSDavid Woodhouse }
2628980c9e8cSDavid Woodhouse 
2629980c9e8cSDavid Woodhouse static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2630980c9e8cSDavid Woodhouse 			      char *buf)
2631980c9e8cSDavid Woodhouse {
2632980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
26330625c883SEric W. Biederman 	return uid_valid(tun->owner)?
26340625c883SEric W. Biederman 		sprintf(buf, "%u\n",
26350625c883SEric W. Biederman 			from_kuid_munged(current_user_ns(), tun->owner)):
26360625c883SEric W. Biederman 		sprintf(buf, "-1\n");
2637980c9e8cSDavid Woodhouse }
2638980c9e8cSDavid Woodhouse 
2639980c9e8cSDavid Woodhouse static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2640980c9e8cSDavid Woodhouse 			      char *buf)
2641980c9e8cSDavid Woodhouse {
2642980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
26430625c883SEric W. Biederman 	return gid_valid(tun->group) ?
26440625c883SEric W. Biederman 		sprintf(buf, "%u\n",
26450625c883SEric W. Biederman 			from_kgid_munged(current_user_ns(), tun->group)):
26460625c883SEric W. Biederman 		sprintf(buf, "-1\n");
2647980c9e8cSDavid Woodhouse }
2648980c9e8cSDavid Woodhouse 
2649980c9e8cSDavid Woodhouse static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2650980c9e8cSDavid Woodhouse static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2651980c9e8cSDavid Woodhouse static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2652980c9e8cSDavid Woodhouse 
2653c4d33e24STakashi Iwai static struct attribute *tun_dev_attrs[] = {
2654c4d33e24STakashi Iwai 	&dev_attr_tun_flags.attr,
2655c4d33e24STakashi Iwai 	&dev_attr_owner.attr,
2656c4d33e24STakashi Iwai 	&dev_attr_group.attr,
2657c4d33e24STakashi Iwai 	NULL
2658c4d33e24STakashi Iwai };
2659c4d33e24STakashi Iwai 
2660c4d33e24STakashi Iwai static const struct attribute_group tun_attr_group = {
2661c4d33e24STakashi Iwai 	.attrs = tun_dev_attrs
2662c4d33e24STakashi Iwai };
2663c4d33e24STakashi Iwai 
2664d647a591SPavel Emelyanov static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
26651da177e4SLinus Torvalds {
26661da177e4SLinus Torvalds 	struct tun_struct *tun;
266754f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
26681da177e4SLinus Torvalds 	struct net_device *dev;
26691da177e4SLinus Torvalds 	int err;
26701da177e4SLinus Torvalds 
26717c0c3b1aSJason Wang 	if (tfile->detached)
26727c0c3b1aSJason Wang 		return -EINVAL;
26737c0c3b1aSJason Wang 
267490e33d45SPetar Penkov 	if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
267590e33d45SPetar Penkov 		if (!capable(CAP_NET_ADMIN))
267690e33d45SPetar Penkov 			return -EPERM;
267790e33d45SPetar Penkov 
267890e33d45SPetar Penkov 		if (!(ifr->ifr_flags & IFF_NAPI) ||
267990e33d45SPetar Penkov 		    (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
268090e33d45SPetar Penkov 			return -EINVAL;
268190e33d45SPetar Penkov 	}
268290e33d45SPetar Penkov 
268374a3e5a7SEric W. Biederman 	dev = __dev_get_by_name(net, ifr->ifr_name);
268474a3e5a7SEric W. Biederman 	if (dev) {
2685f85ba780SDavid Woodhouse 		if (ifr->ifr_flags & IFF_TUN_EXCL)
2686f85ba780SDavid Woodhouse 			return -EBUSY;
268774a3e5a7SEric W. Biederman 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
268874a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
268974a3e5a7SEric W. Biederman 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
269074a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
269174a3e5a7SEric W. Biederman 		else
269274a3e5a7SEric W. Biederman 			return -EINVAL;
269374a3e5a7SEric W. Biederman 
26948e6d91aeSJason Wang 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
269540630b82SMichael S. Tsirkin 		    !!(tun->flags & IFF_MULTI_QUEUE))
26968e6d91aeSJason Wang 			return -EINVAL;
26978e6d91aeSJason Wang 
2698cde8b15fSJason Wang 		if (tun_not_capable(tun))
26992b980dbdSPaul Moore 			return -EPERM;
27005dbbaf2dSPaul Moore 		err = security_tun_dev_open(tun->security);
27012b980dbdSPaul Moore 		if (err < 0)
27022b980dbdSPaul Moore 			return err;
27032b980dbdSPaul Moore 
270494317099SPetar Penkov 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
2705af3fb24eSEric Dumazet 				 ifr->ifr_flags & IFF_NAPI,
2706af3fb24eSEric Dumazet 				 ifr->ifr_flags & IFF_NAPI_FRAGS);
2707a7385ba2SEric W. Biederman 		if (err < 0)
2708a7385ba2SEric W. Biederman 			return err;
27094008e97fSJason Wang 
271040630b82SMichael S. Tsirkin 		if (tun->flags & IFF_MULTI_QUEUE &&
2711e8dbad66SJason Wang 		    (tun->numqueues + tun->numdisabled > 1)) {
2712e8dbad66SJason Wang 			/* One or more queue has already been attached, no need
2713e8dbad66SJason Wang 			 * to initialize the device again.
2714e8dbad66SJason Wang 			 */
271583c1f36fSSabrina Dubroca 			netdev_state_change(dev);
2716e8dbad66SJason Wang 			return 0;
2717e8dbad66SJason Wang 		}
27189fffc5c6SSabrina Dubroca 
27199fffc5c6SSabrina Dubroca 		tun->flags = (tun->flags & ~TUN_FEATURES) |
27209fffc5c6SSabrina Dubroca 			      (ifr->ifr_flags & TUN_FEATURES);
272183c1f36fSSabrina Dubroca 
272283c1f36fSSabrina Dubroca 		netdev_state_change(dev);
272383c1f36fSSabrina Dubroca 	} else {
27241da177e4SLinus Torvalds 		char *name;
27251da177e4SLinus Torvalds 		unsigned long flags = 0;
2726edfb6a14SJason Wang 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2727edfb6a14SJason Wang 			     MAX_TAP_QUEUES : 1;
27281da177e4SLinus Torvalds 
2729c260b772SEric W. Biederman 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2730ca6bb5d7SDavid Woodhouse 			return -EPERM;
27312b980dbdSPaul Moore 		err = security_tun_dev_create();
27322b980dbdSPaul Moore 		if (err < 0)
27332b980dbdSPaul Moore 			return err;
2734ca6bb5d7SDavid Woodhouse 
27351da177e4SLinus Torvalds 		/* Set dev type */
27361da177e4SLinus Torvalds 		if (ifr->ifr_flags & IFF_TUN) {
27371da177e4SLinus Torvalds 			/* TUN device */
273840630b82SMichael S. Tsirkin 			flags |= IFF_TUN;
27391da177e4SLinus Torvalds 			name = "tun%d";
27401da177e4SLinus Torvalds 		} else if (ifr->ifr_flags & IFF_TAP) {
27411da177e4SLinus Torvalds 			/* TAP device */
274240630b82SMichael S. Tsirkin 			flags |= IFF_TAP;
27431da177e4SLinus Torvalds 			name = "tap%d";
27441da177e4SLinus Torvalds 		} else
274536989b90SKusanagi Kouichi 			return -EINVAL;
27461da177e4SLinus Torvalds 
27471da177e4SLinus Torvalds 		if (*ifr->ifr_name)
27481da177e4SLinus Torvalds 			name = ifr->ifr_name;
27491da177e4SLinus Torvalds 
2750c8d68e6bSJason Wang 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2751c835a677STom Gundersen 				       NET_NAME_UNKNOWN, tun_setup, queues,
2752c835a677STom Gundersen 				       queues);
2753edfb6a14SJason Wang 
27541da177e4SLinus Torvalds 		if (!dev)
27551da177e4SLinus Torvalds 			return -ENOMEM;
27560ad646c8SCong Wang 		err = dev_get_valid_name(net, dev, name);
27575c25f65fSJulien Gomes 		if (err < 0)
27580ad646c8SCong Wang 			goto err_free_dev;
27591da177e4SLinus Torvalds 
2760fc54c658SPavel Emelyanov 		dev_net_set(dev, net);
2761f019a7a5SEric W. Biederman 		dev->rtnl_link_ops = &tun_link_ops;
2762fb7589a1SPavel Emelyanov 		dev->ifindex = tfile->ifindex;
2763c4d33e24STakashi Iwai 		dev->sysfs_groups[0] = &tun_attr_group;
2764758e43b7SStephen Hemminger 
27651da177e4SLinus Torvalds 		tun = netdev_priv(dev);
27661da177e4SLinus Torvalds 		tun->dev = dev;
27671da177e4SLinus Torvalds 		tun->flags = flags;
2768f271b2ccSMax Krasnyansky 		tun->txflt.count = 0;
2769d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
27701da177e4SLinus Torvalds 
2771eaea34b2SPaolo Abeni 		tun->align = NET_SKB_PAD;
277254f968d6SJason Wang 		tun->filter_attached = false;
277354f968d6SJason Wang 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
27745503fcecSJason Wang 		tun->rx_batched = 0;
277596f84061SJason Wang 		RCU_INIT_POINTER(tun->steering_prog, NULL);
277633dccbb0SHerbert Xu 
2777608b9977SPaolo Abeni 		tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2778608b9977SPaolo Abeni 		if (!tun->pcpu_stats) {
2779608b9977SPaolo Abeni 			err = -ENOMEM;
2780608b9977SPaolo Abeni 			goto err_free_dev;
2781608b9977SPaolo Abeni 		}
2782608b9977SPaolo Abeni 
278396442e42SJason Wang 		spin_lock_init(&tun->lock);
278496442e42SJason Wang 
27855dbbaf2dSPaul Moore 		err = security_tun_dev_alloc_security(&tun->security);
27865dbbaf2dSPaul Moore 		if (err < 0)
2787608b9977SPaolo Abeni 			goto err_free_stat;
27882b980dbdSPaul Moore 
27891da177e4SLinus Torvalds 		tun_net_init(dev);
2790944a1376SPavel Emelyanov 		tun_flow_init(tun);
279196442e42SJason Wang 
279288255375SMichał Mirosław 		dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
27936680ec68SJason Wang 				   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
27946680ec68SJason Wang 				   NETIF_F_HW_VLAN_STAG_TX;
27952a2bbf17SPaolo Abeni 		dev->features = dev->hw_features | NETIF_F_LLTX;
27966671b224SFernando Luis Vazquez Cao 		dev->vlan_features = dev->features &
27976671b224SFernando Luis Vazquez Cao 				     ~(NETIF_F_HW_VLAN_CTAG_TX |
27986671b224SFernando Luis Vazquez Cao 				       NETIF_F_HW_VLAN_STAG_TX);
279988255375SMichał Mirosław 
28009fffc5c6SSabrina Dubroca 		tun->flags = (tun->flags & ~TUN_FEATURES) |
28019fffc5c6SSabrina Dubroca 			      (ifr->ifr_flags & TUN_FEATURES);
28029fffc5c6SSabrina Dubroca 
28034008e97fSJason Wang 		INIT_LIST_HEAD(&tun->disabled);
2804af3fb24eSEric Dumazet 		err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI,
2805af3fb24eSEric Dumazet 				 ifr->ifr_flags & IFF_NAPI_FRAGS);
2806eb0fb363SJason Wang 		if (err < 0)
2807662ca437SJason Wang 			goto err_free_flow;
2808eb0fb363SJason Wang 
28091da177e4SLinus Torvalds 		err = register_netdevice(tun->dev);
28101da177e4SLinus Torvalds 		if (err < 0)
2811662ca437SJason Wang 			goto err_detach;
2812af668b3cSMichael S. Tsirkin 	}
2813980c9e8cSDavid Woodhouse 
2814eb0fb363SJason Wang 	netif_carrier_on(tun->dev);
28151da177e4SLinus Torvalds 
28166b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_set_iff\n");
28171da177e4SLinus Torvalds 
2818e35259a9SMax Krasnyansky 	/* Make sure persistent devices do not get stuck in
2819e35259a9SMax Krasnyansky 	 * xoff state.
2820e35259a9SMax Krasnyansky 	 */
2821e35259a9SMax Krasnyansky 	if (netif_running(tun->dev))
2822c8d68e6bSJason Wang 		netif_tx_wake_all_queues(tun->dev);
2823e35259a9SMax Krasnyansky 
28241da177e4SLinus Torvalds 	strcpy(ifr->ifr_name, tun->dev->name);
28251da177e4SLinus Torvalds 	return 0;
28261da177e4SLinus Torvalds 
2827662ca437SJason Wang err_detach:
2828662ca437SJason Wang 	tun_detach_all(dev);
2829ff244c6bSEric Dumazet 	/* register_netdevice() already called tun_free_netdev() */
2830ff244c6bSEric Dumazet 	goto err_free_dev;
2831ff244c6bSEric Dumazet 
2832662ca437SJason Wang err_free_flow:
2833662ca437SJason Wang 	tun_flow_uninit(tun);
2834662ca437SJason Wang 	security_tun_dev_free_security(tun->security);
2835608b9977SPaolo Abeni err_free_stat:
2836608b9977SPaolo Abeni 	free_percpu(tun->pcpu_stats);
28371da177e4SLinus Torvalds err_free_dev:
28381da177e4SLinus Torvalds 	free_netdev(dev);
28391da177e4SLinus Torvalds 	return err;
28401da177e4SLinus Torvalds }
28411da177e4SLinus Torvalds 
28429ce99cf6SRami Rosen static void tun_get_iff(struct net *net, struct tun_struct *tun,
2843876bfd4dSHerbert Xu 		       struct ifreq *ifr)
2844e3b99556SMark McLoughlin {
28456b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2846e3b99556SMark McLoughlin 
2847e3b99556SMark McLoughlin 	strcpy(ifr->ifr_name, tun->dev->name);
2848e3b99556SMark McLoughlin 
2849980c9e8cSDavid Woodhouse 	ifr->ifr_flags = tun_flags(tun);
2850e3b99556SMark McLoughlin 
2851e3b99556SMark McLoughlin }
2852e3b99556SMark McLoughlin 
28535228ddc9SRusty Russell /* This is like a cut-down ethtool ops, except done via tun fd so no
28545228ddc9SRusty Russell  * privs required. */
285588255375SMichał Mirosław static int set_offload(struct tun_struct *tun, unsigned long arg)
28565228ddc9SRusty Russell {
2857c8f44affSMichał Mirosław 	netdev_features_t features = 0;
28585228ddc9SRusty Russell 
28595228ddc9SRusty Russell 	if (arg & TUN_F_CSUM) {
286088255375SMichał Mirosław 		features |= NETIF_F_HW_CSUM;
28615228ddc9SRusty Russell 		arg &= ~TUN_F_CSUM;
28625228ddc9SRusty Russell 
28635228ddc9SRusty Russell 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
28645228ddc9SRusty Russell 			if (arg & TUN_F_TSO_ECN) {
28655228ddc9SRusty Russell 				features |= NETIF_F_TSO_ECN;
28665228ddc9SRusty Russell 				arg &= ~TUN_F_TSO_ECN;
28675228ddc9SRusty Russell 			}
28685228ddc9SRusty Russell 			if (arg & TUN_F_TSO4)
28695228ddc9SRusty Russell 				features |= NETIF_F_TSO;
28705228ddc9SRusty Russell 			if (arg & TUN_F_TSO6)
28715228ddc9SRusty Russell 				features |= NETIF_F_TSO6;
28725228ddc9SRusty Russell 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
28735228ddc9SRusty Russell 		}
28740c19f846SWillem de Bruijn 
28750c19f846SWillem de Bruijn 		arg &= ~TUN_F_UFO;
28765228ddc9SRusty Russell 	}
28775228ddc9SRusty Russell 
28785228ddc9SRusty Russell 	/* This gives the user a way to test for new features in future by
28795228ddc9SRusty Russell 	 * trying to set them. */
28805228ddc9SRusty Russell 	if (arg)
28815228ddc9SRusty Russell 		return -EINVAL;
28825228ddc9SRusty Russell 
288388255375SMichał Mirosław 	tun->set_features = features;
288409050957SYaroslav Isakov 	tun->dev->wanted_features &= ~TUN_USER_FEATURES;
288509050957SYaroslav Isakov 	tun->dev->wanted_features |= features;
288688255375SMichał Mirosław 	netdev_update_features(tun->dev);
28875228ddc9SRusty Russell 
28885228ddc9SRusty Russell 	return 0;
28895228ddc9SRusty Russell }
28905228ddc9SRusty Russell 
2891c8d68e6bSJason Wang static void tun_detach_filter(struct tun_struct *tun, int n)
2892c8d68e6bSJason Wang {
2893c8d68e6bSJason Wang 	int i;
2894c8d68e6bSJason Wang 	struct tun_file *tfile;
2895c8d68e6bSJason Wang 
2896c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
2897b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
28988ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
28998ced425eSHannes Frederic Sowa 		sk_detach_filter(tfile->socket.sk);
29008ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2901c8d68e6bSJason Wang 	}
2902c8d68e6bSJason Wang 
2903c8d68e6bSJason Wang 	tun->filter_attached = false;
2904c8d68e6bSJason Wang }
2905c8d68e6bSJason Wang 
2906c8d68e6bSJason Wang static int tun_attach_filter(struct tun_struct *tun)
2907c8d68e6bSJason Wang {
2908c8d68e6bSJason Wang 	int i, ret = 0;
2909c8d68e6bSJason Wang 	struct tun_file *tfile;
2910c8d68e6bSJason Wang 
2911c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2912b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
29138ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
29148ced425eSHannes Frederic Sowa 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
29158ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
2916c8d68e6bSJason Wang 		if (ret) {
2917c8d68e6bSJason Wang 			tun_detach_filter(tun, i);
2918c8d68e6bSJason Wang 			return ret;
2919c8d68e6bSJason Wang 		}
2920c8d68e6bSJason Wang 	}
2921c8d68e6bSJason Wang 
2922c8d68e6bSJason Wang 	tun->filter_attached = true;
2923c8d68e6bSJason Wang 	return ret;
2924c8d68e6bSJason Wang }
2925c8d68e6bSJason Wang 
2926c8d68e6bSJason Wang static void tun_set_sndbuf(struct tun_struct *tun)
2927c8d68e6bSJason Wang {
2928c8d68e6bSJason Wang 	struct tun_file *tfile;
2929c8d68e6bSJason Wang 	int i;
2930c8d68e6bSJason Wang 
2931c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
2932b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
2933c8d68e6bSJason Wang 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2934c8d68e6bSJason Wang 	}
2935c8d68e6bSJason Wang }
2936c8d68e6bSJason Wang 
2937cde8b15fSJason Wang static int tun_set_queue(struct file *file, struct ifreq *ifr)
2938cde8b15fSJason Wang {
2939cde8b15fSJason Wang 	struct tun_file *tfile = file->private_data;
2940cde8b15fSJason Wang 	struct tun_struct *tun;
2941cde8b15fSJason Wang 	int ret = 0;
2942cde8b15fSJason Wang 
2943cde8b15fSJason Wang 	rtnl_lock();
2944cde8b15fSJason Wang 
2945cde8b15fSJason Wang 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
29464008e97fSJason Wang 		tun = tfile->detached;
29475dbbaf2dSPaul Moore 		if (!tun) {
2948cde8b15fSJason Wang 			ret = -EINVAL;
29495dbbaf2dSPaul Moore 			goto unlock;
29505dbbaf2dSPaul Moore 		}
29515dbbaf2dSPaul Moore 		ret = security_tun_dev_attach_queue(tun->security);
29525dbbaf2dSPaul Moore 		if (ret < 0)
29535dbbaf2dSPaul Moore 			goto unlock;
2954af3fb24eSEric Dumazet 		ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
2955af3fb24eSEric Dumazet 				 tun->flags & IFF_NAPI_FRAGS);
29564008e97fSJason Wang 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2957b8deabd3SJason Wang 		tun = rtnl_dereference(tfile->tun);
295840630b82SMichael S. Tsirkin 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
29594008e97fSJason Wang 			ret = -EINVAL;
2960cde8b15fSJason Wang 		else
29614008e97fSJason Wang 			__tun_detach(tfile, false);
29624008e97fSJason Wang 	} else
2963cde8b15fSJason Wang 		ret = -EINVAL;
2964cde8b15fSJason Wang 
296583c1f36fSSabrina Dubroca 	if (ret >= 0)
296683c1f36fSSabrina Dubroca 		netdev_state_change(tun->dev);
296783c1f36fSSabrina Dubroca 
29685dbbaf2dSPaul Moore unlock:
2969cde8b15fSJason Wang 	rtnl_unlock();
2970cde8b15fSJason Wang 	return ret;
2971cde8b15fSJason Wang }
2972cde8b15fSJason Wang 
2973cd5681d7SJason Wang static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog **prog_p,
2974cd5681d7SJason Wang 			void __user *data)
297596f84061SJason Wang {
297696f84061SJason Wang 	struct bpf_prog *prog;
297796f84061SJason Wang 	int fd;
297896f84061SJason Wang 
297996f84061SJason Wang 	if (copy_from_user(&fd, data, sizeof(fd)))
298096f84061SJason Wang 		return -EFAULT;
298196f84061SJason Wang 
298296f84061SJason Wang 	if (fd == -1) {
298396f84061SJason Wang 		prog = NULL;
298496f84061SJason Wang 	} else {
298596f84061SJason Wang 		prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
298696f84061SJason Wang 		if (IS_ERR(prog))
298796f84061SJason Wang 			return PTR_ERR(prog);
298896f84061SJason Wang 	}
298996f84061SJason Wang 
2990cd5681d7SJason Wang 	return __tun_set_ebpf(tun, prog_p, prog);
299196f84061SJason Wang }
299296f84061SJason Wang 
299350857e2aSArnd Bergmann static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
299450857e2aSArnd Bergmann 			    unsigned long arg, int ifreq_len)
29951da177e4SLinus Torvalds {
299636b50babSEric W. Biederman 	struct tun_file *tfile = file->private_data;
2997f663706aSKirill Tkhai 	struct net *net = sock_net(&tfile->sk);
2998631ab46bSEric W. Biederman 	struct tun_struct *tun;
29991da177e4SLinus Torvalds 	void __user* argp = (void __user*)arg;
30001da177e4SLinus Torvalds 	struct ifreq ifr;
30010625c883SEric W. Biederman 	kuid_t owner;
30020625c883SEric W. Biederman 	kgid_t group;
300333dccbb0SHerbert Xu 	int sndbuf;
3004d9d52b51SMichael S. Tsirkin 	int vnet_hdr_sz;
3005fb7589a1SPavel Emelyanov 	unsigned int ifindex;
30061cf8e410SMichael S. Tsirkin 	int le;
3007f271b2ccSMax Krasnyansky 	int ret;
300883c1f36fSSabrina Dubroca 	bool do_notify = false;
30091da177e4SLinus Torvalds 
3010f2780d6dSKirill Tkhai 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
3011f2780d6dSKirill Tkhai 	    (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
301250857e2aSArnd Bergmann 		if (copy_from_user(&ifr, argp, ifreq_len))
30131da177e4SLinus Torvalds 			return -EFAULT;
30148bbb1813SDavid S. Miller 	} else {
3015a117dacdSMathias Krause 		memset(&ifr, 0, sizeof(ifr));
30168bbb1813SDavid S. Miller 	}
3017631ab46bSEric W. Biederman 	if (cmd == TUNGETFEATURES) {
3018631ab46bSEric W. Biederman 		/* Currently this just means: "what IFF flags are valid?".
3019631ab46bSEric W. Biederman 		 * This is needed because we never checked for invalid flags on
3020031f5e03SMichael S. Tsirkin 		 * TUNSETIFF.
3021031f5e03SMichael S. Tsirkin 		 */
3022031f5e03SMichael S. Tsirkin 		return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
3023631ab46bSEric W. Biederman 				(unsigned int __user*)argp);
3024f663706aSKirill Tkhai 	} else if (cmd == TUNSETQUEUE) {
3025cde8b15fSJason Wang 		return tun_set_queue(file, &ifr);
3026f663706aSKirill Tkhai 	} else if (cmd == SIOCGSKNS) {
3027f663706aSKirill Tkhai 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3028f663706aSKirill Tkhai 			return -EPERM;
3029f663706aSKirill Tkhai 		return open_related_ns(&net->ns, get_net_ns);
3030f663706aSKirill Tkhai 	}
3031631ab46bSEric W. Biederman 
3032c8d68e6bSJason Wang 	ret = 0;
3033876bfd4dSHerbert Xu 	rtnl_lock();
3034876bfd4dSHerbert Xu 
30359484dc74Syuan linyu 	tun = tun_get(tfile);
30360f16bc13SGao Feng 	if (cmd == TUNSETIFF) {
30370f16bc13SGao Feng 		ret = -EEXIST;
30380f16bc13SGao Feng 		if (tun)
30390f16bc13SGao Feng 			goto unlock;
30400f16bc13SGao Feng 
30411da177e4SLinus Torvalds 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
30421da177e4SLinus Torvalds 
3043f2780d6dSKirill Tkhai 		ret = tun_set_iff(net, file, &ifr);
30441da177e4SLinus Torvalds 
3045876bfd4dSHerbert Xu 		if (ret)
3046876bfd4dSHerbert Xu 			goto unlock;
30471da177e4SLinus Torvalds 
304850857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3049876bfd4dSHerbert Xu 			ret = -EFAULT;
3050876bfd4dSHerbert Xu 		goto unlock;
30511da177e4SLinus Torvalds 	}
3052fb7589a1SPavel Emelyanov 	if (cmd == TUNSETIFINDEX) {
3053fb7589a1SPavel Emelyanov 		ret = -EPERM;
3054fb7589a1SPavel Emelyanov 		if (tun)
3055fb7589a1SPavel Emelyanov 			goto unlock;
3056fb7589a1SPavel Emelyanov 
3057fb7589a1SPavel Emelyanov 		ret = -EFAULT;
3058fb7589a1SPavel Emelyanov 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
3059fb7589a1SPavel Emelyanov 			goto unlock;
3060fb7589a1SPavel Emelyanov 
3061fb7589a1SPavel Emelyanov 		ret = 0;
3062fb7589a1SPavel Emelyanov 		tfile->ifindex = ifindex;
3063fb7589a1SPavel Emelyanov 		goto unlock;
3064fb7589a1SPavel Emelyanov 	}
30651da177e4SLinus Torvalds 
3066876bfd4dSHerbert Xu 	ret = -EBADFD;
30671da177e4SLinus Torvalds 	if (!tun)
3068876bfd4dSHerbert Xu 		goto unlock;
30691da177e4SLinus Torvalds 
30701e588338SJason Wang 	tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
30711da177e4SLinus Torvalds 
3072631ab46bSEric W. Biederman 	ret = 0;
30731da177e4SLinus Torvalds 	switch (cmd) {
3074e3b99556SMark McLoughlin 	case TUNGETIFF:
30759ce99cf6SRami Rosen 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
3076e3b99556SMark McLoughlin 
30773d407a80SPavel Emelyanov 		if (tfile->detached)
30783d407a80SPavel Emelyanov 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
3079849c9b6fSPavel Emelyanov 		if (!tfile->socket.sk->sk_filter)
3080849c9b6fSPavel Emelyanov 			ifr.ifr_flags |= IFF_NOFILTER;
30813d407a80SPavel Emelyanov 
308250857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3083631ab46bSEric W. Biederman 			ret = -EFAULT;
3084e3b99556SMark McLoughlin 		break;
3085e3b99556SMark McLoughlin 
30861da177e4SLinus Torvalds 	case TUNSETNOCSUM:
30871da177e4SLinus Torvalds 		/* Disable/Enable checksum */
30881da177e4SLinus Torvalds 
308988255375SMichał Mirosław 		/* [unimplemented] */
309088255375SMichał Mirosław 		tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
30916b8a66eeSJoe Perches 			  arg ? "disabled" : "enabled");
30921da177e4SLinus Torvalds 		break;
30931da177e4SLinus Torvalds 
30941da177e4SLinus Torvalds 	case TUNSETPERSIST:
309554f968d6SJason Wang 		/* Disable/Enable persist mode. Keep an extra reference to the
309654f968d6SJason Wang 		 * module to prevent the module being unprobed.
309754f968d6SJason Wang 		 */
309840630b82SMichael S. Tsirkin 		if (arg && !(tun->flags & IFF_PERSIST)) {
309940630b82SMichael S. Tsirkin 			tun->flags |= IFF_PERSIST;
310054f968d6SJason Wang 			__module_get(THIS_MODULE);
310183c1f36fSSabrina Dubroca 			do_notify = true;
3102dd38bd85SJason Wang 		}
310340630b82SMichael S. Tsirkin 		if (!arg && (tun->flags & IFF_PERSIST)) {
310440630b82SMichael S. Tsirkin 			tun->flags &= ~IFF_PERSIST;
310554f968d6SJason Wang 			module_put(THIS_MODULE);
310683c1f36fSSabrina Dubroca 			do_notify = true;
310754f968d6SJason Wang 		}
31081da177e4SLinus Torvalds 
31096b8a66eeSJoe Perches 		tun_debug(KERN_INFO, tun, "persist %s\n",
31106b8a66eeSJoe Perches 			  arg ? "enabled" : "disabled");
31111da177e4SLinus Torvalds 		break;
31121da177e4SLinus Torvalds 
31131da177e4SLinus Torvalds 	case TUNSETOWNER:
31141da177e4SLinus Torvalds 		/* Set owner of the device */
31150625c883SEric W. Biederman 		owner = make_kuid(current_user_ns(), arg);
31160625c883SEric W. Biederman 		if (!uid_valid(owner)) {
31170625c883SEric W. Biederman 			ret = -EINVAL;
31180625c883SEric W. Biederman 			break;
31190625c883SEric W. Biederman 		}
31200625c883SEric W. Biederman 		tun->owner = owner;
312183c1f36fSSabrina Dubroca 		do_notify = true;
31221e588338SJason Wang 		tun_debug(KERN_INFO, tun, "owner set to %u\n",
31230625c883SEric W. Biederman 			  from_kuid(&init_user_ns, tun->owner));
31241da177e4SLinus Torvalds 		break;
31251da177e4SLinus Torvalds 
31268c644623SGuido Guenther 	case TUNSETGROUP:
31278c644623SGuido Guenther 		/* Set group of the device */
31280625c883SEric W. Biederman 		group = make_kgid(current_user_ns(), arg);
31290625c883SEric W. Biederman 		if (!gid_valid(group)) {
31300625c883SEric W. Biederman 			ret = -EINVAL;
31310625c883SEric W. Biederman 			break;
31320625c883SEric W. Biederman 		}
31330625c883SEric W. Biederman 		tun->group = group;
313483c1f36fSSabrina Dubroca 		do_notify = true;
31351e588338SJason Wang 		tun_debug(KERN_INFO, tun, "group set to %u\n",
31360625c883SEric W. Biederman 			  from_kgid(&init_user_ns, tun->group));
31378c644623SGuido Guenther 		break;
31388c644623SGuido Guenther 
3139ff4cc3acSMike Kershaw 	case TUNSETLINK:
3140ff4cc3acSMike Kershaw 		/* Only allow setting the type when the interface is down */
3141ff4cc3acSMike Kershaw 		if (tun->dev->flags & IFF_UP) {
31426b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun,
31436b8a66eeSJoe Perches 				  "Linktype set failed because interface is up\n");
314448abfe05SDavid S. Miller 			ret = -EBUSY;
3145ff4cc3acSMike Kershaw 		} else {
3146ff4cc3acSMike Kershaw 			tun->dev->type = (int) arg;
31476b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun, "linktype set to %d\n",
31486b8a66eeSJoe Perches 				  tun->dev->type);
314948abfe05SDavid S. Miller 			ret = 0;
3150ff4cc3acSMike Kershaw 		}
3151631ab46bSEric W. Biederman 		break;
3152ff4cc3acSMike Kershaw 
31531da177e4SLinus Torvalds #ifdef TUN_DEBUG
31541da177e4SLinus Torvalds 	case TUNSETDEBUG:
31551da177e4SLinus Torvalds 		tun->debug = arg;
31561da177e4SLinus Torvalds 		break;
31571da177e4SLinus Torvalds #endif
31585228ddc9SRusty Russell 	case TUNSETOFFLOAD:
315988255375SMichał Mirosław 		ret = set_offload(tun, arg);
3160631ab46bSEric W. Biederman 		break;
31615228ddc9SRusty Russell 
3162f271b2ccSMax Krasnyansky 	case TUNSETTXFILTER:
3163f271b2ccSMax Krasnyansky 		/* Can be set only for TAPs */
3164631ab46bSEric W. Biederman 		ret = -EINVAL;
316540630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3166631ab46bSEric W. Biederman 			break;
3167c0e5a8c2SHarvey Harrison 		ret = update_filter(&tun->txflt, (void __user *)arg);
3168631ab46bSEric W. Biederman 		break;
31691da177e4SLinus Torvalds 
31701da177e4SLinus Torvalds 	case SIOCGIFHWADDR:
3171b595076aSUwe Kleine-König 		/* Get hw address */
3172f271b2ccSMax Krasnyansky 		memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
3173f271b2ccSMax Krasnyansky 		ifr.ifr_hwaddr.sa_family = tun->dev->type;
317450857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
3175631ab46bSEric W. Biederman 			ret = -EFAULT;
3176631ab46bSEric W. Biederman 		break;
31771da177e4SLinus Torvalds 
31781da177e4SLinus Torvalds 	case SIOCSIFHWADDR:
3179f271b2ccSMax Krasnyansky 		/* Set hw address */
31806b8a66eeSJoe Perches 		tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
31816b8a66eeSJoe Perches 			  ifr.ifr_hwaddr.sa_data);
318240102371SKim B. Heino 
318340102371SKim B. Heino 		ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
3184631ab46bSEric W. Biederman 		break;
318533dccbb0SHerbert Xu 
318633dccbb0SHerbert Xu 	case TUNGETSNDBUF:
318754f968d6SJason Wang 		sndbuf = tfile->socket.sk->sk_sndbuf;
318833dccbb0SHerbert Xu 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
318933dccbb0SHerbert Xu 			ret = -EFAULT;
319033dccbb0SHerbert Xu 		break;
319133dccbb0SHerbert Xu 
319233dccbb0SHerbert Xu 	case TUNSETSNDBUF:
319333dccbb0SHerbert Xu 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
319433dccbb0SHerbert Xu 			ret = -EFAULT;
319533dccbb0SHerbert Xu 			break;
319633dccbb0SHerbert Xu 		}
319793161922SCraig Gallek 		if (sndbuf <= 0) {
319893161922SCraig Gallek 			ret = -EINVAL;
319993161922SCraig Gallek 			break;
320093161922SCraig Gallek 		}
320133dccbb0SHerbert Xu 
3202c8d68e6bSJason Wang 		tun->sndbuf = sndbuf;
3203c8d68e6bSJason Wang 		tun_set_sndbuf(tun);
320433dccbb0SHerbert Xu 		break;
320533dccbb0SHerbert Xu 
3206d9d52b51SMichael S. Tsirkin 	case TUNGETVNETHDRSZ:
3207d9d52b51SMichael S. Tsirkin 		vnet_hdr_sz = tun->vnet_hdr_sz;
3208d9d52b51SMichael S. Tsirkin 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
3209d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
3210d9d52b51SMichael S. Tsirkin 		break;
3211d9d52b51SMichael S. Tsirkin 
3212d9d52b51SMichael S. Tsirkin 	case TUNSETVNETHDRSZ:
3213d9d52b51SMichael S. Tsirkin 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
3214d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
3215d9d52b51SMichael S. Tsirkin 			break;
3216d9d52b51SMichael S. Tsirkin 		}
3217d9d52b51SMichael S. Tsirkin 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
3218d9d52b51SMichael S. Tsirkin 			ret = -EINVAL;
3219d9d52b51SMichael S. Tsirkin 			break;
3220d9d52b51SMichael S. Tsirkin 		}
3221d9d52b51SMichael S. Tsirkin 
3222d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = vnet_hdr_sz;
3223d9d52b51SMichael S. Tsirkin 		break;
3224d9d52b51SMichael S. Tsirkin 
32251cf8e410SMichael S. Tsirkin 	case TUNGETVNETLE:
32261cf8e410SMichael S. Tsirkin 		le = !!(tun->flags & TUN_VNET_LE);
32271cf8e410SMichael S. Tsirkin 		if (put_user(le, (int __user *)argp))
32281cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
32291cf8e410SMichael S. Tsirkin 		break;
32301cf8e410SMichael S. Tsirkin 
32311cf8e410SMichael S. Tsirkin 	case TUNSETVNETLE:
32321cf8e410SMichael S. Tsirkin 		if (get_user(le, (int __user *)argp)) {
32331cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
32341cf8e410SMichael S. Tsirkin 			break;
32351cf8e410SMichael S. Tsirkin 		}
32361cf8e410SMichael S. Tsirkin 		if (le)
32371cf8e410SMichael S. Tsirkin 			tun->flags |= TUN_VNET_LE;
32381cf8e410SMichael S. Tsirkin 		else
32391cf8e410SMichael S. Tsirkin 			tun->flags &= ~TUN_VNET_LE;
32401cf8e410SMichael S. Tsirkin 		break;
32411cf8e410SMichael S. Tsirkin 
32428b8e658bSGreg Kurz 	case TUNGETVNETBE:
32438b8e658bSGreg Kurz 		ret = tun_get_vnet_be(tun, argp);
32448b8e658bSGreg Kurz 		break;
32458b8e658bSGreg Kurz 
32468b8e658bSGreg Kurz 	case TUNSETVNETBE:
32478b8e658bSGreg Kurz 		ret = tun_set_vnet_be(tun, argp);
32488b8e658bSGreg Kurz 		break;
32498b8e658bSGreg Kurz 
325099405162SMichael S. Tsirkin 	case TUNATTACHFILTER:
325199405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
325299405162SMichael S. Tsirkin 		ret = -EINVAL;
325340630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
325499405162SMichael S. Tsirkin 			break;
325599405162SMichael S. Tsirkin 		ret = -EFAULT;
325654f968d6SJason Wang 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
325799405162SMichael S. Tsirkin 			break;
325899405162SMichael S. Tsirkin 
3259c8d68e6bSJason Wang 		ret = tun_attach_filter(tun);
326099405162SMichael S. Tsirkin 		break;
326199405162SMichael S. Tsirkin 
326299405162SMichael S. Tsirkin 	case TUNDETACHFILTER:
326399405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
326499405162SMichael S. Tsirkin 		ret = -EINVAL;
326540630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
326699405162SMichael S. Tsirkin 			break;
3267c8d68e6bSJason Wang 		ret = 0;
3268c8d68e6bSJason Wang 		tun_detach_filter(tun, tun->numqueues);
326999405162SMichael S. Tsirkin 		break;
327099405162SMichael S. Tsirkin 
327176975e9cSPavel Emelyanov 	case TUNGETFILTER:
327276975e9cSPavel Emelyanov 		ret = -EINVAL;
327340630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
327476975e9cSPavel Emelyanov 			break;
327576975e9cSPavel Emelyanov 		ret = -EFAULT;
327676975e9cSPavel Emelyanov 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
327776975e9cSPavel Emelyanov 			break;
327876975e9cSPavel Emelyanov 		ret = 0;
327976975e9cSPavel Emelyanov 		break;
328076975e9cSPavel Emelyanov 
328196f84061SJason Wang 	case TUNSETSTEERINGEBPF:
3282cd5681d7SJason Wang 		ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
328396f84061SJason Wang 		break;
328496f84061SJason Wang 
3285aff3d70aSJason Wang 	case TUNSETFILTEREBPF:
3286aff3d70aSJason Wang 		ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3287aff3d70aSJason Wang 		break;
3288aff3d70aSJason Wang 
32891da177e4SLinus Torvalds 	default:
3290631ab46bSEric W. Biederman 		ret = -EINVAL;
3291631ab46bSEric W. Biederman 		break;
3292ee289b64SJoe Perches 	}
32931da177e4SLinus Torvalds 
329483c1f36fSSabrina Dubroca 	if (do_notify)
329583c1f36fSSabrina Dubroca 		netdev_state_change(tun->dev);
329683c1f36fSSabrina Dubroca 
3297876bfd4dSHerbert Xu unlock:
3298876bfd4dSHerbert Xu 	rtnl_unlock();
3299876bfd4dSHerbert Xu 	if (tun)
3300631ab46bSEric W. Biederman 		tun_put(tun);
3301631ab46bSEric W. Biederman 	return ret;
33021da177e4SLinus Torvalds }
33031da177e4SLinus Torvalds 
330450857e2aSArnd Bergmann static long tun_chr_ioctl(struct file *file,
330550857e2aSArnd Bergmann 			  unsigned int cmd, unsigned long arg)
330650857e2aSArnd Bergmann {
330750857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
330850857e2aSArnd Bergmann }
330950857e2aSArnd Bergmann 
331050857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
331150857e2aSArnd Bergmann static long tun_chr_compat_ioctl(struct file *file,
331250857e2aSArnd Bergmann 			 unsigned int cmd, unsigned long arg)
331350857e2aSArnd Bergmann {
331450857e2aSArnd Bergmann 	switch (cmd) {
331550857e2aSArnd Bergmann 	case TUNSETIFF:
331650857e2aSArnd Bergmann 	case TUNGETIFF:
331750857e2aSArnd Bergmann 	case TUNSETTXFILTER:
331850857e2aSArnd Bergmann 	case TUNGETSNDBUF:
331950857e2aSArnd Bergmann 	case TUNSETSNDBUF:
332050857e2aSArnd Bergmann 	case SIOCGIFHWADDR:
332150857e2aSArnd Bergmann 	case SIOCSIFHWADDR:
332250857e2aSArnd Bergmann 		arg = (unsigned long)compat_ptr(arg);
332350857e2aSArnd Bergmann 		break;
332450857e2aSArnd Bergmann 	default:
332550857e2aSArnd Bergmann 		arg = (compat_ulong_t)arg;
332650857e2aSArnd Bergmann 		break;
332750857e2aSArnd Bergmann 	}
332850857e2aSArnd Bergmann 
332950857e2aSArnd Bergmann 	/*
333050857e2aSArnd Bergmann 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
333150857e2aSArnd Bergmann 	 * the end of that structure. All fields that are used in this
333250857e2aSArnd Bergmann 	 * driver are compatible though, we don't need to convert the
333350857e2aSArnd Bergmann 	 * contents.
333450857e2aSArnd Bergmann 	 */
333550857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
333650857e2aSArnd Bergmann }
333750857e2aSArnd Bergmann #endif /* CONFIG_COMPAT */
333850857e2aSArnd Bergmann 
33391da177e4SLinus Torvalds static int tun_chr_fasync(int fd, struct file *file, int on)
33401da177e4SLinus Torvalds {
334154f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
33421da177e4SLinus Torvalds 	int ret;
33431da177e4SLinus Torvalds 
334454f968d6SJason Wang 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
33459d319522SJonathan Corbet 		goto out;
33461da177e4SLinus Torvalds 
33471da177e4SLinus Torvalds 	if (on) {
334801919134SEric W. Biederman 		__f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
334954f968d6SJason Wang 		tfile->flags |= TUN_FASYNC;
33501da177e4SLinus Torvalds 	} else
335154f968d6SJason Wang 		tfile->flags &= ~TUN_FASYNC;
33529d319522SJonathan Corbet 	ret = 0;
33539d319522SJonathan Corbet out:
33549d319522SJonathan Corbet 	return ret;
33551da177e4SLinus Torvalds }
33561da177e4SLinus Torvalds 
33571da177e4SLinus Torvalds static int tun_chr_open(struct inode *inode, struct file * file)
33581da177e4SLinus Torvalds {
3359140e807dSEric W. Biederman 	struct net *net = current->nsproxy->net_ns;
3360631ab46bSEric W. Biederman 	struct tun_file *tfile;
3361deed49fbSThomas Gleixner 
33626b8a66eeSJoe Perches 	DBG1(KERN_INFO, "tunX: tun_chr_open\n");
3363631ab46bSEric W. Biederman 
3364140e807dSEric W. Biederman 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
336511aa9c28SEric W. Biederman 					    &tun_proto, 0);
3366631ab46bSEric W. Biederman 	if (!tfile)
3367631ab46bSEric W. Biederman 		return -ENOMEM;
3368b196d88aSJason Wang 	if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
3369b196d88aSJason Wang 		sk_free(&tfile->sk);
3370b196d88aSJason Wang 		return -ENOMEM;
3371b196d88aSJason Wang 	}
3372b196d88aSJason Wang 
3373c7256f57SEric Dumazet 	mutex_init(&tfile->napi_mutex);
3374c956674bSMonam Agarwal 	RCU_INIT_POINTER(tfile->tun, NULL);
337554f968d6SJason Wang 	tfile->flags = 0;
3376fb7589a1SPavel Emelyanov 	tfile->ifindex = 0;
337754f968d6SJason Wang 
337854f968d6SJason Wang 	init_waitqueue_head(&tfile->wq.wait);
33799e641bdcSXi Wang 	RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
338054f968d6SJason Wang 
338154f968d6SJason Wang 	tfile->socket.file = file;
338254f968d6SJason Wang 	tfile->socket.ops = &tun_socket_ops;
338354f968d6SJason Wang 
338454f968d6SJason Wang 	sock_init_data(&tfile->socket, &tfile->sk);
338554f968d6SJason Wang 
338654f968d6SJason Wang 	tfile->sk.sk_write_space = tun_sock_write_space;
338754f968d6SJason Wang 	tfile->sk.sk_sndbuf = INT_MAX;
338854f968d6SJason Wang 
3389631ab46bSEric W. Biederman 	file->private_data = tfile;
33904008e97fSJason Wang 	INIT_LIST_HEAD(&tfile->next);
339154f968d6SJason Wang 
339219a6afb2SJason Wang 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
339319a6afb2SJason Wang 
33941da177e4SLinus Torvalds 	return 0;
33951da177e4SLinus Torvalds }
33961da177e4SLinus Torvalds 
33971da177e4SLinus Torvalds static int tun_chr_close(struct inode *inode, struct file *file)
33981da177e4SLinus Torvalds {
3399631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
34001da177e4SLinus Torvalds 
3401c8d68e6bSJason Wang 	tun_detach(tfile, true);
34021da177e4SLinus Torvalds 
34031da177e4SLinus Torvalds 	return 0;
34041da177e4SLinus Torvalds }
34051da177e4SLinus Torvalds 
340693e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
34079484dc74Syuan linyu static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
340893e14b6dSMasatake YAMATO {
34099484dc74Syuan linyu 	struct tun_file *tfile = file->private_data;
341093e14b6dSMasatake YAMATO 	struct tun_struct *tun;
341193e14b6dSMasatake YAMATO 	struct ifreq ifr;
341293e14b6dSMasatake YAMATO 
341393e14b6dSMasatake YAMATO 	memset(&ifr, 0, sizeof(ifr));
341493e14b6dSMasatake YAMATO 
341593e14b6dSMasatake YAMATO 	rtnl_lock();
34169484dc74Syuan linyu 	tun = tun_get(tfile);
341793e14b6dSMasatake YAMATO 	if (tun)
341893e14b6dSMasatake YAMATO 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
341993e14b6dSMasatake YAMATO 	rtnl_unlock();
342093e14b6dSMasatake YAMATO 
342193e14b6dSMasatake YAMATO 	if (tun)
342293e14b6dSMasatake YAMATO 		tun_put(tun);
342393e14b6dSMasatake YAMATO 
3424a3816ab0SJoe Perches 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
342593e14b6dSMasatake YAMATO }
342693e14b6dSMasatake YAMATO #endif
342793e14b6dSMasatake YAMATO 
3428d54b1fdbSArjan van de Ven static const struct file_operations tun_fops = {
34291da177e4SLinus Torvalds 	.owner	= THIS_MODULE,
34301da177e4SLinus Torvalds 	.llseek = no_llseek,
34319b067034SAl Viro 	.read_iter  = tun_chr_read_iter,
3432f5ff53b4SAl Viro 	.write_iter = tun_chr_write_iter,
34331da177e4SLinus Torvalds 	.poll	= tun_chr_poll,
3434876bfd4dSHerbert Xu 	.unlocked_ioctl	= tun_chr_ioctl,
343550857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
343650857e2aSArnd Bergmann 	.compat_ioctl = tun_chr_compat_ioctl,
343750857e2aSArnd Bergmann #endif
34381da177e4SLinus Torvalds 	.open	= tun_chr_open,
34391da177e4SLinus Torvalds 	.release = tun_chr_close,
344093e14b6dSMasatake YAMATO 	.fasync = tun_chr_fasync,
344193e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
344293e14b6dSMasatake YAMATO 	.show_fdinfo = tun_chr_show_fdinfo,
344393e14b6dSMasatake YAMATO #endif
34441da177e4SLinus Torvalds };
34451da177e4SLinus Torvalds 
34461da177e4SLinus Torvalds static struct miscdevice tun_miscdev = {
34471da177e4SLinus Torvalds 	.minor = TUN_MINOR,
34481da177e4SLinus Torvalds 	.name = "tun",
3449e454cea2SKay Sievers 	.nodename = "net/tun",
34501da177e4SLinus Torvalds 	.fops = &tun_fops,
34511da177e4SLinus Torvalds };
34521da177e4SLinus Torvalds 
34531da177e4SLinus Torvalds /* ethtool interface */
34541da177e4SLinus Torvalds 
34554e24f2ddSChas Williams static void tun_default_link_ksettings(struct net_device *dev,
345629ccc49dSPhilippe Reynes 				       struct ethtool_link_ksettings *cmd)
34571da177e4SLinus Torvalds {
345829ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
345929ccc49dSPhilippe Reynes 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
346029ccc49dSPhilippe Reynes 	cmd->base.speed		= SPEED_10;
346129ccc49dSPhilippe Reynes 	cmd->base.duplex	= DUPLEX_FULL;
346229ccc49dSPhilippe Reynes 	cmd->base.port		= PORT_TP;
346329ccc49dSPhilippe Reynes 	cmd->base.phy_address	= 0;
346429ccc49dSPhilippe Reynes 	cmd->base.autoneg	= AUTONEG_DISABLE;
34654e24f2ddSChas Williams }
34664e24f2ddSChas Williams 
34674e24f2ddSChas Williams static int tun_get_link_ksettings(struct net_device *dev,
34684e24f2ddSChas Williams 				  struct ethtool_link_ksettings *cmd)
34694e24f2ddSChas Williams {
34704e24f2ddSChas Williams 	struct tun_struct *tun = netdev_priv(dev);
34714e24f2ddSChas Williams 
34724e24f2ddSChas Williams 	memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
34734e24f2ddSChas Williams 	return 0;
34744e24f2ddSChas Williams }
34754e24f2ddSChas Williams 
34764e24f2ddSChas Williams static int tun_set_link_ksettings(struct net_device *dev,
34774e24f2ddSChas Williams 				  const struct ethtool_link_ksettings *cmd)
34784e24f2ddSChas Williams {
34794e24f2ddSChas Williams 	struct tun_struct *tun = netdev_priv(dev);
34804e24f2ddSChas Williams 
34814e24f2ddSChas Williams 	memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
34821da177e4SLinus Torvalds 	return 0;
34831da177e4SLinus Torvalds }
34841da177e4SLinus Torvalds 
34851da177e4SLinus Torvalds static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
34861da177e4SLinus Torvalds {
34871da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
34881da177e4SLinus Torvalds 
348933a5ba14SRick Jones 	strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
349033a5ba14SRick Jones 	strlcpy(info->version, DRV_VERSION, sizeof(info->version));
34911da177e4SLinus Torvalds 
34921da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
349340630b82SMichael S. Tsirkin 	case IFF_TUN:
349433a5ba14SRick Jones 		strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
34951da177e4SLinus Torvalds 		break;
349640630b82SMichael S. Tsirkin 	case IFF_TAP:
349733a5ba14SRick Jones 		strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
34981da177e4SLinus Torvalds 		break;
34991da177e4SLinus Torvalds 	}
35001da177e4SLinus Torvalds }
35011da177e4SLinus Torvalds 
35021da177e4SLinus Torvalds static u32 tun_get_msglevel(struct net_device *dev)
35031da177e4SLinus Torvalds {
35041da177e4SLinus Torvalds #ifdef TUN_DEBUG
35051da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
35061da177e4SLinus Torvalds 	return tun->debug;
35071da177e4SLinus Torvalds #else
35081da177e4SLinus Torvalds 	return -EOPNOTSUPP;
35091da177e4SLinus Torvalds #endif
35101da177e4SLinus Torvalds }
35111da177e4SLinus Torvalds 
35121da177e4SLinus Torvalds static void tun_set_msglevel(struct net_device *dev, u32 value)
35131da177e4SLinus Torvalds {
35141da177e4SLinus Torvalds #ifdef TUN_DEBUG
35151da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
35161da177e4SLinus Torvalds 	tun->debug = value;
35171da177e4SLinus Torvalds #endif
35181da177e4SLinus Torvalds }
35191da177e4SLinus Torvalds 
35205503fcecSJason Wang static int tun_get_coalesce(struct net_device *dev,
35215503fcecSJason Wang 			    struct ethtool_coalesce *ec)
35225503fcecSJason Wang {
35235503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
35245503fcecSJason Wang 
35255503fcecSJason Wang 	ec->rx_max_coalesced_frames = tun->rx_batched;
35265503fcecSJason Wang 
35275503fcecSJason Wang 	return 0;
35285503fcecSJason Wang }
35295503fcecSJason Wang 
35305503fcecSJason Wang static int tun_set_coalesce(struct net_device *dev,
35315503fcecSJason Wang 			    struct ethtool_coalesce *ec)
35325503fcecSJason Wang {
35335503fcecSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
35345503fcecSJason Wang 
35355503fcecSJason Wang 	if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
35365503fcecSJason Wang 		tun->rx_batched = NAPI_POLL_WEIGHT;
35375503fcecSJason Wang 	else
35385503fcecSJason Wang 		tun->rx_batched = ec->rx_max_coalesced_frames;
35395503fcecSJason Wang 
35405503fcecSJason Wang 	return 0;
35415503fcecSJason Wang }
35425503fcecSJason Wang 
35437282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops = {
35441da177e4SLinus Torvalds 	.get_drvinfo	= tun_get_drvinfo,
35451da177e4SLinus Torvalds 	.get_msglevel	= tun_get_msglevel,
35461da177e4SLinus Torvalds 	.set_msglevel	= tun_set_msglevel,
3547bee31369SNolan Leake 	.get_link	= ethtool_op_get_link,
3548eda29772SRichard Cochran 	.get_ts_info	= ethtool_op_get_ts_info,
35495503fcecSJason Wang 	.get_coalesce   = tun_get_coalesce,
35505503fcecSJason Wang 	.set_coalesce   = tun_set_coalesce,
355129ccc49dSPhilippe Reynes 	.get_link_ksettings = tun_get_link_ksettings,
35524e24f2ddSChas Williams 	.set_link_ksettings = tun_set_link_ksettings,
35531da177e4SLinus Torvalds };
35541da177e4SLinus Torvalds 
35551576d986SJason Wang static int tun_queue_resize(struct tun_struct *tun)
35561576d986SJason Wang {
35571576d986SJason Wang 	struct net_device *dev = tun->dev;
35581576d986SJason Wang 	struct tun_file *tfile;
35595990a305SJason Wang 	struct ptr_ring **rings;
35601576d986SJason Wang 	int n = tun->numqueues + tun->numdisabled;
35611576d986SJason Wang 	int ret, i;
35621576d986SJason Wang 
35635990a305SJason Wang 	rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
35645990a305SJason Wang 	if (!rings)
35651576d986SJason Wang 		return -ENOMEM;
35661576d986SJason Wang 
35671576d986SJason Wang 	for (i = 0; i < tun->numqueues; i++) {
35681576d986SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
35695990a305SJason Wang 		rings[i] = &tfile->tx_ring;
35701576d986SJason Wang 	}
35711576d986SJason Wang 	list_for_each_entry(tfile, &tun->disabled, next)
35725990a305SJason Wang 		rings[i++] = &tfile->tx_ring;
35731576d986SJason Wang 
35745990a305SJason Wang 	ret = ptr_ring_resize_multiple(rings, n,
35755990a305SJason Wang 				       dev->tx_queue_len, GFP_KERNEL,
3576fc72d1d5SJason Wang 				       tun_ptr_free);
35771576d986SJason Wang 
35785990a305SJason Wang 	kfree(rings);
35791576d986SJason Wang 	return ret;
35801576d986SJason Wang }
35811576d986SJason Wang 
35821576d986SJason Wang static int tun_device_event(struct notifier_block *unused,
35831576d986SJason Wang 			    unsigned long event, void *ptr)
35841576d986SJason Wang {
35851576d986SJason Wang 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
35861576d986SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
35871576d986SJason Wang 
358886dfb4acSCraig Gallek 	if (dev->rtnl_link_ops != &tun_link_ops)
358986dfb4acSCraig Gallek 		return NOTIFY_DONE;
359086dfb4acSCraig Gallek 
35911576d986SJason Wang 	switch (event) {
35921576d986SJason Wang 	case NETDEV_CHANGE_TX_QUEUE_LEN:
35931576d986SJason Wang 		if (tun_queue_resize(tun))
35941576d986SJason Wang 			return NOTIFY_BAD;
35951576d986SJason Wang 		break;
35961576d986SJason Wang 	default:
35971576d986SJason Wang 		break;
35981576d986SJason Wang 	}
35991576d986SJason Wang 
36001576d986SJason Wang 	return NOTIFY_DONE;
36011576d986SJason Wang }
36021576d986SJason Wang 
36031576d986SJason Wang static struct notifier_block tun_notifier_block __read_mostly = {
36041576d986SJason Wang 	.notifier_call	= tun_device_event,
36051576d986SJason Wang };
360679d17604SPavel Emelyanov 
36071da177e4SLinus Torvalds static int __init tun_init(void)
36081da177e4SLinus Torvalds {
36091da177e4SLinus Torvalds 	int ret = 0;
36101da177e4SLinus Torvalds 
36116b8a66eeSJoe Perches 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
36121da177e4SLinus Torvalds 
3613f019a7a5SEric W. Biederman 	ret = rtnl_link_register(&tun_link_ops);
361479d17604SPavel Emelyanov 	if (ret) {
36156b8a66eeSJoe Perches 		pr_err("Can't register link_ops\n");
3616f019a7a5SEric W. Biederman 		goto err_linkops;
361779d17604SPavel Emelyanov 	}
361879d17604SPavel Emelyanov 
36191da177e4SLinus Torvalds 	ret = misc_register(&tun_miscdev);
362079d17604SPavel Emelyanov 	if (ret) {
36216b8a66eeSJoe Perches 		pr_err("Can't register misc device %d\n", TUN_MINOR);
362279d17604SPavel Emelyanov 		goto err_misc;
362379d17604SPavel Emelyanov 	}
36241576d986SJason Wang 
36255edfbd3cSTonghao Zhang 	ret = register_netdevice_notifier(&tun_notifier_block);
36265edfbd3cSTonghao Zhang 	if (ret) {
36275edfbd3cSTonghao Zhang 		pr_err("Can't register netdevice notifier\n");
36285edfbd3cSTonghao Zhang 		goto err_notifier;
36295edfbd3cSTonghao Zhang 	}
36305edfbd3cSTonghao Zhang 
363179d17604SPavel Emelyanov 	return  0;
36325edfbd3cSTonghao Zhang 
36335edfbd3cSTonghao Zhang err_notifier:
36345edfbd3cSTonghao Zhang 	misc_deregister(&tun_miscdev);
363579d17604SPavel Emelyanov err_misc:
3636f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
3637f019a7a5SEric W. Biederman err_linkops:
36381da177e4SLinus Torvalds 	return ret;
36391da177e4SLinus Torvalds }
36401da177e4SLinus Torvalds 
36411da177e4SLinus Torvalds static void tun_cleanup(void)
36421da177e4SLinus Torvalds {
36431da177e4SLinus Torvalds 	misc_deregister(&tun_miscdev);
3644f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
36451576d986SJason Wang 	unregister_netdevice_notifier(&tun_notifier_block);
36461da177e4SLinus Torvalds }
36471da177e4SLinus Torvalds 
364805c2828cSMichael S. Tsirkin /* Get an underlying socket object from tun file.  Returns error unless file is
364905c2828cSMichael S. Tsirkin  * attached to a device.  The returned object works like a packet socket, it
365005c2828cSMichael S. Tsirkin  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
365105c2828cSMichael S. Tsirkin  * holding a reference to the file for as long as the socket is in use. */
365205c2828cSMichael S. Tsirkin struct socket *tun_get_socket(struct file *file)
365305c2828cSMichael S. Tsirkin {
36546e914fc7SJason Wang 	struct tun_file *tfile;
365505c2828cSMichael S. Tsirkin 	if (file->f_op != &tun_fops)
365605c2828cSMichael S. Tsirkin 		return ERR_PTR(-EINVAL);
36576e914fc7SJason Wang 	tfile = file->private_data;
36586e914fc7SJason Wang 	if (!tfile)
365905c2828cSMichael S. Tsirkin 		return ERR_PTR(-EBADFD);
366054f968d6SJason Wang 	return &tfile->socket;
366105c2828cSMichael S. Tsirkin }
366205c2828cSMichael S. Tsirkin EXPORT_SYMBOL_GPL(tun_get_socket);
366305c2828cSMichael S. Tsirkin 
36645990a305SJason Wang struct ptr_ring *tun_get_tx_ring(struct file *file)
366583339c6bSJason Wang {
366683339c6bSJason Wang 	struct tun_file *tfile;
366783339c6bSJason Wang 
366883339c6bSJason Wang 	if (file->f_op != &tun_fops)
366983339c6bSJason Wang 		return ERR_PTR(-EINVAL);
367083339c6bSJason Wang 	tfile = file->private_data;
367183339c6bSJason Wang 	if (!tfile)
367283339c6bSJason Wang 		return ERR_PTR(-EBADFD);
36735990a305SJason Wang 	return &tfile->tx_ring;
367483339c6bSJason Wang }
36755990a305SJason Wang EXPORT_SYMBOL_GPL(tun_get_tx_ring);
367683339c6bSJason Wang 
36771da177e4SLinus Torvalds module_init(tun_init);
36781da177e4SLinus Torvalds module_exit(tun_cleanup);
36791da177e4SLinus Torvalds MODULE_DESCRIPTION(DRV_DESCRIPTION);
36801da177e4SLinus Torvalds MODULE_AUTHOR(DRV_COPYRIGHT);
36811da177e4SLinus Torvalds MODULE_LICENSE("GPL");
36821da177e4SLinus Torvalds MODULE_ALIAS_MISCDEV(TUN_MINOR);
3683578454ffSKay Sievers MODULE_ALIAS("devname:net/tun");
3684