xref: /openbmc/linux/drivers/net/tun.c (revision 8ced425ee630c03beea06c1dfa35190bf8395d07)
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>
471da177e4SLinus Torvalds #include <linux/major.h>
481da177e4SLinus Torvalds #include <linux/slab.h>
491da177e4SLinus Torvalds #include <linux/poll.h>
501da177e4SLinus Torvalds #include <linux/fcntl.h>
511da177e4SLinus Torvalds #include <linux/init.h>
521da177e4SLinus Torvalds #include <linux/skbuff.h>
531da177e4SLinus Torvalds #include <linux/netdevice.h>
541da177e4SLinus Torvalds #include <linux/etherdevice.h>
551da177e4SLinus Torvalds #include <linux/miscdevice.h>
561da177e4SLinus Torvalds #include <linux/ethtool.h>
571da177e4SLinus Torvalds #include <linux/rtnetlink.h>
5850857e2aSArnd Bergmann #include <linux/compat.h>
591da177e4SLinus Torvalds #include <linux/if.h>
601da177e4SLinus Torvalds #include <linux/if_arp.h>
611da177e4SLinus Torvalds #include <linux/if_ether.h>
621da177e4SLinus Torvalds #include <linux/if_tun.h>
636680ec68SJason Wang #include <linux/if_vlan.h>
641da177e4SLinus Torvalds #include <linux/crc32.h>
65d647a591SPavel Emelyanov #include <linux/nsproxy.h>
66f43798c2SRusty Russell #include <linux/virtio_net.h>
6799405162SMichael S. Tsirkin #include <linux/rcupdate.h>
68881d966bSEric W. Biederman #include <net/net_namespace.h>
6979d17604SPavel Emelyanov #include <net/netns/generic.h>
70f019a7a5SEric W. Biederman #include <net/rtnetlink.h>
7133dccbb0SHerbert Xu #include <net/sock.h>
7293e14b6dSMasatake YAMATO #include <linux/seq_file.h>
73e0b46d0eSHerbert Xu #include <linux/uio.h>
741da177e4SLinus Torvalds 
751da177e4SLinus Torvalds #include <asm/uaccess.h>
761da177e4SLinus Torvalds 
7714daa021SRusty Russell /* Uncomment to enable debugging */
7814daa021SRusty Russell /* #define TUN_DEBUG 1 */
7914daa021SRusty Russell 
801da177e4SLinus Torvalds #ifdef TUN_DEBUG
811da177e4SLinus Torvalds static int debug;
8214daa021SRusty Russell 
836b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
846b8a66eeSJoe Perches do {								\
856b8a66eeSJoe Perches 	if (tun->debug)						\
866b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
876b8a66eeSJoe Perches } while (0)
886b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
896b8a66eeSJoe Perches do {								\
906b8a66eeSJoe Perches 	if (debug == 2)						\
916b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
926b8a66eeSJoe Perches } while (0)
9314daa021SRusty Russell #else
946b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
956b8a66eeSJoe Perches do {								\
966b8a66eeSJoe Perches 	if (0)							\
976b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
986b8a66eeSJoe Perches } while (0)
996b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
1006b8a66eeSJoe Perches do {								\
1016b8a66eeSJoe Perches 	if (0)							\
1026b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
1036b8a66eeSJoe Perches } while (0)
1041da177e4SLinus Torvalds #endif
1051da177e4SLinus Torvalds 
106031f5e03SMichael S. Tsirkin /* TUN device flags */
107031f5e03SMichael S. Tsirkin 
108031f5e03SMichael S. Tsirkin /* IFF_ATTACH_QUEUE is never stored in device flags,
109031f5e03SMichael S. Tsirkin  * overload it to mean fasync when stored there.
110031f5e03SMichael S. Tsirkin  */
111031f5e03SMichael S. Tsirkin #define TUN_FASYNC	IFF_ATTACH_QUEUE
1121cf8e410SMichael S. Tsirkin /* High bits in flags field are unused. */
1131cf8e410SMichael S. Tsirkin #define TUN_VNET_LE     0x80000000
1148b8e658bSGreg Kurz #define TUN_VNET_BE     0x40000000
115031f5e03SMichael S. Tsirkin 
116031f5e03SMichael S. Tsirkin #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
1171cf8e410SMichael S. Tsirkin 		      IFF_MULTI_QUEUE)
1180690899bSMichael S. Tsirkin #define GOODCOPY_LEN 128
1190690899bSMichael S. Tsirkin 
120f271b2ccSMax Krasnyansky #define FLT_EXACT_COUNT 8
121f271b2ccSMax Krasnyansky struct tap_filter {
122f271b2ccSMax Krasnyansky 	unsigned int    count;    /* Number of addrs. Zero means disabled */
123f271b2ccSMax Krasnyansky 	u32             mask[2];  /* Mask of the hashed addrs */
124f271b2ccSMax Krasnyansky 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
125f271b2ccSMax Krasnyansky };
126f271b2ccSMax Krasnyansky 
127baf71c5cSPankaj Gupta /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
128baf71c5cSPankaj Gupta  * to max number of VCPUs in guest. */
129baf71c5cSPankaj Gupta #define MAX_TAP_QUEUES 256
130b8732fb7SJason Wang #define MAX_TAP_FLOWS  4096
131c8d68e6bSJason Wang 
13296442e42SJason Wang #define TUN_FLOW_EXPIRE (3 * HZ)
13396442e42SJason Wang 
13454f968d6SJason Wang /* A tun_file connects an open character device to a tuntap netdevice. It
13592d4ea6eSstephen hemminger  * also contains all socket related structures (except sock_fprog and tap_filter)
13654f968d6SJason Wang  * to serve as one transmit queue for tuntap device. The sock_fprog and
13754f968d6SJason Wang  * tap_filter were kept in tun_struct since they were used for filtering for the
13836fe8c09SRami Rosen  * netdevice not for a specific queue (at least I didn't see the requirement for
13954f968d6SJason Wang  * this).
1406e914fc7SJason Wang  *
1416e914fc7SJason Wang  * RCU usage:
14236fe8c09SRami Rosen  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
1436e914fc7SJason Wang  * other can only be read while rcu_read_lock or rtnl_lock is held.
14454f968d6SJason Wang  */
145631ab46bSEric W. Biederman struct tun_file {
14654f968d6SJason Wang 	struct sock sk;
14754f968d6SJason Wang 	struct socket socket;
14854f968d6SJason Wang 	struct socket_wq wq;
1496e914fc7SJason Wang 	struct tun_struct __rcu *tun;
15054f968d6SJason Wang 	struct fasync_struct *fasync;
15154f968d6SJason Wang 	/* only used for fasnyc */
15254f968d6SJason Wang 	unsigned int flags;
153fb7589a1SPavel Emelyanov 	union {
154c8d68e6bSJason Wang 		u16 queue_index;
155fb7589a1SPavel Emelyanov 		unsigned int ifindex;
156fb7589a1SPavel Emelyanov 	};
1574008e97fSJason Wang 	struct list_head next;
1584008e97fSJason Wang 	struct tun_struct *detached;
159631ab46bSEric W. Biederman };
160631ab46bSEric W. Biederman 
16196442e42SJason Wang struct tun_flow_entry {
16296442e42SJason Wang 	struct hlist_node hash_link;
16396442e42SJason Wang 	struct rcu_head rcu;
16496442e42SJason Wang 	struct tun_struct *tun;
16596442e42SJason Wang 
16696442e42SJason Wang 	u32 rxhash;
1679bc88939STom Herbert 	u32 rps_rxhash;
16896442e42SJason Wang 	int queue_index;
16996442e42SJason Wang 	unsigned long updated;
17096442e42SJason Wang };
17196442e42SJason Wang 
17296442e42SJason Wang #define TUN_NUM_FLOW_ENTRIES 1024
17396442e42SJason Wang 
17454f968d6SJason Wang /* Since the socket were moved to tun_file, to preserve the behavior of persist
17536fe8c09SRami Rosen  * device, socket filter, sndbuf and vnet header size were restore when the
17654f968d6SJason Wang  * file were attached to a persist device.
17754f968d6SJason Wang  */
17814daa021SRusty Russell struct tun_struct {
179c8d68e6bSJason Wang 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
180c8d68e6bSJason Wang 	unsigned int            numqueues;
181f271b2ccSMax Krasnyansky 	unsigned int 		flags;
1820625c883SEric W. Biederman 	kuid_t			owner;
1830625c883SEric W. Biederman 	kgid_t			group;
18414daa021SRusty Russell 
18514daa021SRusty Russell 	struct net_device	*dev;
186c8f44affSMichał Mirosław 	netdev_features_t	set_features;
18788255375SMichał Mirosław #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
188e3e3c423SVlad Yasevich 			  NETIF_F_TSO6|NETIF_F_UFO)
189d9d52b51SMichael S. Tsirkin 
190eaea34b2SPaolo Abeni 	int			align;
191d9d52b51SMichael S. Tsirkin 	int			vnet_hdr_sz;
19254f968d6SJason Wang 	int			sndbuf;
19354f968d6SJason Wang 	struct tap_filter	txflt;
19454f968d6SJason Wang 	struct sock_fprog	fprog;
19554f968d6SJason Wang 	/* protected by rtnl lock */
19654f968d6SJason Wang 	bool			filter_attached;
19714daa021SRusty Russell #ifdef TUN_DEBUG
19814daa021SRusty Russell 	int debug;
19914daa021SRusty Russell #endif
20096442e42SJason Wang 	spinlock_t lock;
20196442e42SJason Wang 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
20296442e42SJason Wang 	struct timer_list flow_gc_timer;
20396442e42SJason Wang 	unsigned long ageing_time;
2044008e97fSJason Wang 	unsigned int numdisabled;
2054008e97fSJason Wang 	struct list_head disabled;
2065dbbaf2dSPaul Moore 	void *security;
207b8732fb7SJason Wang 	u32 flow_count;
20814daa021SRusty Russell };
20914daa021SRusty Russell 
2108b8e658bSGreg Kurz #ifdef CONFIG_TUN_VNET_CROSS_LE
2118b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
2128b8e658bSGreg Kurz {
2138b8e658bSGreg Kurz 	return tun->flags & TUN_VNET_BE ? false :
2148b8e658bSGreg Kurz 		virtio_legacy_is_little_endian();
2158b8e658bSGreg Kurz }
2168b8e658bSGreg Kurz 
2178b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
2188b8e658bSGreg Kurz {
2198b8e658bSGreg Kurz 	int be = !!(tun->flags & TUN_VNET_BE);
2208b8e658bSGreg Kurz 
2218b8e658bSGreg Kurz 	if (put_user(be, argp))
2228b8e658bSGreg Kurz 		return -EFAULT;
2238b8e658bSGreg Kurz 
2248b8e658bSGreg Kurz 	return 0;
2258b8e658bSGreg Kurz }
2268b8e658bSGreg Kurz 
2278b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
2288b8e658bSGreg Kurz {
2298b8e658bSGreg Kurz 	int be;
2308b8e658bSGreg Kurz 
2318b8e658bSGreg Kurz 	if (get_user(be, argp))
2328b8e658bSGreg Kurz 		return -EFAULT;
2338b8e658bSGreg Kurz 
2348b8e658bSGreg Kurz 	if (be)
2358b8e658bSGreg Kurz 		tun->flags |= TUN_VNET_BE;
2368b8e658bSGreg Kurz 	else
2378b8e658bSGreg Kurz 		tun->flags &= ~TUN_VNET_BE;
2388b8e658bSGreg Kurz 
2398b8e658bSGreg Kurz 	return 0;
2408b8e658bSGreg Kurz }
2418b8e658bSGreg Kurz #else
2428b8e658bSGreg Kurz static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
2438b8e658bSGreg Kurz {
2448b8e658bSGreg Kurz 	return virtio_legacy_is_little_endian();
2458b8e658bSGreg Kurz }
2468b8e658bSGreg Kurz 
2478b8e658bSGreg Kurz static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
2488b8e658bSGreg Kurz {
2498b8e658bSGreg Kurz 	return -EINVAL;
2508b8e658bSGreg Kurz }
2518b8e658bSGreg Kurz 
2528b8e658bSGreg Kurz static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
2538b8e658bSGreg Kurz {
2548b8e658bSGreg Kurz 	return -EINVAL;
2558b8e658bSGreg Kurz }
2568b8e658bSGreg Kurz #endif /* CONFIG_TUN_VNET_CROSS_LE */
2578b8e658bSGreg Kurz 
25825bd55bbSGreg Kurz static inline bool tun_is_little_endian(struct tun_struct *tun)
25925bd55bbSGreg Kurz {
2607d824109SGreg Kurz 	return tun->flags & TUN_VNET_LE ||
2618b8e658bSGreg Kurz 		tun_legacy_is_little_endian(tun);
26225bd55bbSGreg Kurz }
26325bd55bbSGreg Kurz 
26456f0dcc5SMichael S. Tsirkin static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
26556f0dcc5SMichael S. Tsirkin {
26625bd55bbSGreg Kurz 	return __virtio16_to_cpu(tun_is_little_endian(tun), val);
26756f0dcc5SMichael S. Tsirkin }
26856f0dcc5SMichael S. Tsirkin 
26956f0dcc5SMichael S. Tsirkin static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
27056f0dcc5SMichael S. Tsirkin {
27125bd55bbSGreg Kurz 	return __cpu_to_virtio16(tun_is_little_endian(tun), val);
27256f0dcc5SMichael S. Tsirkin }
27356f0dcc5SMichael S. Tsirkin 
27496442e42SJason Wang static inline u32 tun_hashfn(u32 rxhash)
27596442e42SJason Wang {
27696442e42SJason Wang 	return rxhash & 0x3ff;
27796442e42SJason Wang }
27896442e42SJason Wang 
27996442e42SJason Wang static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
28096442e42SJason Wang {
28196442e42SJason Wang 	struct tun_flow_entry *e;
28296442e42SJason Wang 
283b67bfe0dSSasha Levin 	hlist_for_each_entry_rcu(e, head, hash_link) {
28496442e42SJason Wang 		if (e->rxhash == rxhash)
28596442e42SJason Wang 			return e;
28696442e42SJason Wang 	}
28796442e42SJason Wang 	return NULL;
28896442e42SJason Wang }
28996442e42SJason Wang 
29096442e42SJason Wang static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
29196442e42SJason Wang 					      struct hlist_head *head,
29296442e42SJason Wang 					      u32 rxhash, u16 queue_index)
29396442e42SJason Wang {
2949fdc6befSEric Dumazet 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
2959fdc6befSEric Dumazet 
29696442e42SJason Wang 	if (e) {
29796442e42SJason Wang 		tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
29896442e42SJason Wang 			  rxhash, queue_index);
29996442e42SJason Wang 		e->updated = jiffies;
30096442e42SJason Wang 		e->rxhash = rxhash;
3019bc88939STom Herbert 		e->rps_rxhash = 0;
30296442e42SJason Wang 		e->queue_index = queue_index;
30396442e42SJason Wang 		e->tun = tun;
30496442e42SJason Wang 		hlist_add_head_rcu(&e->hash_link, head);
305b8732fb7SJason Wang 		++tun->flow_count;
30696442e42SJason Wang 	}
30796442e42SJason Wang 	return e;
30896442e42SJason Wang }
30996442e42SJason Wang 
31096442e42SJason Wang static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
31196442e42SJason Wang {
31296442e42SJason Wang 	tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
31396442e42SJason Wang 		  e->rxhash, e->queue_index);
31496442e42SJason Wang 	hlist_del_rcu(&e->hash_link);
3159fdc6befSEric Dumazet 	kfree_rcu(e, rcu);
316b8732fb7SJason Wang 	--tun->flow_count;
31796442e42SJason Wang }
31896442e42SJason Wang 
31996442e42SJason Wang static void tun_flow_flush(struct tun_struct *tun)
32096442e42SJason Wang {
32196442e42SJason Wang 	int i;
32296442e42SJason Wang 
32396442e42SJason Wang 	spin_lock_bh(&tun->lock);
32496442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
32596442e42SJason Wang 		struct tun_flow_entry *e;
326b67bfe0dSSasha Levin 		struct hlist_node *n;
32796442e42SJason Wang 
328b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
32996442e42SJason Wang 			tun_flow_delete(tun, e);
33096442e42SJason Wang 	}
33196442e42SJason Wang 	spin_unlock_bh(&tun->lock);
33296442e42SJason Wang }
33396442e42SJason Wang 
33496442e42SJason Wang static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
33596442e42SJason Wang {
33696442e42SJason Wang 	int i;
33796442e42SJason Wang 
33896442e42SJason Wang 	spin_lock_bh(&tun->lock);
33996442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
34096442e42SJason Wang 		struct tun_flow_entry *e;
341b67bfe0dSSasha Levin 		struct hlist_node *n;
34296442e42SJason Wang 
343b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
34496442e42SJason Wang 			if (e->queue_index == queue_index)
34596442e42SJason Wang 				tun_flow_delete(tun, e);
34696442e42SJason Wang 		}
34796442e42SJason Wang 	}
34896442e42SJason Wang 	spin_unlock_bh(&tun->lock);
34996442e42SJason Wang }
35096442e42SJason Wang 
35196442e42SJason Wang static void tun_flow_cleanup(unsigned long data)
35296442e42SJason Wang {
35396442e42SJason Wang 	struct tun_struct *tun = (struct tun_struct *)data;
35496442e42SJason Wang 	unsigned long delay = tun->ageing_time;
35596442e42SJason Wang 	unsigned long next_timer = jiffies + delay;
35696442e42SJason Wang 	unsigned long count = 0;
35796442e42SJason Wang 	int i;
35896442e42SJason Wang 
35996442e42SJason Wang 	tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
36096442e42SJason Wang 
36196442e42SJason Wang 	spin_lock_bh(&tun->lock);
36296442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
36396442e42SJason Wang 		struct tun_flow_entry *e;
364b67bfe0dSSasha Levin 		struct hlist_node *n;
36596442e42SJason Wang 
366b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
36796442e42SJason Wang 			unsigned long this_timer;
36896442e42SJason Wang 			count++;
36996442e42SJason Wang 			this_timer = e->updated + delay;
37096442e42SJason Wang 			if (time_before_eq(this_timer, jiffies))
37196442e42SJason Wang 				tun_flow_delete(tun, e);
37296442e42SJason Wang 			else if (time_before(this_timer, next_timer))
37396442e42SJason Wang 				next_timer = this_timer;
37496442e42SJason Wang 		}
37596442e42SJason Wang 	}
37696442e42SJason Wang 
37796442e42SJason Wang 	if (count)
37896442e42SJason Wang 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
37996442e42SJason Wang 	spin_unlock_bh(&tun->lock);
38096442e42SJason Wang }
38196442e42SJason Wang 
38249974420SEric Dumazet static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
3839e85722dSJason Wang 			    struct tun_file *tfile)
38496442e42SJason Wang {
38596442e42SJason Wang 	struct hlist_head *head;
38696442e42SJason Wang 	struct tun_flow_entry *e;
38796442e42SJason Wang 	unsigned long delay = tun->ageing_time;
3889e85722dSJason Wang 	u16 queue_index = tfile->queue_index;
38996442e42SJason Wang 
39096442e42SJason Wang 	if (!rxhash)
39196442e42SJason Wang 		return;
39296442e42SJason Wang 	else
39396442e42SJason Wang 		head = &tun->flows[tun_hashfn(rxhash)];
39496442e42SJason Wang 
39596442e42SJason Wang 	rcu_read_lock();
39696442e42SJason Wang 
3979e85722dSJason Wang 	/* We may get a very small possibility of OOO during switching, not
3989e85722dSJason Wang 	 * worth to optimize.*/
3999e85722dSJason Wang 	if (tun->numqueues == 1 || tfile->detached)
40096442e42SJason Wang 		goto unlock;
40196442e42SJason Wang 
40296442e42SJason Wang 	e = tun_flow_find(head, rxhash);
40396442e42SJason Wang 	if (likely(e)) {
40496442e42SJason Wang 		/* TODO: keep queueing to old queue until it's empty? */
40596442e42SJason Wang 		e->queue_index = queue_index;
40696442e42SJason Wang 		e->updated = jiffies;
4079bc88939STom Herbert 		sock_rps_record_flow_hash(e->rps_rxhash);
40896442e42SJason Wang 	} else {
40996442e42SJason Wang 		spin_lock_bh(&tun->lock);
410b8732fb7SJason Wang 		if (!tun_flow_find(head, rxhash) &&
411b8732fb7SJason Wang 		    tun->flow_count < MAX_TAP_FLOWS)
41296442e42SJason Wang 			tun_flow_create(tun, head, rxhash, queue_index);
41396442e42SJason Wang 
41496442e42SJason Wang 		if (!timer_pending(&tun->flow_gc_timer))
41596442e42SJason Wang 			mod_timer(&tun->flow_gc_timer,
41696442e42SJason Wang 				  round_jiffies_up(jiffies + delay));
41796442e42SJason Wang 		spin_unlock_bh(&tun->lock);
41896442e42SJason Wang 	}
41996442e42SJason Wang 
42096442e42SJason Wang unlock:
42196442e42SJason Wang 	rcu_read_unlock();
42296442e42SJason Wang }
42396442e42SJason Wang 
4249bc88939STom Herbert /**
4259bc88939STom Herbert  * Save the hash received in the stack receive path and update the
4269bc88939STom Herbert  * flow_hash table accordingly.
4279bc88939STom Herbert  */
4289bc88939STom Herbert static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
4299bc88939STom Herbert {
430567e4b79SEric Dumazet 	if (unlikely(e->rps_rxhash != hash))
4319bc88939STom Herbert 		e->rps_rxhash = hash;
4329bc88939STom Herbert }
4339bc88939STom Herbert 
434c8d68e6bSJason Wang /* We try to identify a flow through its rxhash first. The reason that
43592d4ea6eSstephen hemminger  * we do not check rxq no. is because some cards(e.g 82599), chooses
436c8d68e6bSJason Wang  * the rxq based on the txq where the last packet of the flow comes. As
437c8d68e6bSJason Wang  * the userspace application move between processors, we may get a
438c8d68e6bSJason Wang  * different rxq no. here. If we could not get rxhash, then we would
439c8d68e6bSJason Wang  * hope the rxq no. may help here.
440c8d68e6bSJason Wang  */
441f663dd9aSJason Wang static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
44299932d4fSDaniel Borkmann 			    void *accel_priv, select_queue_fallback_t fallback)
443c8d68e6bSJason Wang {
444c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
44596442e42SJason Wang 	struct tun_flow_entry *e;
446c8d68e6bSJason Wang 	u32 txq = 0;
447c8d68e6bSJason Wang 	u32 numqueues = 0;
448c8d68e6bSJason Wang 
449c8d68e6bSJason Wang 	rcu_read_lock();
45092bb73eaSJason Wang 	numqueues = ACCESS_ONCE(tun->numqueues);
451c8d68e6bSJason Wang 
4523958afa1STom Herbert 	txq = skb_get_hash(skb);
453c8d68e6bSJason Wang 	if (txq) {
45496442e42SJason Wang 		e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
4559bc88939STom Herbert 		if (e) {
4569bc88939STom Herbert 			tun_flow_save_rps_rxhash(e, txq);
457fbe4d456SZhi Yong Wu 			txq = e->queue_index;
4589bc88939STom Herbert 		} else
459c8d68e6bSJason Wang 			/* use multiply and shift instead of expensive divide */
460c8d68e6bSJason Wang 			txq = ((u64)txq * numqueues) >> 32;
461c8d68e6bSJason Wang 	} else if (likely(skb_rx_queue_recorded(skb))) {
462c8d68e6bSJason Wang 		txq = skb_get_rx_queue(skb);
463c8d68e6bSJason Wang 		while (unlikely(txq >= numqueues))
464c8d68e6bSJason Wang 			txq -= numqueues;
465c8d68e6bSJason Wang 	}
466c8d68e6bSJason Wang 
467c8d68e6bSJason Wang 	rcu_read_unlock();
468c8d68e6bSJason Wang 	return txq;
469c8d68e6bSJason Wang }
470c8d68e6bSJason Wang 
471cde8b15fSJason Wang static inline bool tun_not_capable(struct tun_struct *tun)
472cde8b15fSJason Wang {
473cde8b15fSJason Wang 	const struct cred *cred = current_cred();
474c260b772SEric W. Biederman 	struct net *net = dev_net(tun->dev);
475cde8b15fSJason Wang 
476cde8b15fSJason Wang 	return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
477cde8b15fSJason Wang 		  (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
478c260b772SEric W. Biederman 		!ns_capable(net->user_ns, CAP_NET_ADMIN);
479cde8b15fSJason Wang }
480cde8b15fSJason Wang 
481c8d68e6bSJason Wang static void tun_set_real_num_queues(struct tun_struct *tun)
482c8d68e6bSJason Wang {
483c8d68e6bSJason Wang 	netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
484c8d68e6bSJason Wang 	netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
485c8d68e6bSJason Wang }
486c8d68e6bSJason Wang 
4874008e97fSJason Wang static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
4884008e97fSJason Wang {
4894008e97fSJason Wang 	tfile->detached = tun;
4904008e97fSJason Wang 	list_add_tail(&tfile->next, &tun->disabled);
4914008e97fSJason Wang 	++tun->numdisabled;
4924008e97fSJason Wang }
4934008e97fSJason Wang 
494d32649d1SJason Wang static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
4954008e97fSJason Wang {
4964008e97fSJason Wang 	struct tun_struct *tun = tfile->detached;
4974008e97fSJason Wang 
4984008e97fSJason Wang 	tfile->detached = NULL;
4994008e97fSJason Wang 	list_del_init(&tfile->next);
5004008e97fSJason Wang 	--tun->numdisabled;
5014008e97fSJason Wang 	return tun;
5024008e97fSJason Wang }
5034008e97fSJason Wang 
5044bfb0513SJason Wang static void tun_queue_purge(struct tun_file *tfile)
5054bfb0513SJason Wang {
5064bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_receive_queue);
5074bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_error_queue);
5084bfb0513SJason Wang }
5094bfb0513SJason Wang 
510c8d68e6bSJason Wang static void __tun_detach(struct tun_file *tfile, bool clean)
511c8d68e6bSJason Wang {
512c8d68e6bSJason Wang 	struct tun_file *ntfile;
513c8d68e6bSJason Wang 	struct tun_struct *tun;
514c8d68e6bSJason Wang 
515b8deabd3SJason Wang 	tun = rtnl_dereference(tfile->tun);
516b8deabd3SJason Wang 
5179e85722dSJason Wang 	if (tun && !tfile->detached) {
518c8d68e6bSJason Wang 		u16 index = tfile->queue_index;
519c8d68e6bSJason Wang 		BUG_ON(index >= tun->numqueues);
520c8d68e6bSJason Wang 
521c8d68e6bSJason Wang 		rcu_assign_pointer(tun->tfiles[index],
522c8d68e6bSJason Wang 				   tun->tfiles[tun->numqueues - 1]);
523b8deabd3SJason Wang 		ntfile = rtnl_dereference(tun->tfiles[index]);
524c8d68e6bSJason Wang 		ntfile->queue_index = index;
525c8d68e6bSJason Wang 
526c8d68e6bSJason Wang 		--tun->numqueues;
5279e85722dSJason Wang 		if (clean) {
528c956674bSMonam Agarwal 			RCU_INIT_POINTER(tfile->tun, NULL);
529c8d68e6bSJason Wang 			sock_put(&tfile->sk);
5309e85722dSJason Wang 		} else
5314008e97fSJason Wang 			tun_disable_queue(tun, tfile);
532c8d68e6bSJason Wang 
533c8d68e6bSJason Wang 		synchronize_net();
53496442e42SJason Wang 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
535c8d68e6bSJason Wang 		/* Drop read queue */
5364bfb0513SJason Wang 		tun_queue_purge(tfile);
537c8d68e6bSJason Wang 		tun_set_real_num_queues(tun);
538dd38bd85SJason Wang 	} else if (tfile->detached && clean) {
5394008e97fSJason Wang 		tun = tun_enable_queue(tfile);
540dd38bd85SJason Wang 		sock_put(&tfile->sk);
541dd38bd85SJason Wang 	}
542c8d68e6bSJason Wang 
543c8d68e6bSJason Wang 	if (clean) {
544af668b3cSMichael S. Tsirkin 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
545af668b3cSMichael S. Tsirkin 			netif_carrier_off(tun->dev);
546af668b3cSMichael S. Tsirkin 
54740630b82SMichael S. Tsirkin 			if (!(tun->flags & IFF_PERSIST) &&
548af668b3cSMichael S. Tsirkin 			    tun->dev->reg_state == NETREG_REGISTERED)
5494008e97fSJason Wang 				unregister_netdevice(tun->dev);
550af668b3cSMichael S. Tsirkin 		}
551140e807dSEric W. Biederman 		sock_put(&tfile->sk);
552c8d68e6bSJason Wang 	}
553c8d68e6bSJason Wang }
554c8d68e6bSJason Wang 
555c8d68e6bSJason Wang static void tun_detach(struct tun_file *tfile, bool clean)
556c8d68e6bSJason Wang {
557c8d68e6bSJason Wang 	rtnl_lock();
558c8d68e6bSJason Wang 	__tun_detach(tfile, clean);
559c8d68e6bSJason Wang 	rtnl_unlock();
560c8d68e6bSJason Wang }
561c8d68e6bSJason Wang 
562c8d68e6bSJason Wang static void tun_detach_all(struct net_device *dev)
563c8d68e6bSJason Wang {
564c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
5654008e97fSJason Wang 	struct tun_file *tfile, *tmp;
566c8d68e6bSJason Wang 	int i, n = tun->numqueues;
567c8d68e6bSJason Wang 
568c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
569b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
570c8d68e6bSJason Wang 		BUG_ON(!tfile);
5719e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
572c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
573c8d68e6bSJason Wang 		--tun->numqueues;
574c8d68e6bSJason Wang 	}
5759e85722dSJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
5769e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
577c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
5789e85722dSJason Wang 	}
579c8d68e6bSJason Wang 	BUG_ON(tun->numqueues != 0);
580c8d68e6bSJason Wang 
581c8d68e6bSJason Wang 	synchronize_net();
582c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
583b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
584c8d68e6bSJason Wang 		/* Drop read queue */
5854bfb0513SJason Wang 		tun_queue_purge(tfile);
586c8d68e6bSJason Wang 		sock_put(&tfile->sk);
587c8d68e6bSJason Wang 	}
5884008e97fSJason Wang 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
5894008e97fSJason Wang 		tun_enable_queue(tfile);
5904bfb0513SJason Wang 		tun_queue_purge(tfile);
5914008e97fSJason Wang 		sock_put(&tfile->sk);
5924008e97fSJason Wang 	}
5934008e97fSJason Wang 	BUG_ON(tun->numdisabled != 0);
594dd38bd85SJason Wang 
59540630b82SMichael S. Tsirkin 	if (tun->flags & IFF_PERSIST)
596dd38bd85SJason Wang 		module_put(THIS_MODULE);
597c8d68e6bSJason Wang }
598c8d68e6bSJason Wang 
599849c9b6fSPavel Emelyanov static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter)
600a7385ba2SEric W. Biederman {
601631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
60238231b7aSEric W. Biederman 	int err;
603a7385ba2SEric W. Biederman 
6045dbbaf2dSPaul Moore 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
6055dbbaf2dSPaul Moore 	if (err < 0)
6065dbbaf2dSPaul Moore 		goto out;
6075dbbaf2dSPaul Moore 
60838231b7aSEric W. Biederman 	err = -EINVAL;
6099e85722dSJason Wang 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
61038231b7aSEric W. Biederman 		goto out;
61138231b7aSEric W. Biederman 
61238231b7aSEric W. Biederman 	err = -EBUSY;
61340630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
614c8d68e6bSJason Wang 		goto out;
615c8d68e6bSJason Wang 
616c8d68e6bSJason Wang 	err = -E2BIG;
6174008e97fSJason Wang 	if (!tfile->detached &&
6184008e97fSJason Wang 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
61938231b7aSEric W. Biederman 		goto out;
62038231b7aSEric W. Biederman 
62138231b7aSEric W. Biederman 	err = 0;
62254f968d6SJason Wang 
62392d4ea6eSstephen hemminger 	/* Re-attach the filter to persist device */
624849c9b6fSPavel Emelyanov 	if (!skip_filter && (tun->filter_attached == true)) {
625*8ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
626*8ced425eSHannes Frederic Sowa 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
627*8ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
62854f968d6SJason Wang 		if (!err)
62954f968d6SJason Wang 			goto out;
63054f968d6SJason Wang 	}
631c8d68e6bSJason Wang 	tfile->queue_index = tun->numqueues;
6326e914fc7SJason Wang 	rcu_assign_pointer(tfile->tun, tun);
633c8d68e6bSJason Wang 	rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
634c8d68e6bSJason Wang 	tun->numqueues++;
635c8d68e6bSJason Wang 
6364008e97fSJason Wang 	if (tfile->detached)
6374008e97fSJason Wang 		tun_enable_queue(tfile);
6384008e97fSJason Wang 	else
6394008e97fSJason Wang 		sock_hold(&tfile->sk);
6404008e97fSJason Wang 
641c8d68e6bSJason Wang 	tun_set_real_num_queues(tun);
642c8d68e6bSJason Wang 
643c8d68e6bSJason Wang 	/* device is allowed to go away first, so no need to hold extra
644c8d68e6bSJason Wang 	 * refcnt.
645c8d68e6bSJason Wang 	 */
646a7385ba2SEric W. Biederman 
64738231b7aSEric W. Biederman out:
64838231b7aSEric W. Biederman 	return err;
649a7385ba2SEric W. Biederman }
650a7385ba2SEric W. Biederman 
651631ab46bSEric W. Biederman static struct tun_struct *__tun_get(struct tun_file *tfile)
652631ab46bSEric W. Biederman {
6536e914fc7SJason Wang 	struct tun_struct *tun;
654c70f1829SEric W. Biederman 
6556e914fc7SJason Wang 	rcu_read_lock();
6566e914fc7SJason Wang 	tun = rcu_dereference(tfile->tun);
6576e914fc7SJason Wang 	if (tun)
6586e914fc7SJason Wang 		dev_hold(tun->dev);
6596e914fc7SJason Wang 	rcu_read_unlock();
660c70f1829SEric W. Biederman 
661c70f1829SEric W. Biederman 	return tun;
662631ab46bSEric W. Biederman }
663631ab46bSEric W. Biederman 
664631ab46bSEric W. Biederman static struct tun_struct *tun_get(struct file *file)
665631ab46bSEric W. Biederman {
666631ab46bSEric W. Biederman 	return __tun_get(file->private_data);
667631ab46bSEric W. Biederman }
668631ab46bSEric W. Biederman 
669631ab46bSEric W. Biederman static void tun_put(struct tun_struct *tun)
670631ab46bSEric W. Biederman {
6716e914fc7SJason Wang 	dev_put(tun->dev);
672631ab46bSEric W. Biederman }
673631ab46bSEric W. Biederman 
6746b8a66eeSJoe Perches /* TAP filtering */
675f271b2ccSMax Krasnyansky static void addr_hash_set(u32 *mask, const u8 *addr)
676f271b2ccSMax Krasnyansky {
677f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
678f271b2ccSMax Krasnyansky 	mask[n >> 5] |= (1 << (n & 31));
679f271b2ccSMax Krasnyansky }
680f271b2ccSMax Krasnyansky 
681f271b2ccSMax Krasnyansky static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
682f271b2ccSMax Krasnyansky {
683f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
684f271b2ccSMax Krasnyansky 	return mask[n >> 5] & (1 << (n & 31));
685f271b2ccSMax Krasnyansky }
686f271b2ccSMax Krasnyansky 
687f271b2ccSMax Krasnyansky static int update_filter(struct tap_filter *filter, void __user *arg)
688f271b2ccSMax Krasnyansky {
689f271b2ccSMax Krasnyansky 	struct { u8 u[ETH_ALEN]; } *addr;
690f271b2ccSMax Krasnyansky 	struct tun_filter uf;
691f271b2ccSMax Krasnyansky 	int err, alen, n, nexact;
692f271b2ccSMax Krasnyansky 
693f271b2ccSMax Krasnyansky 	if (copy_from_user(&uf, arg, sizeof(uf)))
694f271b2ccSMax Krasnyansky 		return -EFAULT;
695f271b2ccSMax Krasnyansky 
696f271b2ccSMax Krasnyansky 	if (!uf.count) {
697f271b2ccSMax Krasnyansky 		/* Disabled */
698f271b2ccSMax Krasnyansky 		filter->count = 0;
699f271b2ccSMax Krasnyansky 		return 0;
700f271b2ccSMax Krasnyansky 	}
701f271b2ccSMax Krasnyansky 
702f271b2ccSMax Krasnyansky 	alen = ETH_ALEN * uf.count;
703f271b2ccSMax Krasnyansky 	addr = kmalloc(alen, GFP_KERNEL);
704f271b2ccSMax Krasnyansky 	if (!addr)
705f271b2ccSMax Krasnyansky 		return -ENOMEM;
706f271b2ccSMax Krasnyansky 
707f271b2ccSMax Krasnyansky 	if (copy_from_user(addr, arg + sizeof(uf), alen)) {
708f271b2ccSMax Krasnyansky 		err = -EFAULT;
709f271b2ccSMax Krasnyansky 		goto done;
710f271b2ccSMax Krasnyansky 	}
711f271b2ccSMax Krasnyansky 
712f271b2ccSMax Krasnyansky 	/* The filter is updated without holding any locks. Which is
713f271b2ccSMax Krasnyansky 	 * perfectly safe. We disable it first and in the worst
714f271b2ccSMax Krasnyansky 	 * case we'll accept a few undesired packets. */
715f271b2ccSMax Krasnyansky 	filter->count = 0;
716f271b2ccSMax Krasnyansky 	wmb();
717f271b2ccSMax Krasnyansky 
718f271b2ccSMax Krasnyansky 	/* Use first set of addresses as an exact filter */
719f271b2ccSMax Krasnyansky 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
720f271b2ccSMax Krasnyansky 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
721f271b2ccSMax Krasnyansky 
722f271b2ccSMax Krasnyansky 	nexact = n;
723f271b2ccSMax Krasnyansky 
724cfbf84fcSAlex Williamson 	/* Remaining multicast addresses are hashed,
725cfbf84fcSAlex Williamson 	 * unicast will leave the filter disabled. */
726f271b2ccSMax Krasnyansky 	memset(filter->mask, 0, sizeof(filter->mask));
727cfbf84fcSAlex Williamson 	for (; n < uf.count; n++) {
728cfbf84fcSAlex Williamson 		if (!is_multicast_ether_addr(addr[n].u)) {
729cfbf84fcSAlex Williamson 			err = 0; /* no filter */
730cfbf84fcSAlex Williamson 			goto done;
731cfbf84fcSAlex Williamson 		}
732f271b2ccSMax Krasnyansky 		addr_hash_set(filter->mask, addr[n].u);
733cfbf84fcSAlex Williamson 	}
734f271b2ccSMax Krasnyansky 
735f271b2ccSMax Krasnyansky 	/* For ALLMULTI just set the mask to all ones.
736f271b2ccSMax Krasnyansky 	 * This overrides the mask populated above. */
737f271b2ccSMax Krasnyansky 	if ((uf.flags & TUN_FLT_ALLMULTI))
738f271b2ccSMax Krasnyansky 		memset(filter->mask, ~0, sizeof(filter->mask));
739f271b2ccSMax Krasnyansky 
740f271b2ccSMax Krasnyansky 	/* Now enable the filter */
741f271b2ccSMax Krasnyansky 	wmb();
742f271b2ccSMax Krasnyansky 	filter->count = nexact;
743f271b2ccSMax Krasnyansky 
744f271b2ccSMax Krasnyansky 	/* Return the number of exact filters */
745f271b2ccSMax Krasnyansky 	err = nexact;
746f271b2ccSMax Krasnyansky 
747f271b2ccSMax Krasnyansky done:
748f271b2ccSMax Krasnyansky 	kfree(addr);
749f271b2ccSMax Krasnyansky 	return err;
750f271b2ccSMax Krasnyansky }
751f271b2ccSMax Krasnyansky 
752f271b2ccSMax Krasnyansky /* Returns: 0 - drop, !=0 - accept */
753f271b2ccSMax Krasnyansky static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
754f271b2ccSMax Krasnyansky {
755f271b2ccSMax Krasnyansky 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
756f271b2ccSMax Krasnyansky 	 * at this point. */
757f271b2ccSMax Krasnyansky 	struct ethhdr *eh = (struct ethhdr *) skb->data;
758f271b2ccSMax Krasnyansky 	int i;
759f271b2ccSMax Krasnyansky 
760f271b2ccSMax Krasnyansky 	/* Exact match */
761f271b2ccSMax Krasnyansky 	for (i = 0; i < filter->count; i++)
7622e42e474SJoe Perches 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
763f271b2ccSMax Krasnyansky 			return 1;
764f271b2ccSMax Krasnyansky 
765f271b2ccSMax Krasnyansky 	/* Inexact match (multicast only) */
766f271b2ccSMax Krasnyansky 	if (is_multicast_ether_addr(eh->h_dest))
767f271b2ccSMax Krasnyansky 		return addr_hash_test(filter->mask, eh->h_dest);
768f271b2ccSMax Krasnyansky 
769f271b2ccSMax Krasnyansky 	return 0;
770f271b2ccSMax Krasnyansky }
771f271b2ccSMax Krasnyansky 
772f271b2ccSMax Krasnyansky /*
773f271b2ccSMax Krasnyansky  * Checks whether the packet is accepted or not.
774f271b2ccSMax Krasnyansky  * Returns: 0 - drop, !=0 - accept
775f271b2ccSMax Krasnyansky  */
776f271b2ccSMax Krasnyansky static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
777f271b2ccSMax Krasnyansky {
778f271b2ccSMax Krasnyansky 	if (!filter->count)
779f271b2ccSMax Krasnyansky 		return 1;
780f271b2ccSMax Krasnyansky 
781f271b2ccSMax Krasnyansky 	return run_filter(filter, skb);
782f271b2ccSMax Krasnyansky }
783f271b2ccSMax Krasnyansky 
7841da177e4SLinus Torvalds /* Network device part of the driver */
7851da177e4SLinus Torvalds 
7867282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops;
7871da177e4SLinus Torvalds 
788c70f1829SEric W. Biederman /* Net device detach from fd. */
789c70f1829SEric W. Biederman static void tun_net_uninit(struct net_device *dev)
790c70f1829SEric W. Biederman {
791c8d68e6bSJason Wang 	tun_detach_all(dev);
792c70f1829SEric W. Biederman }
793c70f1829SEric W. Biederman 
7941da177e4SLinus Torvalds /* Net device open. */
7951da177e4SLinus Torvalds static int tun_net_open(struct net_device *dev)
7961da177e4SLinus Torvalds {
797c8d68e6bSJason Wang 	netif_tx_start_all_queues(dev);
7981da177e4SLinus Torvalds 	return 0;
7991da177e4SLinus Torvalds }
8001da177e4SLinus Torvalds 
8011da177e4SLinus Torvalds /* Net device close. */
8021da177e4SLinus Torvalds static int tun_net_close(struct net_device *dev)
8031da177e4SLinus Torvalds {
804c8d68e6bSJason Wang 	netif_tx_stop_all_queues(dev);
8051da177e4SLinus Torvalds 	return 0;
8061da177e4SLinus Torvalds }
8071da177e4SLinus Torvalds 
8081da177e4SLinus Torvalds /* Net device start xmit */
809424efe9cSStephen Hemminger static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
8101da177e4SLinus Torvalds {
8111da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
812c8d68e6bSJason Wang 	int txq = skb->queue_mapping;
8136e914fc7SJason Wang 	struct tun_file *tfile;
814fa35864eSDominic Curran 	u32 numqueues = 0;
8151da177e4SLinus Torvalds 
8166e914fc7SJason Wang 	rcu_read_lock();
817c8d68e6bSJason Wang 	tfile = rcu_dereference(tun->tfiles[txq]);
818fa35864eSDominic Curran 	numqueues = ACCESS_ONCE(tun->numqueues);
819c8d68e6bSJason Wang 
8201da177e4SLinus Torvalds 	/* Drop packet if interface is not attached */
821fa35864eSDominic Curran 	if (txq >= numqueues)
8221da177e4SLinus Torvalds 		goto drop;
8231da177e4SLinus Torvalds 
824fa35864eSDominic Curran 	if (numqueues == 1) {
8259bc88939STom Herbert 		/* Select queue was not called for the skbuff, so we extract the
8269bc88939STom Herbert 		 * RPS hash and save it into the flow_table here.
8279bc88939STom Herbert 		 */
8289bc88939STom Herbert 		__u32 rxhash;
8299bc88939STom Herbert 
8309bc88939STom Herbert 		rxhash = skb_get_hash(skb);
8319bc88939STom Herbert 		if (rxhash) {
8329bc88939STom Herbert 			struct tun_flow_entry *e;
8339bc88939STom Herbert 			e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
8349bc88939STom Herbert 					rxhash);
8359bc88939STom Herbert 			if (e)
8369bc88939STom Herbert 				tun_flow_save_rps_rxhash(e, rxhash);
8379bc88939STom Herbert 		}
8389bc88939STom Herbert 	}
8399bc88939STom Herbert 
8406e914fc7SJason Wang 	tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
8416e914fc7SJason Wang 
842c8d68e6bSJason Wang 	BUG_ON(!tfile);
843c8d68e6bSJason Wang 
844f271b2ccSMax Krasnyansky 	/* Drop if the filter does not like it.
845f271b2ccSMax Krasnyansky 	 * This is a noop if the filter is disabled.
846f271b2ccSMax Krasnyansky 	 * Filter can be enabled only for the TAP devices. */
847f271b2ccSMax Krasnyansky 	if (!check_filter(&tun->txflt, skb))
848f271b2ccSMax Krasnyansky 		goto drop;
849f271b2ccSMax Krasnyansky 
85054f968d6SJason Wang 	if (tfile->socket.sk->sk_filter &&
85154f968d6SJason Wang 	    sk_filter(tfile->socket.sk, skb))
85299405162SMichael S. Tsirkin 		goto drop;
85399405162SMichael S. Tsirkin 
85436fe8c09SRami Rosen 	/* Limit the number of packets queued by dividing txq length with the
855c8d68e6bSJason Wang 	 * number of queues.
856c8d68e6bSJason Wang 	 */
857fa35864eSDominic Curran 	if (skb_queue_len(&tfile->socket.sk->sk_receive_queue) * numqueues
858fa35864eSDominic Curran 			  >= dev->tx_queue_len)
8591da177e4SLinus Torvalds 		goto drop;
8601da177e4SLinus Torvalds 
8617bf66305SJason Wang 	if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
8627bf66305SJason Wang 		goto drop;
8637bf66305SJason Wang 
8645fcd2d8bSEric Dumazet 	if (skb->sk && sk_fullsock(skb->sk)) {
865c14ac945SSoheil Hassas Yeganeh 		sock_tx_timestamp(skb->sk, skb->sk->sk_tsflags,
866c14ac945SSoheil Hassas Yeganeh 				  &skb_shinfo(skb)->tx_flags);
867eda29772SRichard Cochran 		sw_tx_timestamp(skb);
868eda29772SRichard Cochran 	}
869eda29772SRichard Cochran 
8700110d6f2SMichael S. Tsirkin 	/* Orphan the skb - required as we might hang on to it
8717bf66305SJason Wang 	 * for indefinite time.
8727bf66305SJason Wang 	 */
8730110d6f2SMichael S. Tsirkin 	skb_orphan(skb);
8740110d6f2SMichael S. Tsirkin 
875f8af75f3SEric Dumazet 	nf_reset(skb);
876f8af75f3SEric Dumazet 
877f271b2ccSMax Krasnyansky 	/* Enqueue packet */
87854f968d6SJason Wang 	skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
8791da177e4SLinus Torvalds 
8801da177e4SLinus Torvalds 	/* Notify and wake up reader process */
88154f968d6SJason Wang 	if (tfile->flags & TUN_FASYNC)
88254f968d6SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
8839e641bdcSXi Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
8846e914fc7SJason Wang 
8856e914fc7SJason Wang 	rcu_read_unlock();
8866ed10654SPatrick McHardy 	return NETDEV_TX_OK;
8871da177e4SLinus Torvalds 
8881da177e4SLinus Torvalds drop:
88909f75cd7SJeff Garzik 	dev->stats.tx_dropped++;
890149d36f7SMichael S. Tsirkin 	skb_tx_error(skb);
8911da177e4SLinus Torvalds 	kfree_skb(skb);
8926e914fc7SJason Wang 	rcu_read_unlock();
893baeababbSJason Wang 	return NET_XMIT_DROP;
8941da177e4SLinus Torvalds }
8951da177e4SLinus Torvalds 
896f271b2ccSMax Krasnyansky static void tun_net_mclist(struct net_device *dev)
8971da177e4SLinus Torvalds {
898f271b2ccSMax Krasnyansky 	/*
899f271b2ccSMax Krasnyansky 	 * This callback is supposed to deal with mc filter in
900f271b2ccSMax Krasnyansky 	 * _rx_ path and has nothing to do with the _tx_ path.
901f271b2ccSMax Krasnyansky 	 * In rx path we always accept everything userspace gives us.
902f271b2ccSMax Krasnyansky 	 */
9031da177e4SLinus Torvalds }
9041da177e4SLinus Torvalds 
9054885a504SEd Swierk #define MIN_MTU 68
9064885a504SEd Swierk #define MAX_MTU 65535
9074885a504SEd Swierk 
9084885a504SEd Swierk static int
9094885a504SEd Swierk tun_net_change_mtu(struct net_device *dev, int new_mtu)
9104885a504SEd Swierk {
9114885a504SEd Swierk 	if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
9124885a504SEd Swierk 		return -EINVAL;
9134885a504SEd Swierk 	dev->mtu = new_mtu;
9144885a504SEd Swierk 	return 0;
9154885a504SEd Swierk }
9164885a504SEd Swierk 
917c8f44affSMichał Mirosław static netdev_features_t tun_net_fix_features(struct net_device *dev,
918c8f44affSMichał Mirosław 	netdev_features_t features)
91988255375SMichał Mirosław {
92088255375SMichał Mirosław 	struct tun_struct *tun = netdev_priv(dev);
92188255375SMichał Mirosław 
92288255375SMichał Mirosław 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
92388255375SMichał Mirosław }
924bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
925bebd097aSNeil Horman static void tun_poll_controller(struct net_device *dev)
926bebd097aSNeil Horman {
927bebd097aSNeil Horman 	/*
928bebd097aSNeil Horman 	 * Tun only receives frames when:
929bebd097aSNeil Horman 	 * 1) the char device endpoint gets data from user space
930bebd097aSNeil Horman 	 * 2) the tun socket gets a sendmsg call from user space
93192d4ea6eSstephen hemminger 	 * Since both of those are synchronous operations, we are guaranteed
932bebd097aSNeil Horman 	 * never to have pending data when we poll for it
93392d4ea6eSstephen hemminger 	 * so there is nothing to do here but return.
934bebd097aSNeil Horman 	 * We need this though so netpoll recognizes us as an interface that
935bebd097aSNeil Horman 	 * supports polling, which enables bridge devices in virt setups to
936bebd097aSNeil Horman 	 * still use netconsole
937bebd097aSNeil Horman 	 */
938bebd097aSNeil Horman 	return;
939bebd097aSNeil Horman }
940bebd097aSNeil Horman #endif
941eaea34b2SPaolo Abeni 
942eaea34b2SPaolo Abeni static void tun_set_headroom(struct net_device *dev, int new_hr)
943eaea34b2SPaolo Abeni {
944eaea34b2SPaolo Abeni 	struct tun_struct *tun = netdev_priv(dev);
945eaea34b2SPaolo Abeni 
946eaea34b2SPaolo Abeni 	if (new_hr < NET_SKB_PAD)
947eaea34b2SPaolo Abeni 		new_hr = NET_SKB_PAD;
948eaea34b2SPaolo Abeni 
949eaea34b2SPaolo Abeni 	tun->align = new_hr;
950eaea34b2SPaolo Abeni }
951eaea34b2SPaolo Abeni 
952758e43b7SStephen Hemminger static const struct net_device_ops tun_netdev_ops = {
953c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
954758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
955758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
95600829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
957758e43b7SStephen Hemminger 	.ndo_change_mtu		= tun_net_change_mtu,
95888255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
959c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
960bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
961bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
962bebd097aSNeil Horman #endif
963eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
964758e43b7SStephen Hemminger };
965758e43b7SStephen Hemminger 
966758e43b7SStephen Hemminger static const struct net_device_ops tap_netdev_ops = {
967c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
968758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
969758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
97000829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
971758e43b7SStephen Hemminger 	.ndo_change_mtu		= tun_net_change_mtu,
97288255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
973afc4b13dSJiri Pirko 	.ndo_set_rx_mode	= tun_net_mclist,
974758e43b7SStephen Hemminger 	.ndo_set_mac_address	= eth_mac_addr,
975758e43b7SStephen Hemminger 	.ndo_validate_addr	= eth_validate_addr,
976c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
977bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
978bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
979bebd097aSNeil Horman #endif
9805e52796aSToshiaki Makita 	.ndo_features_check	= passthru_features_check,
981eaea34b2SPaolo Abeni 	.ndo_set_rx_headroom	= tun_set_headroom,
982758e43b7SStephen Hemminger };
983758e43b7SStephen Hemminger 
984944a1376SPavel Emelyanov static void tun_flow_init(struct tun_struct *tun)
98596442e42SJason Wang {
98696442e42SJason Wang 	int i;
98796442e42SJason Wang 
98896442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
98996442e42SJason Wang 		INIT_HLIST_HEAD(&tun->flows[i]);
99096442e42SJason Wang 
99196442e42SJason Wang 	tun->ageing_time = TUN_FLOW_EXPIRE;
99296442e42SJason Wang 	setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
99396442e42SJason Wang 	mod_timer(&tun->flow_gc_timer,
99496442e42SJason Wang 		  round_jiffies_up(jiffies + tun->ageing_time));
99596442e42SJason Wang }
99696442e42SJason Wang 
99796442e42SJason Wang static void tun_flow_uninit(struct tun_struct *tun)
99896442e42SJason Wang {
99996442e42SJason Wang 	del_timer_sync(&tun->flow_gc_timer);
100096442e42SJason Wang 	tun_flow_flush(tun);
100196442e42SJason Wang }
100296442e42SJason Wang 
10031da177e4SLinus Torvalds /* Initialize net device. */
10041da177e4SLinus Torvalds static void tun_net_init(struct net_device *dev)
10051da177e4SLinus Torvalds {
10061da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
10071da177e4SLinus Torvalds 
10081da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
100940630b82SMichael S. Tsirkin 	case IFF_TUN:
1010758e43b7SStephen Hemminger 		dev->netdev_ops = &tun_netdev_ops;
1011758e43b7SStephen Hemminger 
10121da177e4SLinus Torvalds 		/* Point-to-Point TUN Device */
10131da177e4SLinus Torvalds 		dev->hard_header_len = 0;
10141da177e4SLinus Torvalds 		dev->addr_len = 0;
10151da177e4SLinus Torvalds 		dev->mtu = 1500;
10161da177e4SLinus Torvalds 
10171da177e4SLinus Torvalds 		/* Zero header length */
10181da177e4SLinus Torvalds 		dev->type = ARPHRD_NONE;
10191da177e4SLinus Torvalds 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
10201da177e4SLinus Torvalds 		dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
10211da177e4SLinus Torvalds 		break;
10221da177e4SLinus Torvalds 
102340630b82SMichael S. Tsirkin 	case IFF_TAP:
10247a0a9608SKusanagi Kouichi 		dev->netdev_ops = &tap_netdev_ops;
10251da177e4SLinus Torvalds 		/* Ethernet TAP Device */
10261da177e4SLinus Torvalds 		ether_setup(dev);
1027550fd08cSNeil Horman 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1028a676847bSstephen hemminger 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
102936226a8dSBrian Braunstein 
1030f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
103136226a8dSBrian Braunstein 
10321da177e4SLinus Torvalds 		dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
10331da177e4SLinus Torvalds 		break;
10341da177e4SLinus Torvalds 	}
10351da177e4SLinus Torvalds }
10361da177e4SLinus Torvalds 
10371da177e4SLinus Torvalds /* Character device part */
10381da177e4SLinus Torvalds 
10391da177e4SLinus Torvalds /* Poll */
10401da177e4SLinus Torvalds static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
10411da177e4SLinus Torvalds {
1042b2430de3SEric W. Biederman 	struct tun_file *tfile = file->private_data;
1043b2430de3SEric W. Biederman 	struct tun_struct *tun = __tun_get(tfile);
10443c8a9c63SMariusz Kozlowski 	struct sock *sk;
104533dccbb0SHerbert Xu 	unsigned int mask = 0;
10461da177e4SLinus Torvalds 
10471da177e4SLinus Torvalds 	if (!tun)
1048eac9e902SEric W. Biederman 		return POLLERR;
10491da177e4SLinus Torvalds 
105054f968d6SJason Wang 	sk = tfile->socket.sk;
10513c8a9c63SMariusz Kozlowski 
10526b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
10531da177e4SLinus Torvalds 
10549e641bdcSXi Wang 	poll_wait(file, sk_sleep(sk), wait);
10551da177e4SLinus Torvalds 
105689f56d1eSMichael S. Tsirkin 	if (!skb_queue_empty(&sk->sk_receive_queue))
10571da177e4SLinus Torvalds 		mask |= POLLIN | POLLRDNORM;
10581da177e4SLinus Torvalds 
105933dccbb0SHerbert Xu 	if (sock_writeable(sk) ||
10609cd3e072SEric Dumazet 	    (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
106133dccbb0SHerbert Xu 	     sock_writeable(sk)))
106233dccbb0SHerbert Xu 		mask |= POLLOUT | POLLWRNORM;
106333dccbb0SHerbert Xu 
1064c70f1829SEric W. Biederman 	if (tun->dev->reg_state != NETREG_REGISTERED)
1065c70f1829SEric W. Biederman 		mask = POLLERR;
1066c70f1829SEric W. Biederman 
1067631ab46bSEric W. Biederman 	tun_put(tun);
10681da177e4SLinus Torvalds 	return mask;
10691da177e4SLinus Torvalds }
10701da177e4SLinus Torvalds 
1071f42157cbSRusty Russell /* prepad is the amount to reserve at front.  len is length after that.
1072f42157cbSRusty Russell  * linear is a hint as to how much to copy (usually headers). */
107354f968d6SJason Wang static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
107433dccbb0SHerbert Xu 				     size_t prepad, size_t len,
107533dccbb0SHerbert Xu 				     size_t linear, int noblock)
1076f42157cbSRusty Russell {
107754f968d6SJason Wang 	struct sock *sk = tfile->socket.sk;
1078f42157cbSRusty Russell 	struct sk_buff *skb;
107933dccbb0SHerbert Xu 	int err;
1080f42157cbSRusty Russell 
1081f42157cbSRusty Russell 	/* Under a page?  Don't bother with paged skb. */
10820eca93bcSHerbert Xu 	if (prepad + len < PAGE_SIZE || !linear)
108333dccbb0SHerbert Xu 		linear = len;
1084f42157cbSRusty Russell 
108533dccbb0SHerbert Xu 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
108628d64271SEric Dumazet 				   &err, 0);
1087f42157cbSRusty Russell 	if (!skb)
108833dccbb0SHerbert Xu 		return ERR_PTR(err);
1089f42157cbSRusty Russell 
1090f42157cbSRusty Russell 	skb_reserve(skb, prepad);
1091f42157cbSRusty Russell 	skb_put(skb, linear);
109233dccbb0SHerbert Xu 	skb->data_len = len - linear;
109333dccbb0SHerbert Xu 	skb->len += len - linear;
1094f42157cbSRusty Russell 
1095f42157cbSRusty Russell 	return skb;
1096f42157cbSRusty Russell }
1097f42157cbSRusty Russell 
10981da177e4SLinus Torvalds /* Get packet from user space buffer */
109954f968d6SJason Wang static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1100f5ff53b4SAl Viro 			    void *msg_control, struct iov_iter *from,
1101f5ff53b4SAl Viro 			    int noblock)
11021da177e4SLinus Torvalds {
110309640e63SHarvey Harrison 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
11041da177e4SLinus Torvalds 	struct sk_buff *skb;
1105f5ff53b4SAl Viro 	size_t total_len = iov_iter_count(from);
1106eaea34b2SPaolo Abeni 	size_t len = total_len, align = tun->align, linear;
1107f43798c2SRusty Russell 	struct virtio_net_hdr gso = { 0 };
110896f8d9ecSJason Wang 	int good_linear;
11090690899bSMichael S. Tsirkin 	int copylen;
11100690899bSMichael S. Tsirkin 	bool zerocopy = false;
11110690899bSMichael S. Tsirkin 	int err;
111249974420SEric Dumazet 	u32 rxhash;
1113f5ff53b4SAl Viro 	ssize_t n;
11141da177e4SLinus Torvalds 
11151bd4978aSEric Dumazet 	if (!(tun->dev->flags & IFF_UP))
11161bd4978aSEric Dumazet 		return -EIO;
11171bd4978aSEric Dumazet 
111840630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
111915718ea0SDan Carpenter 		if (len < sizeof(pi))
11201da177e4SLinus Torvalds 			return -EINVAL;
112115718ea0SDan Carpenter 		len -= sizeof(pi);
11221da177e4SLinus Torvalds 
1123f5ff53b4SAl Viro 		n = copy_from_iter(&pi, sizeof(pi), from);
1124f5ff53b4SAl Viro 		if (n != sizeof(pi))
11251da177e4SLinus Torvalds 			return -EFAULT;
11261da177e4SLinus Torvalds 	}
11271da177e4SLinus Torvalds 
112840630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR) {
112915718ea0SDan Carpenter 		if (len < tun->vnet_hdr_sz)
1130f43798c2SRusty Russell 			return -EINVAL;
113115718ea0SDan Carpenter 		len -= tun->vnet_hdr_sz;
1132f43798c2SRusty Russell 
1133f5ff53b4SAl Viro 		n = copy_from_iter(&gso, sizeof(gso), from);
1134f5ff53b4SAl Viro 		if (n != sizeof(gso))
1135f43798c2SRusty Russell 			return -EFAULT;
1136f43798c2SRusty Russell 
11374909122fSHerbert Xu 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
113856f0dcc5SMichael S. Tsirkin 		    tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
113956f0dcc5SMichael S. Tsirkin 			gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
11404909122fSHerbert Xu 
114156f0dcc5SMichael S. Tsirkin 		if (tun16_to_cpu(tun, gso.hdr_len) > len)
1142f43798c2SRusty Russell 			return -EINVAL;
1143d8febb77SHerbert Xu 		iov_iter_advance(from, tun->vnet_hdr_sz - sizeof(gso));
1144f43798c2SRusty Russell 	}
1145f43798c2SRusty Russell 
114640630b82SMichael S. Tsirkin 	if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1147a504b86eSstephen hemminger 		align += NET_IP_ALIGN;
11480eca93bcSHerbert Xu 		if (unlikely(len < ETH_HLEN ||
114956f0dcc5SMichael S. Tsirkin 			     (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1150e01bf1c8SRusty Russell 			return -EINVAL;
1151e01bf1c8SRusty Russell 	}
11521da177e4SLinus Torvalds 
115396f8d9ecSJason Wang 	good_linear = SKB_MAX_HEAD(align);
115496f8d9ecSJason Wang 
115588529176SJason Wang 	if (msg_control) {
1156f5ff53b4SAl Viro 		struct iov_iter i = *from;
1157f5ff53b4SAl Viro 
115888529176SJason Wang 		/* There are 256 bytes to be copied in skb, so there is
115988529176SJason Wang 		 * enough room for skb expand head in case it is used.
11600690899bSMichael S. Tsirkin 		 * The rest of the buffer is mapped from userspace.
11610690899bSMichael S. Tsirkin 		 */
116256f0dcc5SMichael S. Tsirkin 		copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
116396f8d9ecSJason Wang 		if (copylen > good_linear)
116496f8d9ecSJason Wang 			copylen = good_linear;
11653dd5c330SJason Wang 		linear = copylen;
1166f5ff53b4SAl Viro 		iov_iter_advance(&i, copylen);
1167f5ff53b4SAl Viro 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
116888529176SJason Wang 			zerocopy = true;
116988529176SJason Wang 	}
117088529176SJason Wang 
117188529176SJason Wang 	if (!zerocopy) {
11720690899bSMichael S. Tsirkin 		copylen = len;
117356f0dcc5SMichael S. Tsirkin 		if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
117496f8d9ecSJason Wang 			linear = good_linear;
117596f8d9ecSJason Wang 		else
117656f0dcc5SMichael S. Tsirkin 			linear = tun16_to_cpu(tun, gso.hdr_len);
11773dd5c330SJason Wang 	}
11780690899bSMichael S. Tsirkin 
11793dd5c330SJason Wang 	skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
118033dccbb0SHerbert Xu 	if (IS_ERR(skb)) {
118133dccbb0SHerbert Xu 		if (PTR_ERR(skb) != -EAGAIN)
118209f75cd7SJeff Garzik 			tun->dev->stats.rx_dropped++;
118333dccbb0SHerbert Xu 		return PTR_ERR(skb);
11841da177e4SLinus Torvalds 	}
11851da177e4SLinus Torvalds 
11860690899bSMichael S. Tsirkin 	if (zerocopy)
1187f5ff53b4SAl Viro 		err = zerocopy_sg_from_iter(skb, from);
118888529176SJason Wang 	else {
1189f5ff53b4SAl Viro 		err = skb_copy_datagram_from_iter(skb, 0, from, len);
119088529176SJason Wang 		if (!err && msg_control) {
119188529176SJason Wang 			struct ubuf_info *uarg = msg_control;
119288529176SJason Wang 			uarg->callback(uarg, false);
119388529176SJason Wang 		}
119488529176SJason Wang 	}
11950690899bSMichael S. Tsirkin 
11960690899bSMichael S. Tsirkin 	if (err) {
119709f75cd7SJeff Garzik 		tun->dev->stats.rx_dropped++;
11988f22757eSDave Jones 		kfree_skb(skb);
11991da177e4SLinus Torvalds 		return -EFAULT;
12008f22757eSDave Jones 	}
12011da177e4SLinus Torvalds 
1202f43798c2SRusty Russell 	if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
120356f0dcc5SMichael S. Tsirkin 		if (!skb_partial_csum_set(skb, tun16_to_cpu(tun, gso.csum_start),
120456f0dcc5SMichael S. Tsirkin 					  tun16_to_cpu(tun, gso.csum_offset))) {
1205f43798c2SRusty Russell 			tun->dev->stats.rx_frame_errors++;
1206f43798c2SRusty Russell 			kfree_skb(skb);
1207f43798c2SRusty Russell 			return -EINVAL;
1208f43798c2SRusty Russell 		}
120988255375SMichał Mirosław 	}
1210f43798c2SRusty Russell 
12111da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
121240630b82SMichael S. Tsirkin 	case IFF_TUN:
121340630b82SMichael S. Tsirkin 		if (tun->flags & IFF_NO_PI) {
1214f09f7ee2SAng Way Chuang 			switch (skb->data[0] & 0xf0) {
1215f09f7ee2SAng Way Chuang 			case 0x40:
1216f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IP);
1217f09f7ee2SAng Way Chuang 				break;
1218f09f7ee2SAng Way Chuang 			case 0x60:
1219f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IPV6);
1220f09f7ee2SAng Way Chuang 				break;
1221f09f7ee2SAng Way Chuang 			default:
1222f09f7ee2SAng Way Chuang 				tun->dev->stats.rx_dropped++;
1223f09f7ee2SAng Way Chuang 				kfree_skb(skb);
1224f09f7ee2SAng Way Chuang 				return -EINVAL;
1225f09f7ee2SAng Way Chuang 			}
1226f09f7ee2SAng Way Chuang 		}
1227f09f7ee2SAng Way Chuang 
1228459a98edSArnaldo Carvalho de Melo 		skb_reset_mac_header(skb);
12291da177e4SLinus Torvalds 		skb->protocol = pi.proto;
12304c13eb66SArnaldo Carvalho de Melo 		skb->dev = tun->dev;
12311da177e4SLinus Torvalds 		break;
123240630b82SMichael S. Tsirkin 	case IFF_TAP:
12331da177e4SLinus Torvalds 		skb->protocol = eth_type_trans(skb, tun->dev);
12341da177e4SLinus Torvalds 		break;
12356403eab1SJoe Perches 	}
12361da177e4SLinus Torvalds 
1237f43798c2SRusty Russell 	if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1238f43798c2SRusty Russell 		pr_debug("GSO!\n");
1239f43798c2SRusty Russell 		switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1240f43798c2SRusty Russell 		case VIRTIO_NET_HDR_GSO_TCPV4:
1241c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1242f43798c2SRusty Russell 			break;
1243f43798c2SRusty Russell 		case VIRTIO_NET_HDR_GSO_TCPV6:
1244c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1245f43798c2SRusty Russell 			break;
1246e36aa25aSSridhar Samudrala 		case VIRTIO_NET_HDR_GSO_UDP:
1247c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
1248e36aa25aSSridhar Samudrala 			break;
1249f43798c2SRusty Russell 		default:
1250f43798c2SRusty Russell 			tun->dev->stats.rx_frame_errors++;
1251f43798c2SRusty Russell 			kfree_skb(skb);
1252f43798c2SRusty Russell 			return -EINVAL;
1253f43798c2SRusty Russell 		}
1254f43798c2SRusty Russell 
1255f43798c2SRusty Russell 		if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1256c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
1257f43798c2SRusty Russell 
125856f0dcc5SMichael S. Tsirkin 		skb_shinfo(skb)->gso_size = tun16_to_cpu(tun, gso.gso_size);
1259f43798c2SRusty Russell 		if (skb_shinfo(skb)->gso_size == 0) {
1260f43798c2SRusty Russell 			tun->dev->stats.rx_frame_errors++;
1261f43798c2SRusty Russell 			kfree_skb(skb);
1262f43798c2SRusty Russell 			return -EINVAL;
1263f43798c2SRusty Russell 		}
1264f43798c2SRusty Russell 
1265f43798c2SRusty Russell 		/* Header must be checked, and gso_segs computed. */
1266f43798c2SRusty Russell 		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1267f43798c2SRusty Russell 		skb_shinfo(skb)->gso_segs = 0;
1268f43798c2SRusty Russell 	}
12691da177e4SLinus Torvalds 
12700690899bSMichael S. Tsirkin 	/* copy skb_ubuf_info for callback when skb has no error */
12710690899bSMichael S. Tsirkin 	if (zerocopy) {
12720690899bSMichael S. Tsirkin 		skb_shinfo(skb)->destructor_arg = msg_control;
12730690899bSMichael S. Tsirkin 		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1274c9af6db4SPravin B Shelar 		skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
12750690899bSMichael S. Tsirkin 	}
12760690899bSMichael S. Tsirkin 
127772f65107SVlad Yasevich 	skb_reset_network_header(skb);
127840893fd0SJason Wang 	skb_probe_transport_header(skb, 0);
127938502af7SJason Wang 
12803958afa1STom Herbert 	rxhash = skb_get_hash(skb);
12811da177e4SLinus Torvalds 	netif_rx_ni(skb);
12821da177e4SLinus Torvalds 
128309f75cd7SJeff Garzik 	tun->dev->stats.rx_packets++;
128409f75cd7SJeff Garzik 	tun->dev->stats.rx_bytes += len;
12851da177e4SLinus Torvalds 
12869e85722dSJason Wang 	tun_flow_update(tun, rxhash, tfile);
12870690899bSMichael S. Tsirkin 	return total_len;
12881da177e4SLinus Torvalds }
12891da177e4SLinus Torvalds 
1290f5ff53b4SAl Viro static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
12911da177e4SLinus Torvalds {
129233dccbb0SHerbert Xu 	struct file *file = iocb->ki_filp;
1293ab46d779SHerbert Xu 	struct tun_struct *tun = tun_get(file);
129454f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
1295631ab46bSEric W. Biederman 	ssize_t result;
12961da177e4SLinus Torvalds 
12971da177e4SLinus Torvalds 	if (!tun)
12981da177e4SLinus Torvalds 		return -EBADFD;
12991da177e4SLinus Torvalds 
1300f5ff53b4SAl Viro 	result = tun_get_user(tun, tfile, NULL, from, file->f_flags & O_NONBLOCK);
1301631ab46bSEric W. Biederman 
1302631ab46bSEric W. Biederman 	tun_put(tun);
1303631ab46bSEric W. Biederman 	return result;
13041da177e4SLinus Torvalds }
13051da177e4SLinus Torvalds 
13061da177e4SLinus Torvalds /* Put packet to the user space buffer */
13076f7c156cSstephen hemminger static ssize_t tun_put_user(struct tun_struct *tun,
130854f968d6SJason Wang 			    struct tun_file *tfile,
13091da177e4SLinus Torvalds 			    struct sk_buff *skb,
1310e0b46d0eSHerbert Xu 			    struct iov_iter *iter)
13111da177e4SLinus Torvalds {
13121da177e4SLinus Torvalds 	struct tun_pi pi = { 0, skb->protocol };
1313e0b46d0eSHerbert Xu 	ssize_t total;
13148c847d25SJason Wang 	int vlan_offset = 0;
1315a8f9bfdfSHerbert Xu 	int vlan_hlen = 0;
13162eb783c4SHerbert Xu 	int vnet_hdr_sz = 0;
1317a8f9bfdfSHerbert Xu 
1318df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb))
1319a8f9bfdfSHerbert Xu 		vlan_hlen = VLAN_HLEN;
13201da177e4SLinus Torvalds 
132140630b82SMichael S. Tsirkin 	if (tun->flags & IFF_VNET_HDR)
13222eb783c4SHerbert Xu 		vnet_hdr_sz = tun->vnet_hdr_sz;
13231da177e4SLinus Torvalds 
1324e0b46d0eSHerbert Xu 	total = skb->len + vlan_hlen + vnet_hdr_sz;
1325e0b46d0eSHerbert Xu 
132640630b82SMichael S. Tsirkin 	if (!(tun->flags & IFF_NO_PI)) {
1327e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < sizeof(pi))
13281da177e4SLinus Torvalds 			return -EINVAL;
13291da177e4SLinus Torvalds 
1330e0b46d0eSHerbert Xu 		total += sizeof(pi);
1331e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < total) {
13321da177e4SLinus Torvalds 			/* Packet will be striped */
13331da177e4SLinus Torvalds 			pi.flags |= TUN_PKT_STRIP;
13341da177e4SLinus Torvalds 		}
13351da177e4SLinus Torvalds 
1336e0b46d0eSHerbert Xu 		if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
13371da177e4SLinus Torvalds 			return -EFAULT;
13381da177e4SLinus Torvalds 	}
13391da177e4SLinus Torvalds 
13402eb783c4SHerbert Xu 	if (vnet_hdr_sz) {
1341f43798c2SRusty Russell 		struct virtio_net_hdr gso = { 0 }; /* no info leak */
1342e0b46d0eSHerbert Xu 		if (iov_iter_count(iter) < vnet_hdr_sz)
1343f43798c2SRusty Russell 			return -EINVAL;
1344f43798c2SRusty Russell 
1345f43798c2SRusty Russell 		if (skb_is_gso(skb)) {
1346f43798c2SRusty Russell 			struct skb_shared_info *sinfo = skb_shinfo(skb);
1347f43798c2SRusty Russell 
1348f43798c2SRusty Russell 			/* This is a hint as to how much should be linear. */
134956f0dcc5SMichael S. Tsirkin 			gso.hdr_len = cpu_to_tun16(tun, skb_headlen(skb));
135056f0dcc5SMichael S. Tsirkin 			gso.gso_size = cpu_to_tun16(tun, sinfo->gso_size);
1351f43798c2SRusty Russell 			if (sinfo->gso_type & SKB_GSO_TCPV4)
1352f43798c2SRusty Russell 				gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1353f43798c2SRusty Russell 			else if (sinfo->gso_type & SKB_GSO_TCPV6)
1354f43798c2SRusty Russell 				gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1355e3e3c423SVlad Yasevich 			else if (sinfo->gso_type & SKB_GSO_UDP)
1356e3e3c423SVlad Yasevich 				gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1357ef3db4a5SMichael S. Tsirkin 			else {
13586b8a66eeSJoe Perches 				pr_err("unexpected GSO type: "
1359ef3db4a5SMichael S. Tsirkin 				       "0x%x, gso_size %d, hdr_len %d\n",
136056f0dcc5SMichael S. Tsirkin 				       sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
136156f0dcc5SMichael S. Tsirkin 				       tun16_to_cpu(tun, gso.hdr_len));
1362ef3db4a5SMichael S. Tsirkin 				print_hex_dump(KERN_ERR, "tun: ",
1363ef3db4a5SMichael S. Tsirkin 					       DUMP_PREFIX_NONE,
1364ef3db4a5SMichael S. Tsirkin 					       16, 1, skb->head,
136556f0dcc5SMichael S. Tsirkin 					       min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
1366ef3db4a5SMichael S. Tsirkin 				WARN_ON_ONCE(1);
1367ef3db4a5SMichael S. Tsirkin 				return -EINVAL;
1368ef3db4a5SMichael S. Tsirkin 			}
1369f43798c2SRusty Russell 			if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1370f43798c2SRusty Russell 				gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1371f43798c2SRusty Russell 		} else
1372f43798c2SRusty Russell 			gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1373f43798c2SRusty Russell 
1374f43798c2SRusty Russell 		if (skb->ip_summed == CHECKSUM_PARTIAL) {
1375f43798c2SRusty Russell 			gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
137656f0dcc5SMichael S. Tsirkin 			gso.csum_start = cpu_to_tun16(tun, skb_checksum_start_offset(skb) +
137756f0dcc5SMichael S. Tsirkin 						      vlan_hlen);
137856f0dcc5SMichael S. Tsirkin 			gso.csum_offset = cpu_to_tun16(tun, skb->csum_offset);
137910a8d94aSJason Wang 		} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
138010a8d94aSJason Wang 			gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1381f43798c2SRusty Russell 		} /* else everything is zero */
1382f43798c2SRusty Russell 
1383e0b46d0eSHerbert Xu 		if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
1384f43798c2SRusty Russell 			return -EFAULT;
13858c847d25SJason Wang 
13868c847d25SJason Wang 		iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
1387f43798c2SRusty Russell 	}
1388f43798c2SRusty Russell 
1389a8f9bfdfSHerbert Xu 	if (vlan_hlen) {
1390e0b46d0eSHerbert Xu 		int ret;
13916680ec68SJason Wang 		struct {
13926680ec68SJason Wang 			__be16 h_vlan_proto;
13936680ec68SJason Wang 			__be16 h_vlan_TCI;
13946680ec68SJason Wang 		} veth;
13951da177e4SLinus Torvalds 
13966680ec68SJason Wang 		veth.h_vlan_proto = skb->vlan_proto;
1397df8a39deSJiri Pirko 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
13981da177e4SLinus Torvalds 
13996680ec68SJason Wang 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
14006680ec68SJason Wang 
1401e0b46d0eSHerbert Xu 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
1402e0b46d0eSHerbert Xu 		if (ret || !iov_iter_count(iter))
14036680ec68SJason Wang 			goto done;
14046680ec68SJason Wang 
1405e0b46d0eSHerbert Xu 		ret = copy_to_iter(&veth, sizeof(veth), iter);
1406e0b46d0eSHerbert Xu 		if (ret != sizeof(veth) || !iov_iter_count(iter))
14076680ec68SJason Wang 			goto done;
14086680ec68SJason Wang 	}
14096680ec68SJason Wang 
1410e0b46d0eSHerbert Xu 	skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
14116680ec68SJason Wang 
14126680ec68SJason Wang done:
141309f75cd7SJeff Garzik 	tun->dev->stats.tx_packets++;
1414e0b46d0eSHerbert Xu 	tun->dev->stats.tx_bytes += skb->len + vlan_hlen;
14151da177e4SLinus Torvalds 
14161da177e4SLinus Torvalds 	return total;
14171da177e4SLinus Torvalds }
14181da177e4SLinus Torvalds 
141954f968d6SJason Wang static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
14209b067034SAl Viro 			   struct iov_iter *to,
14219b067034SAl Viro 			   int noblock)
14221da177e4SLinus Torvalds {
14231da177e4SLinus Torvalds 	struct sk_buff *skb;
14249b067034SAl Viro 	ssize_t ret;
14259e641bdcSXi Wang 	int peeked, err, off = 0;
14261da177e4SLinus Torvalds 
14273872baf6SRami Rosen 	tun_debug(KERN_INFO, tun, "tun_do_read\n");
14281da177e4SLinus Torvalds 
14299b067034SAl Viro 	if (!iov_iter_count(to))
14309b067034SAl Viro 		return 0;
14311da177e4SLinus Torvalds 
14329e641bdcSXi Wang 	if (tun->dev->reg_state != NETREG_REGISTERED)
14339e641bdcSXi Wang 		return -EIO;
14341da177e4SLinus Torvalds 
14359e641bdcSXi Wang 	/* Read frames from queue */
14369e641bdcSXi Wang 	skb = __skb_recv_datagram(tfile->socket.sk, noblock ? MSG_DONTWAIT : 0,
14379e641bdcSXi Wang 				  &peeked, &off, &err);
1438e0b46d0eSHerbert Xu 	if (!skb)
1439957f094fSAlex Gartrell 		return err;
1440e0b46d0eSHerbert Xu 
14419b067034SAl Viro 	ret = tun_put_user(tun, tfile, skb, to);
1442f51a5e82SJason Wang 	if (unlikely(ret < 0))
14431da177e4SLinus Torvalds 		kfree_skb(skb);
1444f51a5e82SJason Wang 	else
1445f51a5e82SJason Wang 		consume_skb(skb);
14461da177e4SLinus Torvalds 
144705c2828cSMichael S. Tsirkin 	return ret;
144805c2828cSMichael S. Tsirkin }
144905c2828cSMichael S. Tsirkin 
14509b067034SAl Viro static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
145105c2828cSMichael S. Tsirkin {
145205c2828cSMichael S. Tsirkin 	struct file *file = iocb->ki_filp;
145305c2828cSMichael S. Tsirkin 	struct tun_file *tfile = file->private_data;
145405c2828cSMichael S. Tsirkin 	struct tun_struct *tun = __tun_get(tfile);
14559b067034SAl Viro 	ssize_t len = iov_iter_count(to), ret;
145605c2828cSMichael S. Tsirkin 
145705c2828cSMichael S. Tsirkin 	if (!tun)
145805c2828cSMichael S. Tsirkin 		return -EBADFD;
14599b067034SAl Viro 	ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK);
146042404c09SDavid S. Miller 	ret = min_t(ssize_t, ret, len);
1461d0b7da8aSZhi Yong Wu 	if (ret > 0)
1462d0b7da8aSZhi Yong Wu 		iocb->ki_pos = ret;
1463631ab46bSEric W. Biederman 	tun_put(tun);
14641da177e4SLinus Torvalds 	return ret;
14651da177e4SLinus Torvalds }
14661da177e4SLinus Torvalds 
146796442e42SJason Wang static void tun_free_netdev(struct net_device *dev)
146896442e42SJason Wang {
146996442e42SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
147096442e42SJason Wang 
14714008e97fSJason Wang 	BUG_ON(!(list_empty(&tun->disabled)));
147296442e42SJason Wang 	tun_flow_uninit(tun);
14735dbbaf2dSPaul Moore 	security_tun_dev_free_security(tun->security);
147496442e42SJason Wang 	free_netdev(dev);
147596442e42SJason Wang }
147696442e42SJason Wang 
14771da177e4SLinus Torvalds static void tun_setup(struct net_device *dev)
14781da177e4SLinus Torvalds {
14791da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
14801da177e4SLinus Torvalds 
14810625c883SEric W. Biederman 	tun->owner = INVALID_UID;
14820625c883SEric W. Biederman 	tun->group = INVALID_GID;
14831da177e4SLinus Torvalds 
14841da177e4SLinus Torvalds 	dev->ethtool_ops = &tun_ethtool_ops;
148596442e42SJason Wang 	dev->destructor = tun_free_netdev;
14861da177e4SLinus Torvalds }
14871da177e4SLinus Torvalds 
1488f019a7a5SEric W. Biederman /* Trivial set of netlink ops to allow deleting tun or tap
1489f019a7a5SEric W. Biederman  * device with netlink.
1490f019a7a5SEric W. Biederman  */
1491f019a7a5SEric W. Biederman static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1492f019a7a5SEric W. Biederman {
1493f019a7a5SEric W. Biederman 	return -EINVAL;
1494f019a7a5SEric W. Biederman }
1495f019a7a5SEric W. Biederman 
1496f019a7a5SEric W. Biederman static struct rtnl_link_ops tun_link_ops __read_mostly = {
1497f019a7a5SEric W. Biederman 	.kind		= DRV_NAME,
1498f019a7a5SEric W. Biederman 	.priv_size	= sizeof(struct tun_struct),
1499f019a7a5SEric W. Biederman 	.setup		= tun_setup,
1500f019a7a5SEric W. Biederman 	.validate	= tun_validate,
1501f019a7a5SEric W. Biederman };
1502f019a7a5SEric W. Biederman 
150333dccbb0SHerbert Xu static void tun_sock_write_space(struct sock *sk)
150433dccbb0SHerbert Xu {
150554f968d6SJason Wang 	struct tun_file *tfile;
150643815482SEric Dumazet 	wait_queue_head_t *wqueue;
150733dccbb0SHerbert Xu 
150833dccbb0SHerbert Xu 	if (!sock_writeable(sk))
150933dccbb0SHerbert Xu 		return;
151033dccbb0SHerbert Xu 
15119cd3e072SEric Dumazet 	if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
151233dccbb0SHerbert Xu 		return;
151333dccbb0SHerbert Xu 
151443815482SEric Dumazet 	wqueue = sk_sleep(sk);
151543815482SEric Dumazet 	if (wqueue && waitqueue_active(wqueue))
151643815482SEric Dumazet 		wake_up_interruptible_sync_poll(wqueue, POLLOUT |
151705c2828cSMichael S. Tsirkin 						POLLWRNORM | POLLWRBAND);
1518c722c625SHerbert Xu 
151954f968d6SJason Wang 	tfile = container_of(sk, struct tun_file, sk);
152054f968d6SJason Wang 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
152133dccbb0SHerbert Xu }
152233dccbb0SHerbert Xu 
15231b784140SYing Xue static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
152405c2828cSMichael S. Tsirkin {
152554f968d6SJason Wang 	int ret;
152654f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
152754f968d6SJason Wang 	struct tun_struct *tun = __tun_get(tfile);
152854f968d6SJason Wang 
152954f968d6SJason Wang 	if (!tun)
153054f968d6SJason Wang 		return -EBADFD;
1531f5ff53b4SAl Viro 
1532c0371da6SAl Viro 	ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
1533f5ff53b4SAl Viro 			   m->msg_flags & MSG_DONTWAIT);
153454f968d6SJason Wang 	tun_put(tun);
153554f968d6SJason Wang 	return ret;
153605c2828cSMichael S. Tsirkin }
153705c2828cSMichael S. Tsirkin 
15381b784140SYing Xue static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
153905c2828cSMichael S. Tsirkin 		       int flags)
154005c2828cSMichael S. Tsirkin {
154154f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
154254f968d6SJason Wang 	struct tun_struct *tun = __tun_get(tfile);
154305c2828cSMichael S. Tsirkin 	int ret;
154454f968d6SJason Wang 
154554f968d6SJason Wang 	if (!tun)
154654f968d6SJason Wang 		return -EBADFD;
154754f968d6SJason Wang 
1548eda29772SRichard Cochran 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
15493811ae76SGao feng 		ret = -EINVAL;
15503811ae76SGao feng 		goto out;
15513811ae76SGao feng 	}
1552eda29772SRichard Cochran 	if (flags & MSG_ERRQUEUE) {
1553eda29772SRichard Cochran 		ret = sock_recv_errqueue(sock->sk, m, total_len,
1554eda29772SRichard Cochran 					 SOL_PACKET, TUN_TX_TIMESTAMP);
1555eda29772SRichard Cochran 		goto out;
1556eda29772SRichard Cochran 	}
1557c0371da6SAl Viro 	ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT);
155887897931SAlex Gartrell 	if (ret > (ssize_t)total_len) {
155942404c09SDavid S. Miller 		m->msg_flags |= MSG_TRUNC;
156042404c09SDavid S. Miller 		ret = flags & MSG_TRUNC ? ret : total_len;
156142404c09SDavid S. Miller 	}
15623811ae76SGao feng out:
156354f968d6SJason Wang 	tun_put(tun);
156405c2828cSMichael S. Tsirkin 	return ret;
156505c2828cSMichael S. Tsirkin }
156605c2828cSMichael S. Tsirkin 
156705c2828cSMichael S. Tsirkin /* Ops structure to mimic raw sockets with tun */
156805c2828cSMichael S. Tsirkin static const struct proto_ops tun_socket_ops = {
156905c2828cSMichael S. Tsirkin 	.sendmsg = tun_sendmsg,
157005c2828cSMichael S. Tsirkin 	.recvmsg = tun_recvmsg,
157105c2828cSMichael S. Tsirkin };
157205c2828cSMichael S. Tsirkin 
157333dccbb0SHerbert Xu static struct proto tun_proto = {
157433dccbb0SHerbert Xu 	.name		= "tun",
157533dccbb0SHerbert Xu 	.owner		= THIS_MODULE,
157654f968d6SJason Wang 	.obj_size	= sizeof(struct tun_file),
157733dccbb0SHerbert Xu };
1578f019a7a5SEric W. Biederman 
1579980c9e8cSDavid Woodhouse static int tun_flags(struct tun_struct *tun)
1580980c9e8cSDavid Woodhouse {
1581031f5e03SMichael S. Tsirkin 	return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
1582980c9e8cSDavid Woodhouse }
1583980c9e8cSDavid Woodhouse 
1584980c9e8cSDavid Woodhouse static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1585980c9e8cSDavid Woodhouse 			      char *buf)
1586980c9e8cSDavid Woodhouse {
1587980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1588980c9e8cSDavid Woodhouse 	return sprintf(buf, "0x%x\n", tun_flags(tun));
1589980c9e8cSDavid Woodhouse }
1590980c9e8cSDavid Woodhouse 
1591980c9e8cSDavid Woodhouse static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1592980c9e8cSDavid Woodhouse 			      char *buf)
1593980c9e8cSDavid Woodhouse {
1594980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
15950625c883SEric W. Biederman 	return uid_valid(tun->owner)?
15960625c883SEric W. Biederman 		sprintf(buf, "%u\n",
15970625c883SEric W. Biederman 			from_kuid_munged(current_user_ns(), tun->owner)):
15980625c883SEric W. Biederman 		sprintf(buf, "-1\n");
1599980c9e8cSDavid Woodhouse }
1600980c9e8cSDavid Woodhouse 
1601980c9e8cSDavid Woodhouse static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1602980c9e8cSDavid Woodhouse 			      char *buf)
1603980c9e8cSDavid Woodhouse {
1604980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
16050625c883SEric W. Biederman 	return gid_valid(tun->group) ?
16060625c883SEric W. Biederman 		sprintf(buf, "%u\n",
16070625c883SEric W. Biederman 			from_kgid_munged(current_user_ns(), tun->group)):
16080625c883SEric W. Biederman 		sprintf(buf, "-1\n");
1609980c9e8cSDavid Woodhouse }
1610980c9e8cSDavid Woodhouse 
1611980c9e8cSDavid Woodhouse static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1612980c9e8cSDavid Woodhouse static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1613980c9e8cSDavid Woodhouse static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1614980c9e8cSDavid Woodhouse 
1615c4d33e24STakashi Iwai static struct attribute *tun_dev_attrs[] = {
1616c4d33e24STakashi Iwai 	&dev_attr_tun_flags.attr,
1617c4d33e24STakashi Iwai 	&dev_attr_owner.attr,
1618c4d33e24STakashi Iwai 	&dev_attr_group.attr,
1619c4d33e24STakashi Iwai 	NULL
1620c4d33e24STakashi Iwai };
1621c4d33e24STakashi Iwai 
1622c4d33e24STakashi Iwai static const struct attribute_group tun_attr_group = {
1623c4d33e24STakashi Iwai 	.attrs = tun_dev_attrs
1624c4d33e24STakashi Iwai };
1625c4d33e24STakashi Iwai 
1626d647a591SPavel Emelyanov static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
16271da177e4SLinus Torvalds {
16281da177e4SLinus Torvalds 	struct tun_struct *tun;
162954f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
16301da177e4SLinus Torvalds 	struct net_device *dev;
16311da177e4SLinus Torvalds 	int err;
16321da177e4SLinus Torvalds 
16337c0c3b1aSJason Wang 	if (tfile->detached)
16347c0c3b1aSJason Wang 		return -EINVAL;
16357c0c3b1aSJason Wang 
163674a3e5a7SEric W. Biederman 	dev = __dev_get_by_name(net, ifr->ifr_name);
163774a3e5a7SEric W. Biederman 	if (dev) {
1638f85ba780SDavid Woodhouse 		if (ifr->ifr_flags & IFF_TUN_EXCL)
1639f85ba780SDavid Woodhouse 			return -EBUSY;
164074a3e5a7SEric W. Biederman 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
164174a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
164274a3e5a7SEric W. Biederman 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
164374a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
164474a3e5a7SEric W. Biederman 		else
164574a3e5a7SEric W. Biederman 			return -EINVAL;
164674a3e5a7SEric W. Biederman 
16478e6d91aeSJason Wang 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
164840630b82SMichael S. Tsirkin 		    !!(tun->flags & IFF_MULTI_QUEUE))
16498e6d91aeSJason Wang 			return -EINVAL;
16508e6d91aeSJason Wang 
1651cde8b15fSJason Wang 		if (tun_not_capable(tun))
16522b980dbdSPaul Moore 			return -EPERM;
16535dbbaf2dSPaul Moore 		err = security_tun_dev_open(tun->security);
16542b980dbdSPaul Moore 		if (err < 0)
16552b980dbdSPaul Moore 			return err;
16562b980dbdSPaul Moore 
1657849c9b6fSPavel Emelyanov 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
1658a7385ba2SEric W. Biederman 		if (err < 0)
1659a7385ba2SEric W. Biederman 			return err;
16604008e97fSJason Wang 
166140630b82SMichael S. Tsirkin 		if (tun->flags & IFF_MULTI_QUEUE &&
1662e8dbad66SJason Wang 		    (tun->numqueues + tun->numdisabled > 1)) {
1663e8dbad66SJason Wang 			/* One or more queue has already been attached, no need
1664e8dbad66SJason Wang 			 * to initialize the device again.
1665e8dbad66SJason Wang 			 */
1666e8dbad66SJason Wang 			return 0;
1667e8dbad66SJason Wang 		}
166886a264abSDavid Howells 	}
16691da177e4SLinus Torvalds 	else {
16701da177e4SLinus Torvalds 		char *name;
16711da177e4SLinus Torvalds 		unsigned long flags = 0;
1672edfb6a14SJason Wang 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1673edfb6a14SJason Wang 			     MAX_TAP_QUEUES : 1;
16741da177e4SLinus Torvalds 
1675c260b772SEric W. Biederman 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1676ca6bb5d7SDavid Woodhouse 			return -EPERM;
16772b980dbdSPaul Moore 		err = security_tun_dev_create();
16782b980dbdSPaul Moore 		if (err < 0)
16792b980dbdSPaul Moore 			return err;
1680ca6bb5d7SDavid Woodhouse 
16811da177e4SLinus Torvalds 		/* Set dev type */
16821da177e4SLinus Torvalds 		if (ifr->ifr_flags & IFF_TUN) {
16831da177e4SLinus Torvalds 			/* TUN device */
168440630b82SMichael S. Tsirkin 			flags |= IFF_TUN;
16851da177e4SLinus Torvalds 			name = "tun%d";
16861da177e4SLinus Torvalds 		} else if (ifr->ifr_flags & IFF_TAP) {
16871da177e4SLinus Torvalds 			/* TAP device */
168840630b82SMichael S. Tsirkin 			flags |= IFF_TAP;
16891da177e4SLinus Torvalds 			name = "tap%d";
16901da177e4SLinus Torvalds 		} else
169136989b90SKusanagi Kouichi 			return -EINVAL;
16921da177e4SLinus Torvalds 
16931da177e4SLinus Torvalds 		if (*ifr->ifr_name)
16941da177e4SLinus Torvalds 			name = ifr->ifr_name;
16951da177e4SLinus Torvalds 
1696c8d68e6bSJason Wang 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1697c835a677STom Gundersen 				       NET_NAME_UNKNOWN, tun_setup, queues,
1698c835a677STom Gundersen 				       queues);
1699edfb6a14SJason Wang 
17001da177e4SLinus Torvalds 		if (!dev)
17011da177e4SLinus Torvalds 			return -ENOMEM;
17021da177e4SLinus Torvalds 
1703fc54c658SPavel Emelyanov 		dev_net_set(dev, net);
1704f019a7a5SEric W. Biederman 		dev->rtnl_link_ops = &tun_link_ops;
1705fb7589a1SPavel Emelyanov 		dev->ifindex = tfile->ifindex;
1706c4d33e24STakashi Iwai 		dev->sysfs_groups[0] = &tun_attr_group;
1707758e43b7SStephen Hemminger 
17081da177e4SLinus Torvalds 		tun = netdev_priv(dev);
17091da177e4SLinus Torvalds 		tun->dev = dev;
17101da177e4SLinus Torvalds 		tun->flags = flags;
1711f271b2ccSMax Krasnyansky 		tun->txflt.count = 0;
1712d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
17131da177e4SLinus Torvalds 
1714eaea34b2SPaolo Abeni 		tun->align = NET_SKB_PAD;
171554f968d6SJason Wang 		tun->filter_attached = false;
171654f968d6SJason Wang 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
171733dccbb0SHerbert Xu 
171896442e42SJason Wang 		spin_lock_init(&tun->lock);
171996442e42SJason Wang 
17205dbbaf2dSPaul Moore 		err = security_tun_dev_alloc_security(&tun->security);
17215dbbaf2dSPaul Moore 		if (err < 0)
17225dbbaf2dSPaul Moore 			goto err_free_dev;
17232b980dbdSPaul Moore 
17241da177e4SLinus Torvalds 		tun_net_init(dev);
1725944a1376SPavel Emelyanov 		tun_flow_init(tun);
172696442e42SJason Wang 
172788255375SMichał Mirosław 		dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
17286680ec68SJason Wang 				   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
17296680ec68SJason Wang 				   NETIF_F_HW_VLAN_STAG_TX;
173088255375SMichał Mirosław 		dev->features = dev->hw_features;
17316671b224SFernando Luis Vazquez Cao 		dev->vlan_features = dev->features &
17326671b224SFernando Luis Vazquez Cao 				     ~(NETIF_F_HW_VLAN_CTAG_TX |
17336671b224SFernando Luis Vazquez Cao 				       NETIF_F_HW_VLAN_STAG_TX);
173488255375SMichał Mirosław 
17354008e97fSJason Wang 		INIT_LIST_HEAD(&tun->disabled);
1736849c9b6fSPavel Emelyanov 		err = tun_attach(tun, file, false);
1737eb0fb363SJason Wang 		if (err < 0)
1738662ca437SJason Wang 			goto err_free_flow;
1739eb0fb363SJason Wang 
17401da177e4SLinus Torvalds 		err = register_netdevice(tun->dev);
17411da177e4SLinus Torvalds 		if (err < 0)
1742662ca437SJason Wang 			goto err_detach;
1743af668b3cSMichael S. Tsirkin 	}
1744980c9e8cSDavid Woodhouse 
1745eb0fb363SJason Wang 	netif_carrier_on(tun->dev);
17461da177e4SLinus Torvalds 
17476b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_set_iff\n");
17481da177e4SLinus Torvalds 
1749031f5e03SMichael S. Tsirkin 	tun->flags = (tun->flags & ~TUN_FEATURES) |
1750031f5e03SMichael S. Tsirkin 		(ifr->ifr_flags & TUN_FEATURES);
1751c8d68e6bSJason Wang 
1752e35259a9SMax Krasnyansky 	/* Make sure persistent devices do not get stuck in
1753e35259a9SMax Krasnyansky 	 * xoff state.
1754e35259a9SMax Krasnyansky 	 */
1755e35259a9SMax Krasnyansky 	if (netif_running(tun->dev))
1756c8d68e6bSJason Wang 		netif_tx_wake_all_queues(tun->dev);
1757e35259a9SMax Krasnyansky 
17581da177e4SLinus Torvalds 	strcpy(ifr->ifr_name, tun->dev->name);
17591da177e4SLinus Torvalds 	return 0;
17601da177e4SLinus Torvalds 
1761662ca437SJason Wang err_detach:
1762662ca437SJason Wang 	tun_detach_all(dev);
1763662ca437SJason Wang err_free_flow:
1764662ca437SJason Wang 	tun_flow_uninit(tun);
1765662ca437SJason Wang 	security_tun_dev_free_security(tun->security);
17661da177e4SLinus Torvalds err_free_dev:
17671da177e4SLinus Torvalds 	free_netdev(dev);
17681da177e4SLinus Torvalds 	return err;
17691da177e4SLinus Torvalds }
17701da177e4SLinus Torvalds 
17719ce99cf6SRami Rosen static void tun_get_iff(struct net *net, struct tun_struct *tun,
1772876bfd4dSHerbert Xu 		       struct ifreq *ifr)
1773e3b99556SMark McLoughlin {
17746b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1775e3b99556SMark McLoughlin 
1776e3b99556SMark McLoughlin 	strcpy(ifr->ifr_name, tun->dev->name);
1777e3b99556SMark McLoughlin 
1778980c9e8cSDavid Woodhouse 	ifr->ifr_flags = tun_flags(tun);
1779e3b99556SMark McLoughlin 
1780e3b99556SMark McLoughlin }
1781e3b99556SMark McLoughlin 
17825228ddc9SRusty Russell /* This is like a cut-down ethtool ops, except done via tun fd so no
17835228ddc9SRusty Russell  * privs required. */
178488255375SMichał Mirosław static int set_offload(struct tun_struct *tun, unsigned long arg)
17855228ddc9SRusty Russell {
1786c8f44affSMichał Mirosław 	netdev_features_t features = 0;
17875228ddc9SRusty Russell 
17885228ddc9SRusty Russell 	if (arg & TUN_F_CSUM) {
178988255375SMichał Mirosław 		features |= NETIF_F_HW_CSUM;
17905228ddc9SRusty Russell 		arg &= ~TUN_F_CSUM;
17915228ddc9SRusty Russell 
17925228ddc9SRusty Russell 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
17935228ddc9SRusty Russell 			if (arg & TUN_F_TSO_ECN) {
17945228ddc9SRusty Russell 				features |= NETIF_F_TSO_ECN;
17955228ddc9SRusty Russell 				arg &= ~TUN_F_TSO_ECN;
17965228ddc9SRusty Russell 			}
17975228ddc9SRusty Russell 			if (arg & TUN_F_TSO4)
17985228ddc9SRusty Russell 				features |= NETIF_F_TSO;
17995228ddc9SRusty Russell 			if (arg & TUN_F_TSO6)
18005228ddc9SRusty Russell 				features |= NETIF_F_TSO6;
18015228ddc9SRusty Russell 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
18025228ddc9SRusty Russell 		}
1803e3e3c423SVlad Yasevich 
1804e3e3c423SVlad Yasevich 		if (arg & TUN_F_UFO) {
1805e3e3c423SVlad Yasevich 			features |= NETIF_F_UFO;
1806e3e3c423SVlad Yasevich 			arg &= ~TUN_F_UFO;
1807e3e3c423SVlad Yasevich 		}
18085228ddc9SRusty Russell 	}
18095228ddc9SRusty Russell 
18105228ddc9SRusty Russell 	/* This gives the user a way to test for new features in future by
18115228ddc9SRusty Russell 	 * trying to set them. */
18125228ddc9SRusty Russell 	if (arg)
18135228ddc9SRusty Russell 		return -EINVAL;
18145228ddc9SRusty Russell 
181588255375SMichał Mirosław 	tun->set_features = features;
181688255375SMichał Mirosław 	netdev_update_features(tun->dev);
18175228ddc9SRusty Russell 
18185228ddc9SRusty Russell 	return 0;
18195228ddc9SRusty Russell }
18205228ddc9SRusty Russell 
1821c8d68e6bSJason Wang static void tun_detach_filter(struct tun_struct *tun, int n)
1822c8d68e6bSJason Wang {
1823c8d68e6bSJason Wang 	int i;
1824c8d68e6bSJason Wang 	struct tun_file *tfile;
1825c8d68e6bSJason Wang 
1826c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
1827b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1828*8ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
1829*8ced425eSHannes Frederic Sowa 		sk_detach_filter(tfile->socket.sk);
1830*8ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
1831c8d68e6bSJason Wang 	}
1832c8d68e6bSJason Wang 
1833c8d68e6bSJason Wang 	tun->filter_attached = false;
1834c8d68e6bSJason Wang }
1835c8d68e6bSJason Wang 
1836c8d68e6bSJason Wang static int tun_attach_filter(struct tun_struct *tun)
1837c8d68e6bSJason Wang {
1838c8d68e6bSJason Wang 	int i, ret = 0;
1839c8d68e6bSJason Wang 	struct tun_file *tfile;
1840c8d68e6bSJason Wang 
1841c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
1842b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1843*8ced425eSHannes Frederic Sowa 		lock_sock(tfile->socket.sk);
1844*8ced425eSHannes Frederic Sowa 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1845*8ced425eSHannes Frederic Sowa 		release_sock(tfile->socket.sk);
1846c8d68e6bSJason Wang 		if (ret) {
1847c8d68e6bSJason Wang 			tun_detach_filter(tun, i);
1848c8d68e6bSJason Wang 			return ret;
1849c8d68e6bSJason Wang 		}
1850c8d68e6bSJason Wang 	}
1851c8d68e6bSJason Wang 
1852c8d68e6bSJason Wang 	tun->filter_attached = true;
1853c8d68e6bSJason Wang 	return ret;
1854c8d68e6bSJason Wang }
1855c8d68e6bSJason Wang 
1856c8d68e6bSJason Wang static void tun_set_sndbuf(struct tun_struct *tun)
1857c8d68e6bSJason Wang {
1858c8d68e6bSJason Wang 	struct tun_file *tfile;
1859c8d68e6bSJason Wang 	int i;
1860c8d68e6bSJason Wang 
1861c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
1862b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1863c8d68e6bSJason Wang 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1864c8d68e6bSJason Wang 	}
1865c8d68e6bSJason Wang }
1866c8d68e6bSJason Wang 
1867cde8b15fSJason Wang static int tun_set_queue(struct file *file, struct ifreq *ifr)
1868cde8b15fSJason Wang {
1869cde8b15fSJason Wang 	struct tun_file *tfile = file->private_data;
1870cde8b15fSJason Wang 	struct tun_struct *tun;
1871cde8b15fSJason Wang 	int ret = 0;
1872cde8b15fSJason Wang 
1873cde8b15fSJason Wang 	rtnl_lock();
1874cde8b15fSJason Wang 
1875cde8b15fSJason Wang 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
18764008e97fSJason Wang 		tun = tfile->detached;
18775dbbaf2dSPaul Moore 		if (!tun) {
1878cde8b15fSJason Wang 			ret = -EINVAL;
18795dbbaf2dSPaul Moore 			goto unlock;
18805dbbaf2dSPaul Moore 		}
18815dbbaf2dSPaul Moore 		ret = security_tun_dev_attach_queue(tun->security);
18825dbbaf2dSPaul Moore 		if (ret < 0)
18835dbbaf2dSPaul Moore 			goto unlock;
1884849c9b6fSPavel Emelyanov 		ret = tun_attach(tun, file, false);
18854008e97fSJason Wang 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
1886b8deabd3SJason Wang 		tun = rtnl_dereference(tfile->tun);
188740630b82SMichael S. Tsirkin 		if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
18884008e97fSJason Wang 			ret = -EINVAL;
1889cde8b15fSJason Wang 		else
18904008e97fSJason Wang 			__tun_detach(tfile, false);
18914008e97fSJason Wang 	} else
1892cde8b15fSJason Wang 		ret = -EINVAL;
1893cde8b15fSJason Wang 
18945dbbaf2dSPaul Moore unlock:
1895cde8b15fSJason Wang 	rtnl_unlock();
1896cde8b15fSJason Wang 	return ret;
1897cde8b15fSJason Wang }
1898cde8b15fSJason Wang 
189950857e2aSArnd Bergmann static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
190050857e2aSArnd Bergmann 			    unsigned long arg, int ifreq_len)
19011da177e4SLinus Torvalds {
190236b50babSEric W. Biederman 	struct tun_file *tfile = file->private_data;
1903631ab46bSEric W. Biederman 	struct tun_struct *tun;
19041da177e4SLinus Torvalds 	void __user* argp = (void __user*)arg;
19051da177e4SLinus Torvalds 	struct ifreq ifr;
19060625c883SEric W. Biederman 	kuid_t owner;
19070625c883SEric W. Biederman 	kgid_t group;
190833dccbb0SHerbert Xu 	int sndbuf;
1909d9d52b51SMichael S. Tsirkin 	int vnet_hdr_sz;
1910fb7589a1SPavel Emelyanov 	unsigned int ifindex;
19111cf8e410SMichael S. Tsirkin 	int le;
1912f271b2ccSMax Krasnyansky 	int ret;
19131da177e4SLinus Torvalds 
1914cde8b15fSJason Wang 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
191550857e2aSArnd Bergmann 		if (copy_from_user(&ifr, argp, ifreq_len))
19161da177e4SLinus Torvalds 			return -EFAULT;
19178bbb1813SDavid S. Miller 	} else {
1918a117dacdSMathias Krause 		memset(&ifr, 0, sizeof(ifr));
19198bbb1813SDavid S. Miller 	}
1920631ab46bSEric W. Biederman 	if (cmd == TUNGETFEATURES) {
1921631ab46bSEric W. Biederman 		/* Currently this just means: "what IFF flags are valid?".
1922631ab46bSEric W. Biederman 		 * This is needed because we never checked for invalid flags on
1923031f5e03SMichael S. Tsirkin 		 * TUNSETIFF.
1924031f5e03SMichael S. Tsirkin 		 */
1925031f5e03SMichael S. Tsirkin 		return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
1926631ab46bSEric W. Biederman 				(unsigned int __user*)argp);
1927cde8b15fSJason Wang 	} else if (cmd == TUNSETQUEUE)
1928cde8b15fSJason Wang 		return tun_set_queue(file, &ifr);
1929631ab46bSEric W. Biederman 
1930c8d68e6bSJason Wang 	ret = 0;
1931876bfd4dSHerbert Xu 	rtnl_lock();
1932876bfd4dSHerbert Xu 
193336b50babSEric W. Biederman 	tun = __tun_get(tfile);
19341da177e4SLinus Torvalds 	if (cmd == TUNSETIFF && !tun) {
19351da177e4SLinus Torvalds 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
19361da177e4SLinus Torvalds 
1937140e807dSEric W. Biederman 		ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr);
19381da177e4SLinus Torvalds 
1939876bfd4dSHerbert Xu 		if (ret)
1940876bfd4dSHerbert Xu 			goto unlock;
19411da177e4SLinus Torvalds 
194250857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
1943876bfd4dSHerbert Xu 			ret = -EFAULT;
1944876bfd4dSHerbert Xu 		goto unlock;
19451da177e4SLinus Torvalds 	}
1946fb7589a1SPavel Emelyanov 	if (cmd == TUNSETIFINDEX) {
1947fb7589a1SPavel Emelyanov 		ret = -EPERM;
1948fb7589a1SPavel Emelyanov 		if (tun)
1949fb7589a1SPavel Emelyanov 			goto unlock;
1950fb7589a1SPavel Emelyanov 
1951fb7589a1SPavel Emelyanov 		ret = -EFAULT;
1952fb7589a1SPavel Emelyanov 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
1953fb7589a1SPavel Emelyanov 			goto unlock;
1954fb7589a1SPavel Emelyanov 
1955fb7589a1SPavel Emelyanov 		ret = 0;
1956fb7589a1SPavel Emelyanov 		tfile->ifindex = ifindex;
1957fb7589a1SPavel Emelyanov 		goto unlock;
1958fb7589a1SPavel Emelyanov 	}
19591da177e4SLinus Torvalds 
1960876bfd4dSHerbert Xu 	ret = -EBADFD;
19611da177e4SLinus Torvalds 	if (!tun)
1962876bfd4dSHerbert Xu 		goto unlock;
19631da177e4SLinus Torvalds 
19641e588338SJason Wang 	tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
19651da177e4SLinus Torvalds 
1966631ab46bSEric W. Biederman 	ret = 0;
19671da177e4SLinus Torvalds 	switch (cmd) {
1968e3b99556SMark McLoughlin 	case TUNGETIFF:
19699ce99cf6SRami Rosen 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1970e3b99556SMark McLoughlin 
19713d407a80SPavel Emelyanov 		if (tfile->detached)
19723d407a80SPavel Emelyanov 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
1973849c9b6fSPavel Emelyanov 		if (!tfile->socket.sk->sk_filter)
1974849c9b6fSPavel Emelyanov 			ifr.ifr_flags |= IFF_NOFILTER;
19753d407a80SPavel Emelyanov 
197650857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
1977631ab46bSEric W. Biederman 			ret = -EFAULT;
1978e3b99556SMark McLoughlin 		break;
1979e3b99556SMark McLoughlin 
19801da177e4SLinus Torvalds 	case TUNSETNOCSUM:
19811da177e4SLinus Torvalds 		/* Disable/Enable checksum */
19821da177e4SLinus Torvalds 
198388255375SMichał Mirosław 		/* [unimplemented] */
198488255375SMichał Mirosław 		tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
19856b8a66eeSJoe Perches 			  arg ? "disabled" : "enabled");
19861da177e4SLinus Torvalds 		break;
19871da177e4SLinus Torvalds 
19881da177e4SLinus Torvalds 	case TUNSETPERSIST:
198954f968d6SJason Wang 		/* Disable/Enable persist mode. Keep an extra reference to the
199054f968d6SJason Wang 		 * module to prevent the module being unprobed.
199154f968d6SJason Wang 		 */
199240630b82SMichael S. Tsirkin 		if (arg && !(tun->flags & IFF_PERSIST)) {
199340630b82SMichael S. Tsirkin 			tun->flags |= IFF_PERSIST;
199454f968d6SJason Wang 			__module_get(THIS_MODULE);
1995dd38bd85SJason Wang 		}
199640630b82SMichael S. Tsirkin 		if (!arg && (tun->flags & IFF_PERSIST)) {
199740630b82SMichael S. Tsirkin 			tun->flags &= ~IFF_PERSIST;
199854f968d6SJason Wang 			module_put(THIS_MODULE);
199954f968d6SJason Wang 		}
20001da177e4SLinus Torvalds 
20016b8a66eeSJoe Perches 		tun_debug(KERN_INFO, tun, "persist %s\n",
20026b8a66eeSJoe Perches 			  arg ? "enabled" : "disabled");
20031da177e4SLinus Torvalds 		break;
20041da177e4SLinus Torvalds 
20051da177e4SLinus Torvalds 	case TUNSETOWNER:
20061da177e4SLinus Torvalds 		/* Set owner of the device */
20070625c883SEric W. Biederman 		owner = make_kuid(current_user_ns(), arg);
20080625c883SEric W. Biederman 		if (!uid_valid(owner)) {
20090625c883SEric W. Biederman 			ret = -EINVAL;
20100625c883SEric W. Biederman 			break;
20110625c883SEric W. Biederman 		}
20120625c883SEric W. Biederman 		tun->owner = owner;
20131e588338SJason Wang 		tun_debug(KERN_INFO, tun, "owner set to %u\n",
20140625c883SEric W. Biederman 			  from_kuid(&init_user_ns, tun->owner));
20151da177e4SLinus Torvalds 		break;
20161da177e4SLinus Torvalds 
20178c644623SGuido Guenther 	case TUNSETGROUP:
20188c644623SGuido Guenther 		/* Set group of the device */
20190625c883SEric W. Biederman 		group = make_kgid(current_user_ns(), arg);
20200625c883SEric W. Biederman 		if (!gid_valid(group)) {
20210625c883SEric W. Biederman 			ret = -EINVAL;
20220625c883SEric W. Biederman 			break;
20230625c883SEric W. Biederman 		}
20240625c883SEric W. Biederman 		tun->group = group;
20251e588338SJason Wang 		tun_debug(KERN_INFO, tun, "group set to %u\n",
20260625c883SEric W. Biederman 			  from_kgid(&init_user_ns, tun->group));
20278c644623SGuido Guenther 		break;
20288c644623SGuido Guenther 
2029ff4cc3acSMike Kershaw 	case TUNSETLINK:
2030ff4cc3acSMike Kershaw 		/* Only allow setting the type when the interface is down */
2031ff4cc3acSMike Kershaw 		if (tun->dev->flags & IFF_UP) {
20326b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun,
20336b8a66eeSJoe Perches 				  "Linktype set failed because interface is up\n");
203448abfe05SDavid S. Miller 			ret = -EBUSY;
2035ff4cc3acSMike Kershaw 		} else {
2036ff4cc3acSMike Kershaw 			tun->dev->type = (int) arg;
20376b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun, "linktype set to %d\n",
20386b8a66eeSJoe Perches 				  tun->dev->type);
203948abfe05SDavid S. Miller 			ret = 0;
2040ff4cc3acSMike Kershaw 		}
2041631ab46bSEric W. Biederman 		break;
2042ff4cc3acSMike Kershaw 
20431da177e4SLinus Torvalds #ifdef TUN_DEBUG
20441da177e4SLinus Torvalds 	case TUNSETDEBUG:
20451da177e4SLinus Torvalds 		tun->debug = arg;
20461da177e4SLinus Torvalds 		break;
20471da177e4SLinus Torvalds #endif
20485228ddc9SRusty Russell 	case TUNSETOFFLOAD:
204988255375SMichał Mirosław 		ret = set_offload(tun, arg);
2050631ab46bSEric W. Biederman 		break;
20515228ddc9SRusty Russell 
2052f271b2ccSMax Krasnyansky 	case TUNSETTXFILTER:
2053f271b2ccSMax Krasnyansky 		/* Can be set only for TAPs */
2054631ab46bSEric W. Biederman 		ret = -EINVAL;
205540630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2056631ab46bSEric W. Biederman 			break;
2057c0e5a8c2SHarvey Harrison 		ret = update_filter(&tun->txflt, (void __user *)arg);
2058631ab46bSEric W. Biederman 		break;
20591da177e4SLinus Torvalds 
20601da177e4SLinus Torvalds 	case SIOCGIFHWADDR:
2061b595076aSUwe Kleine-König 		/* Get hw address */
2062f271b2ccSMax Krasnyansky 		memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2063f271b2ccSMax Krasnyansky 		ifr.ifr_hwaddr.sa_family = tun->dev->type;
206450857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2065631ab46bSEric W. Biederman 			ret = -EFAULT;
2066631ab46bSEric W. Biederman 		break;
20671da177e4SLinus Torvalds 
20681da177e4SLinus Torvalds 	case SIOCSIFHWADDR:
2069f271b2ccSMax Krasnyansky 		/* Set hw address */
20706b8a66eeSJoe Perches 		tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
20716b8a66eeSJoe Perches 			  ifr.ifr_hwaddr.sa_data);
207240102371SKim B. Heino 
207340102371SKim B. Heino 		ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2074631ab46bSEric W. Biederman 		break;
207533dccbb0SHerbert Xu 
207633dccbb0SHerbert Xu 	case TUNGETSNDBUF:
207754f968d6SJason Wang 		sndbuf = tfile->socket.sk->sk_sndbuf;
207833dccbb0SHerbert Xu 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
207933dccbb0SHerbert Xu 			ret = -EFAULT;
208033dccbb0SHerbert Xu 		break;
208133dccbb0SHerbert Xu 
208233dccbb0SHerbert Xu 	case TUNSETSNDBUF:
208333dccbb0SHerbert Xu 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
208433dccbb0SHerbert Xu 			ret = -EFAULT;
208533dccbb0SHerbert Xu 			break;
208633dccbb0SHerbert Xu 		}
208733dccbb0SHerbert Xu 
2088c8d68e6bSJason Wang 		tun->sndbuf = sndbuf;
2089c8d68e6bSJason Wang 		tun_set_sndbuf(tun);
209033dccbb0SHerbert Xu 		break;
209133dccbb0SHerbert Xu 
2092d9d52b51SMichael S. Tsirkin 	case TUNGETVNETHDRSZ:
2093d9d52b51SMichael S. Tsirkin 		vnet_hdr_sz = tun->vnet_hdr_sz;
2094d9d52b51SMichael S. Tsirkin 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2095d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
2096d9d52b51SMichael S. Tsirkin 		break;
2097d9d52b51SMichael S. Tsirkin 
2098d9d52b51SMichael S. Tsirkin 	case TUNSETVNETHDRSZ:
2099d9d52b51SMichael S. Tsirkin 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2100d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
2101d9d52b51SMichael S. Tsirkin 			break;
2102d9d52b51SMichael S. Tsirkin 		}
2103d9d52b51SMichael S. Tsirkin 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2104d9d52b51SMichael S. Tsirkin 			ret = -EINVAL;
2105d9d52b51SMichael S. Tsirkin 			break;
2106d9d52b51SMichael S. Tsirkin 		}
2107d9d52b51SMichael S. Tsirkin 
2108d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = vnet_hdr_sz;
2109d9d52b51SMichael S. Tsirkin 		break;
2110d9d52b51SMichael S. Tsirkin 
21111cf8e410SMichael S. Tsirkin 	case TUNGETVNETLE:
21121cf8e410SMichael S. Tsirkin 		le = !!(tun->flags & TUN_VNET_LE);
21131cf8e410SMichael S. Tsirkin 		if (put_user(le, (int __user *)argp))
21141cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
21151cf8e410SMichael S. Tsirkin 		break;
21161cf8e410SMichael S. Tsirkin 
21171cf8e410SMichael S. Tsirkin 	case TUNSETVNETLE:
21181cf8e410SMichael S. Tsirkin 		if (get_user(le, (int __user *)argp)) {
21191cf8e410SMichael S. Tsirkin 			ret = -EFAULT;
21201cf8e410SMichael S. Tsirkin 			break;
21211cf8e410SMichael S. Tsirkin 		}
21221cf8e410SMichael S. Tsirkin 		if (le)
21231cf8e410SMichael S. Tsirkin 			tun->flags |= TUN_VNET_LE;
21241cf8e410SMichael S. Tsirkin 		else
21251cf8e410SMichael S. Tsirkin 			tun->flags &= ~TUN_VNET_LE;
21261cf8e410SMichael S. Tsirkin 		break;
21271cf8e410SMichael S. Tsirkin 
21288b8e658bSGreg Kurz 	case TUNGETVNETBE:
21298b8e658bSGreg Kurz 		ret = tun_get_vnet_be(tun, argp);
21308b8e658bSGreg Kurz 		break;
21318b8e658bSGreg Kurz 
21328b8e658bSGreg Kurz 	case TUNSETVNETBE:
21338b8e658bSGreg Kurz 		ret = tun_set_vnet_be(tun, argp);
21348b8e658bSGreg Kurz 		break;
21358b8e658bSGreg Kurz 
213699405162SMichael S. Tsirkin 	case TUNATTACHFILTER:
213799405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
213899405162SMichael S. Tsirkin 		ret = -EINVAL;
213940630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
214099405162SMichael S. Tsirkin 			break;
214199405162SMichael S. Tsirkin 		ret = -EFAULT;
214254f968d6SJason Wang 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
214399405162SMichael S. Tsirkin 			break;
214499405162SMichael S. Tsirkin 
2145c8d68e6bSJason Wang 		ret = tun_attach_filter(tun);
214699405162SMichael S. Tsirkin 		break;
214799405162SMichael S. Tsirkin 
214899405162SMichael S. Tsirkin 	case TUNDETACHFILTER:
214999405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
215099405162SMichael S. Tsirkin 		ret = -EINVAL;
215140630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
215299405162SMichael S. Tsirkin 			break;
2153c8d68e6bSJason Wang 		ret = 0;
2154c8d68e6bSJason Wang 		tun_detach_filter(tun, tun->numqueues);
215599405162SMichael S. Tsirkin 		break;
215699405162SMichael S. Tsirkin 
215776975e9cSPavel Emelyanov 	case TUNGETFILTER:
215876975e9cSPavel Emelyanov 		ret = -EINVAL;
215940630b82SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
216076975e9cSPavel Emelyanov 			break;
216176975e9cSPavel Emelyanov 		ret = -EFAULT;
216276975e9cSPavel Emelyanov 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
216376975e9cSPavel Emelyanov 			break;
216476975e9cSPavel Emelyanov 		ret = 0;
216576975e9cSPavel Emelyanov 		break;
216676975e9cSPavel Emelyanov 
21671da177e4SLinus Torvalds 	default:
2168631ab46bSEric W. Biederman 		ret = -EINVAL;
2169631ab46bSEric W. Biederman 		break;
2170ee289b64SJoe Perches 	}
21711da177e4SLinus Torvalds 
2172876bfd4dSHerbert Xu unlock:
2173876bfd4dSHerbert Xu 	rtnl_unlock();
2174876bfd4dSHerbert Xu 	if (tun)
2175631ab46bSEric W. Biederman 		tun_put(tun);
2176631ab46bSEric W. Biederman 	return ret;
21771da177e4SLinus Torvalds }
21781da177e4SLinus Torvalds 
217950857e2aSArnd Bergmann static long tun_chr_ioctl(struct file *file,
218050857e2aSArnd Bergmann 			  unsigned int cmd, unsigned long arg)
218150857e2aSArnd Bergmann {
218250857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
218350857e2aSArnd Bergmann }
218450857e2aSArnd Bergmann 
218550857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
218650857e2aSArnd Bergmann static long tun_chr_compat_ioctl(struct file *file,
218750857e2aSArnd Bergmann 			 unsigned int cmd, unsigned long arg)
218850857e2aSArnd Bergmann {
218950857e2aSArnd Bergmann 	switch (cmd) {
219050857e2aSArnd Bergmann 	case TUNSETIFF:
219150857e2aSArnd Bergmann 	case TUNGETIFF:
219250857e2aSArnd Bergmann 	case TUNSETTXFILTER:
219350857e2aSArnd Bergmann 	case TUNGETSNDBUF:
219450857e2aSArnd Bergmann 	case TUNSETSNDBUF:
219550857e2aSArnd Bergmann 	case SIOCGIFHWADDR:
219650857e2aSArnd Bergmann 	case SIOCSIFHWADDR:
219750857e2aSArnd Bergmann 		arg = (unsigned long)compat_ptr(arg);
219850857e2aSArnd Bergmann 		break;
219950857e2aSArnd Bergmann 	default:
220050857e2aSArnd Bergmann 		arg = (compat_ulong_t)arg;
220150857e2aSArnd Bergmann 		break;
220250857e2aSArnd Bergmann 	}
220350857e2aSArnd Bergmann 
220450857e2aSArnd Bergmann 	/*
220550857e2aSArnd Bergmann 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
220650857e2aSArnd Bergmann 	 * the end of that structure. All fields that are used in this
220750857e2aSArnd Bergmann 	 * driver are compatible though, we don't need to convert the
220850857e2aSArnd Bergmann 	 * contents.
220950857e2aSArnd Bergmann 	 */
221050857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
221150857e2aSArnd Bergmann }
221250857e2aSArnd Bergmann #endif /* CONFIG_COMPAT */
221350857e2aSArnd Bergmann 
22141da177e4SLinus Torvalds static int tun_chr_fasync(int fd, struct file *file, int on)
22151da177e4SLinus Torvalds {
221654f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
22171da177e4SLinus Torvalds 	int ret;
22181da177e4SLinus Torvalds 
221954f968d6SJason Wang 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
22209d319522SJonathan Corbet 		goto out;
22211da177e4SLinus Torvalds 
22221da177e4SLinus Torvalds 	if (on) {
2223e0b93eddSJeff Layton 		__f_setown(file, task_pid(current), PIDTYPE_PID, 0);
222454f968d6SJason Wang 		tfile->flags |= TUN_FASYNC;
22251da177e4SLinus Torvalds 	} else
222654f968d6SJason Wang 		tfile->flags &= ~TUN_FASYNC;
22279d319522SJonathan Corbet 	ret = 0;
22289d319522SJonathan Corbet out:
22299d319522SJonathan Corbet 	return ret;
22301da177e4SLinus Torvalds }
22311da177e4SLinus Torvalds 
22321da177e4SLinus Torvalds static int tun_chr_open(struct inode *inode, struct file * file)
22331da177e4SLinus Torvalds {
2234140e807dSEric W. Biederman 	struct net *net = current->nsproxy->net_ns;
2235631ab46bSEric W. Biederman 	struct tun_file *tfile;
2236deed49fbSThomas Gleixner 
22376b8a66eeSJoe Perches 	DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2238631ab46bSEric W. Biederman 
2239140e807dSEric W. Biederman 	tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
224011aa9c28SEric W. Biederman 					    &tun_proto, 0);
2241631ab46bSEric W. Biederman 	if (!tfile)
2242631ab46bSEric W. Biederman 		return -ENOMEM;
2243c956674bSMonam Agarwal 	RCU_INIT_POINTER(tfile->tun, NULL);
224454f968d6SJason Wang 	tfile->flags = 0;
2245fb7589a1SPavel Emelyanov 	tfile->ifindex = 0;
224654f968d6SJason Wang 
224754f968d6SJason Wang 	init_waitqueue_head(&tfile->wq.wait);
22489e641bdcSXi Wang 	RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
224954f968d6SJason Wang 
225054f968d6SJason Wang 	tfile->socket.file = file;
225154f968d6SJason Wang 	tfile->socket.ops = &tun_socket_ops;
225254f968d6SJason Wang 
225354f968d6SJason Wang 	sock_init_data(&tfile->socket, &tfile->sk);
225454f968d6SJason Wang 
225554f968d6SJason Wang 	tfile->sk.sk_write_space = tun_sock_write_space;
225654f968d6SJason Wang 	tfile->sk.sk_sndbuf = INT_MAX;
225754f968d6SJason Wang 
2258631ab46bSEric W. Biederman 	file->private_data = tfile;
22594008e97fSJason Wang 	INIT_LIST_HEAD(&tfile->next);
226054f968d6SJason Wang 
226119a6afb2SJason Wang 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
226219a6afb2SJason Wang 
22631da177e4SLinus Torvalds 	return 0;
22641da177e4SLinus Torvalds }
22651da177e4SLinus Torvalds 
22661da177e4SLinus Torvalds static int tun_chr_close(struct inode *inode, struct file *file)
22671da177e4SLinus Torvalds {
2268631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
22691da177e4SLinus Torvalds 
2270c8d68e6bSJason Wang 	tun_detach(tfile, true);
22711da177e4SLinus Torvalds 
22721da177e4SLinus Torvalds 	return 0;
22731da177e4SLinus Torvalds }
22741da177e4SLinus Torvalds 
227593e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
2276a3816ab0SJoe Perches static void tun_chr_show_fdinfo(struct seq_file *m, struct file *f)
227793e14b6dSMasatake YAMATO {
227893e14b6dSMasatake YAMATO 	struct tun_struct *tun;
227993e14b6dSMasatake YAMATO 	struct ifreq ifr;
228093e14b6dSMasatake YAMATO 
228193e14b6dSMasatake YAMATO 	memset(&ifr, 0, sizeof(ifr));
228293e14b6dSMasatake YAMATO 
228393e14b6dSMasatake YAMATO 	rtnl_lock();
228493e14b6dSMasatake YAMATO 	tun = tun_get(f);
228593e14b6dSMasatake YAMATO 	if (tun)
228693e14b6dSMasatake YAMATO 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
228793e14b6dSMasatake YAMATO 	rtnl_unlock();
228893e14b6dSMasatake YAMATO 
228993e14b6dSMasatake YAMATO 	if (tun)
229093e14b6dSMasatake YAMATO 		tun_put(tun);
229193e14b6dSMasatake YAMATO 
2292a3816ab0SJoe Perches 	seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
229393e14b6dSMasatake YAMATO }
229493e14b6dSMasatake YAMATO #endif
229593e14b6dSMasatake YAMATO 
2296d54b1fdbSArjan van de Ven static const struct file_operations tun_fops = {
22971da177e4SLinus Torvalds 	.owner	= THIS_MODULE,
22981da177e4SLinus Torvalds 	.llseek = no_llseek,
22999b067034SAl Viro 	.read_iter  = tun_chr_read_iter,
2300f5ff53b4SAl Viro 	.write_iter = tun_chr_write_iter,
23011da177e4SLinus Torvalds 	.poll	= tun_chr_poll,
2302876bfd4dSHerbert Xu 	.unlocked_ioctl	= tun_chr_ioctl,
230350857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
230450857e2aSArnd Bergmann 	.compat_ioctl = tun_chr_compat_ioctl,
230550857e2aSArnd Bergmann #endif
23061da177e4SLinus Torvalds 	.open	= tun_chr_open,
23071da177e4SLinus Torvalds 	.release = tun_chr_close,
230893e14b6dSMasatake YAMATO 	.fasync = tun_chr_fasync,
230993e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
231093e14b6dSMasatake YAMATO 	.show_fdinfo = tun_chr_show_fdinfo,
231193e14b6dSMasatake YAMATO #endif
23121da177e4SLinus Torvalds };
23131da177e4SLinus Torvalds 
23141da177e4SLinus Torvalds static struct miscdevice tun_miscdev = {
23151da177e4SLinus Torvalds 	.minor = TUN_MINOR,
23161da177e4SLinus Torvalds 	.name = "tun",
2317e454cea2SKay Sievers 	.nodename = "net/tun",
23181da177e4SLinus Torvalds 	.fops = &tun_fops,
23191da177e4SLinus Torvalds };
23201da177e4SLinus Torvalds 
23211da177e4SLinus Torvalds /* ethtool interface */
23221da177e4SLinus Torvalds 
23231da177e4SLinus Torvalds static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
23241da177e4SLinus Torvalds {
23251da177e4SLinus Torvalds 	cmd->supported		= 0;
23261da177e4SLinus Torvalds 	cmd->advertising	= 0;
232770739497SDavid Decotigny 	ethtool_cmd_speed_set(cmd, SPEED_10);
23281da177e4SLinus Torvalds 	cmd->duplex		= DUPLEX_FULL;
23291da177e4SLinus Torvalds 	cmd->port		= PORT_TP;
23301da177e4SLinus Torvalds 	cmd->phy_address	= 0;
23311da177e4SLinus Torvalds 	cmd->transceiver	= XCVR_INTERNAL;
23321da177e4SLinus Torvalds 	cmd->autoneg		= AUTONEG_DISABLE;
23331da177e4SLinus Torvalds 	cmd->maxtxpkt		= 0;
23341da177e4SLinus Torvalds 	cmd->maxrxpkt		= 0;
23351da177e4SLinus Torvalds 	return 0;
23361da177e4SLinus Torvalds }
23371da177e4SLinus Torvalds 
23381da177e4SLinus Torvalds static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
23391da177e4SLinus Torvalds {
23401da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
23411da177e4SLinus Torvalds 
234233a5ba14SRick Jones 	strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
234333a5ba14SRick Jones 	strlcpy(info->version, DRV_VERSION, sizeof(info->version));
23441da177e4SLinus Torvalds 
23451da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
234640630b82SMichael S. Tsirkin 	case IFF_TUN:
234733a5ba14SRick Jones 		strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
23481da177e4SLinus Torvalds 		break;
234940630b82SMichael S. Tsirkin 	case IFF_TAP:
235033a5ba14SRick Jones 		strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
23511da177e4SLinus Torvalds 		break;
23521da177e4SLinus Torvalds 	}
23531da177e4SLinus Torvalds }
23541da177e4SLinus Torvalds 
23551da177e4SLinus Torvalds static u32 tun_get_msglevel(struct net_device *dev)
23561da177e4SLinus Torvalds {
23571da177e4SLinus Torvalds #ifdef TUN_DEBUG
23581da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
23591da177e4SLinus Torvalds 	return tun->debug;
23601da177e4SLinus Torvalds #else
23611da177e4SLinus Torvalds 	return -EOPNOTSUPP;
23621da177e4SLinus Torvalds #endif
23631da177e4SLinus Torvalds }
23641da177e4SLinus Torvalds 
23651da177e4SLinus Torvalds static void tun_set_msglevel(struct net_device *dev, u32 value)
23661da177e4SLinus Torvalds {
23671da177e4SLinus Torvalds #ifdef TUN_DEBUG
23681da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
23691da177e4SLinus Torvalds 	tun->debug = value;
23701da177e4SLinus Torvalds #endif
23711da177e4SLinus Torvalds }
23721da177e4SLinus Torvalds 
23737282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops = {
23741da177e4SLinus Torvalds 	.get_settings	= tun_get_settings,
23751da177e4SLinus Torvalds 	.get_drvinfo	= tun_get_drvinfo,
23761da177e4SLinus Torvalds 	.get_msglevel	= tun_get_msglevel,
23771da177e4SLinus Torvalds 	.set_msglevel	= tun_set_msglevel,
2378bee31369SNolan Leake 	.get_link	= ethtool_op_get_link,
2379eda29772SRichard Cochran 	.get_ts_info	= ethtool_op_get_ts_info,
23801da177e4SLinus Torvalds };
23811da177e4SLinus Torvalds 
238279d17604SPavel Emelyanov 
23831da177e4SLinus Torvalds static int __init tun_init(void)
23841da177e4SLinus Torvalds {
23851da177e4SLinus Torvalds 	int ret = 0;
23861da177e4SLinus Torvalds 
23876b8a66eeSJoe Perches 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
23886b8a66eeSJoe Perches 	pr_info("%s\n", DRV_COPYRIGHT);
23891da177e4SLinus Torvalds 
2390f019a7a5SEric W. Biederman 	ret = rtnl_link_register(&tun_link_ops);
239179d17604SPavel Emelyanov 	if (ret) {
23926b8a66eeSJoe Perches 		pr_err("Can't register link_ops\n");
2393f019a7a5SEric W. Biederman 		goto err_linkops;
239479d17604SPavel Emelyanov 	}
239579d17604SPavel Emelyanov 
23961da177e4SLinus Torvalds 	ret = misc_register(&tun_miscdev);
239779d17604SPavel Emelyanov 	if (ret) {
23986b8a66eeSJoe Perches 		pr_err("Can't register misc device %d\n", TUN_MINOR);
239979d17604SPavel Emelyanov 		goto err_misc;
240079d17604SPavel Emelyanov 	}
240179d17604SPavel Emelyanov 	return  0;
240279d17604SPavel Emelyanov err_misc:
2403f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
2404f019a7a5SEric W. Biederman err_linkops:
24051da177e4SLinus Torvalds 	return ret;
24061da177e4SLinus Torvalds }
24071da177e4SLinus Torvalds 
24081da177e4SLinus Torvalds static void tun_cleanup(void)
24091da177e4SLinus Torvalds {
24101da177e4SLinus Torvalds 	misc_deregister(&tun_miscdev);
2411f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
24121da177e4SLinus Torvalds }
24131da177e4SLinus Torvalds 
241405c2828cSMichael S. Tsirkin /* Get an underlying socket object from tun file.  Returns error unless file is
241505c2828cSMichael S. Tsirkin  * attached to a device.  The returned object works like a packet socket, it
241605c2828cSMichael S. Tsirkin  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
241705c2828cSMichael S. Tsirkin  * holding a reference to the file for as long as the socket is in use. */
241805c2828cSMichael S. Tsirkin struct socket *tun_get_socket(struct file *file)
241905c2828cSMichael S. Tsirkin {
24206e914fc7SJason Wang 	struct tun_file *tfile;
242105c2828cSMichael S. Tsirkin 	if (file->f_op != &tun_fops)
242205c2828cSMichael S. Tsirkin 		return ERR_PTR(-EINVAL);
24236e914fc7SJason Wang 	tfile = file->private_data;
24246e914fc7SJason Wang 	if (!tfile)
242505c2828cSMichael S. Tsirkin 		return ERR_PTR(-EBADFD);
242654f968d6SJason Wang 	return &tfile->socket;
242705c2828cSMichael S. Tsirkin }
242805c2828cSMichael S. Tsirkin EXPORT_SYMBOL_GPL(tun_get_socket);
242905c2828cSMichael S. Tsirkin 
24301da177e4SLinus Torvalds module_init(tun_init);
24311da177e4SLinus Torvalds module_exit(tun_cleanup);
24321da177e4SLinus Torvalds MODULE_DESCRIPTION(DRV_DESCRIPTION);
24331da177e4SLinus Torvalds MODULE_AUTHOR(DRV_COPYRIGHT);
24341da177e4SLinus Torvalds MODULE_LICENSE("GPL");
24351da177e4SLinus Torvalds MODULE_ALIAS_MISCDEV(TUN_MINOR);
2436578454ffSKay Sievers MODULE_ALIAS("devname:net/tun");
2437