xref: /openbmc/linux/drivers/net/tun.c (revision e0b93eddfe17dcb7d644eb5d6ad02a86fc41a977)
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>
731da177e4SLinus Torvalds 
741da177e4SLinus Torvalds #include <asm/uaccess.h>
751da177e4SLinus Torvalds 
7614daa021SRusty Russell /* Uncomment to enable debugging */
7714daa021SRusty Russell /* #define TUN_DEBUG 1 */
7814daa021SRusty Russell 
791da177e4SLinus Torvalds #ifdef TUN_DEBUG
801da177e4SLinus Torvalds static int debug;
8114daa021SRusty Russell 
826b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
836b8a66eeSJoe Perches do {								\
846b8a66eeSJoe Perches 	if (tun->debug)						\
856b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
866b8a66eeSJoe Perches } while (0)
876b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
886b8a66eeSJoe Perches do {								\
896b8a66eeSJoe Perches 	if (debug == 2)						\
906b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
916b8a66eeSJoe Perches } while (0)
9214daa021SRusty Russell #else
936b8a66eeSJoe Perches #define tun_debug(level, tun, fmt, args...)			\
946b8a66eeSJoe Perches do {								\
956b8a66eeSJoe Perches 	if (0)							\
966b8a66eeSJoe Perches 		netdev_printk(level, tun->dev, fmt, ##args);	\
976b8a66eeSJoe Perches } while (0)
986b8a66eeSJoe Perches #define DBG1(level, fmt, args...)				\
996b8a66eeSJoe Perches do {								\
1006b8a66eeSJoe Perches 	if (0)							\
1016b8a66eeSJoe Perches 		printk(level fmt, ##args);			\
1026b8a66eeSJoe Perches } while (0)
1031da177e4SLinus Torvalds #endif
1041da177e4SLinus Torvalds 
1050690899bSMichael S. Tsirkin #define GOODCOPY_LEN 128
1060690899bSMichael S. Tsirkin 
107f271b2ccSMax Krasnyansky #define FLT_EXACT_COUNT 8
108f271b2ccSMax Krasnyansky struct tap_filter {
109f271b2ccSMax Krasnyansky 	unsigned int    count;    /* Number of addrs. Zero means disabled */
110f271b2ccSMax Krasnyansky 	u32             mask[2];  /* Mask of the hashed addrs */
111f271b2ccSMax Krasnyansky 	unsigned char	addr[FLT_EXACT_COUNT][ETH_ALEN];
112f271b2ccSMax Krasnyansky };
113f271b2ccSMax Krasnyansky 
11492d4ea6eSstephen hemminger /* DEFAULT_MAX_NUM_RSS_QUEUES were chosen to let the rx/tx queues allocated for
115edfb6a14SJason Wang  * the netdevice to be fit in one page. So we can make sure the success of
116edfb6a14SJason Wang  * memory allocation. TODO: increase the limit. */
117edfb6a14SJason Wang #define MAX_TAP_QUEUES DEFAULT_MAX_NUM_RSS_QUEUES
118b8732fb7SJason Wang #define MAX_TAP_FLOWS  4096
119c8d68e6bSJason Wang 
12096442e42SJason Wang #define TUN_FLOW_EXPIRE (3 * HZ)
12196442e42SJason Wang 
12254f968d6SJason Wang /* A tun_file connects an open character device to a tuntap netdevice. It
12392d4ea6eSstephen hemminger  * also contains all socket related structures (except sock_fprog and tap_filter)
12454f968d6SJason Wang  * to serve as one transmit queue for tuntap device. The sock_fprog and
12554f968d6SJason Wang  * tap_filter were kept in tun_struct since they were used for filtering for the
12636fe8c09SRami Rosen  * netdevice not for a specific queue (at least I didn't see the requirement for
12754f968d6SJason Wang  * this).
1286e914fc7SJason Wang  *
1296e914fc7SJason Wang  * RCU usage:
13036fe8c09SRami Rosen  * The tun_file and tun_struct are loosely coupled, the pointer from one to the
1316e914fc7SJason Wang  * other can only be read while rcu_read_lock or rtnl_lock is held.
13254f968d6SJason Wang  */
133631ab46bSEric W. Biederman struct tun_file {
13454f968d6SJason Wang 	struct sock sk;
13554f968d6SJason Wang 	struct socket socket;
13654f968d6SJason Wang 	struct socket_wq wq;
1376e914fc7SJason Wang 	struct tun_struct __rcu *tun;
13836b50babSEric W. Biederman 	struct net *net;
13954f968d6SJason Wang 	struct fasync_struct *fasync;
14054f968d6SJason Wang 	/* only used for fasnyc */
14154f968d6SJason Wang 	unsigned int flags;
142fb7589a1SPavel Emelyanov 	union {
143c8d68e6bSJason Wang 		u16 queue_index;
144fb7589a1SPavel Emelyanov 		unsigned int ifindex;
145fb7589a1SPavel Emelyanov 	};
1464008e97fSJason Wang 	struct list_head next;
1474008e97fSJason Wang 	struct tun_struct *detached;
148631ab46bSEric W. Biederman };
149631ab46bSEric W. Biederman 
15096442e42SJason Wang struct tun_flow_entry {
15196442e42SJason Wang 	struct hlist_node hash_link;
15296442e42SJason Wang 	struct rcu_head rcu;
15396442e42SJason Wang 	struct tun_struct *tun;
15496442e42SJason Wang 
15596442e42SJason Wang 	u32 rxhash;
1569bc88939STom Herbert 	u32 rps_rxhash;
15796442e42SJason Wang 	int queue_index;
15896442e42SJason Wang 	unsigned long updated;
15996442e42SJason Wang };
16096442e42SJason Wang 
16196442e42SJason Wang #define TUN_NUM_FLOW_ENTRIES 1024
16296442e42SJason Wang 
16354f968d6SJason Wang /* Since the socket were moved to tun_file, to preserve the behavior of persist
16436fe8c09SRami Rosen  * device, socket filter, sndbuf and vnet header size were restore when the
16554f968d6SJason Wang  * file were attached to a persist device.
16654f968d6SJason Wang  */
16714daa021SRusty Russell struct tun_struct {
168c8d68e6bSJason Wang 	struct tun_file __rcu	*tfiles[MAX_TAP_QUEUES];
169c8d68e6bSJason Wang 	unsigned int            numqueues;
170f271b2ccSMax Krasnyansky 	unsigned int 		flags;
1710625c883SEric W. Biederman 	kuid_t			owner;
1720625c883SEric W. Biederman 	kgid_t			group;
17314daa021SRusty Russell 
17414daa021SRusty Russell 	struct net_device	*dev;
175c8f44affSMichał Mirosław 	netdev_features_t	set_features;
17688255375SMichał Mirosław #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
17788255375SMichał Mirosław 			  NETIF_F_TSO6|NETIF_F_UFO)
178d9d52b51SMichael S. Tsirkin 
179d9d52b51SMichael S. Tsirkin 	int			vnet_hdr_sz;
18054f968d6SJason Wang 	int			sndbuf;
18154f968d6SJason Wang 	struct tap_filter	txflt;
18254f968d6SJason Wang 	struct sock_fprog	fprog;
18354f968d6SJason Wang 	/* protected by rtnl lock */
18454f968d6SJason Wang 	bool			filter_attached;
18514daa021SRusty Russell #ifdef TUN_DEBUG
18614daa021SRusty Russell 	int debug;
18714daa021SRusty Russell #endif
18896442e42SJason Wang 	spinlock_t lock;
18996442e42SJason Wang 	struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
19096442e42SJason Wang 	struct timer_list flow_gc_timer;
19196442e42SJason Wang 	unsigned long ageing_time;
1924008e97fSJason Wang 	unsigned int numdisabled;
1934008e97fSJason Wang 	struct list_head disabled;
1945dbbaf2dSPaul Moore 	void *security;
195b8732fb7SJason Wang 	u32 flow_count;
19614daa021SRusty Russell };
19714daa021SRusty Russell 
19896442e42SJason Wang static inline u32 tun_hashfn(u32 rxhash)
19996442e42SJason Wang {
20096442e42SJason Wang 	return rxhash & 0x3ff;
20196442e42SJason Wang }
20296442e42SJason Wang 
20396442e42SJason Wang static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
20496442e42SJason Wang {
20596442e42SJason Wang 	struct tun_flow_entry *e;
20696442e42SJason Wang 
207b67bfe0dSSasha Levin 	hlist_for_each_entry_rcu(e, head, hash_link) {
20896442e42SJason Wang 		if (e->rxhash == rxhash)
20996442e42SJason Wang 			return e;
21096442e42SJason Wang 	}
21196442e42SJason Wang 	return NULL;
21296442e42SJason Wang }
21396442e42SJason Wang 
21496442e42SJason Wang static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
21596442e42SJason Wang 					      struct hlist_head *head,
21696442e42SJason Wang 					      u32 rxhash, u16 queue_index)
21796442e42SJason Wang {
2189fdc6befSEric Dumazet 	struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
2199fdc6befSEric Dumazet 
22096442e42SJason Wang 	if (e) {
22196442e42SJason Wang 		tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
22296442e42SJason Wang 			  rxhash, queue_index);
22396442e42SJason Wang 		e->updated = jiffies;
22496442e42SJason Wang 		e->rxhash = rxhash;
2259bc88939STom Herbert 		e->rps_rxhash = 0;
22696442e42SJason Wang 		e->queue_index = queue_index;
22796442e42SJason Wang 		e->tun = tun;
22896442e42SJason Wang 		hlist_add_head_rcu(&e->hash_link, head);
229b8732fb7SJason Wang 		++tun->flow_count;
23096442e42SJason Wang 	}
23196442e42SJason Wang 	return e;
23296442e42SJason Wang }
23396442e42SJason Wang 
23496442e42SJason Wang static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
23596442e42SJason Wang {
23696442e42SJason Wang 	tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
23796442e42SJason Wang 		  e->rxhash, e->queue_index);
2389bc88939STom Herbert 	sock_rps_reset_flow_hash(e->rps_rxhash);
23996442e42SJason Wang 	hlist_del_rcu(&e->hash_link);
2409fdc6befSEric Dumazet 	kfree_rcu(e, rcu);
241b8732fb7SJason Wang 	--tun->flow_count;
24296442e42SJason Wang }
24396442e42SJason Wang 
24496442e42SJason Wang static void tun_flow_flush(struct tun_struct *tun)
24596442e42SJason Wang {
24696442e42SJason Wang 	int i;
24796442e42SJason Wang 
24896442e42SJason Wang 	spin_lock_bh(&tun->lock);
24996442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
25096442e42SJason Wang 		struct tun_flow_entry *e;
251b67bfe0dSSasha Levin 		struct hlist_node *n;
25296442e42SJason Wang 
253b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
25496442e42SJason Wang 			tun_flow_delete(tun, e);
25596442e42SJason Wang 	}
25696442e42SJason Wang 	spin_unlock_bh(&tun->lock);
25796442e42SJason Wang }
25896442e42SJason Wang 
25996442e42SJason Wang static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
26096442e42SJason Wang {
26196442e42SJason Wang 	int i;
26296442e42SJason Wang 
26396442e42SJason Wang 	spin_lock_bh(&tun->lock);
26496442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
26596442e42SJason Wang 		struct tun_flow_entry *e;
266b67bfe0dSSasha Levin 		struct hlist_node *n;
26796442e42SJason Wang 
268b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
26996442e42SJason Wang 			if (e->queue_index == queue_index)
27096442e42SJason Wang 				tun_flow_delete(tun, e);
27196442e42SJason Wang 		}
27296442e42SJason Wang 	}
27396442e42SJason Wang 	spin_unlock_bh(&tun->lock);
27496442e42SJason Wang }
27596442e42SJason Wang 
27696442e42SJason Wang static void tun_flow_cleanup(unsigned long data)
27796442e42SJason Wang {
27896442e42SJason Wang 	struct tun_struct *tun = (struct tun_struct *)data;
27996442e42SJason Wang 	unsigned long delay = tun->ageing_time;
28096442e42SJason Wang 	unsigned long next_timer = jiffies + delay;
28196442e42SJason Wang 	unsigned long count = 0;
28296442e42SJason Wang 	int i;
28396442e42SJason Wang 
28496442e42SJason Wang 	tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
28596442e42SJason Wang 
28696442e42SJason Wang 	spin_lock_bh(&tun->lock);
28796442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
28896442e42SJason Wang 		struct tun_flow_entry *e;
289b67bfe0dSSasha Levin 		struct hlist_node *n;
29096442e42SJason Wang 
291b67bfe0dSSasha Levin 		hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
29296442e42SJason Wang 			unsigned long this_timer;
29396442e42SJason Wang 			count++;
29496442e42SJason Wang 			this_timer = e->updated + delay;
29596442e42SJason Wang 			if (time_before_eq(this_timer, jiffies))
29696442e42SJason Wang 				tun_flow_delete(tun, e);
29796442e42SJason Wang 			else if (time_before(this_timer, next_timer))
29896442e42SJason Wang 				next_timer = this_timer;
29996442e42SJason Wang 		}
30096442e42SJason Wang 	}
30196442e42SJason Wang 
30296442e42SJason Wang 	if (count)
30396442e42SJason Wang 		mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
30496442e42SJason Wang 	spin_unlock_bh(&tun->lock);
30596442e42SJason Wang }
30696442e42SJason Wang 
30749974420SEric Dumazet static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
3089e85722dSJason Wang 			    struct tun_file *tfile)
30996442e42SJason Wang {
31096442e42SJason Wang 	struct hlist_head *head;
31196442e42SJason Wang 	struct tun_flow_entry *e;
31296442e42SJason Wang 	unsigned long delay = tun->ageing_time;
3139e85722dSJason Wang 	u16 queue_index = tfile->queue_index;
31496442e42SJason Wang 
31596442e42SJason Wang 	if (!rxhash)
31696442e42SJason Wang 		return;
31796442e42SJason Wang 	else
31896442e42SJason Wang 		head = &tun->flows[tun_hashfn(rxhash)];
31996442e42SJason Wang 
32096442e42SJason Wang 	rcu_read_lock();
32196442e42SJason Wang 
3229e85722dSJason Wang 	/* We may get a very small possibility of OOO during switching, not
3239e85722dSJason Wang 	 * worth to optimize.*/
3249e85722dSJason Wang 	if (tun->numqueues == 1 || tfile->detached)
32596442e42SJason Wang 		goto unlock;
32696442e42SJason Wang 
32796442e42SJason Wang 	e = tun_flow_find(head, rxhash);
32896442e42SJason Wang 	if (likely(e)) {
32996442e42SJason Wang 		/* TODO: keep queueing to old queue until it's empty? */
33096442e42SJason Wang 		e->queue_index = queue_index;
33196442e42SJason Wang 		e->updated = jiffies;
3329bc88939STom Herbert 		sock_rps_record_flow_hash(e->rps_rxhash);
33396442e42SJason Wang 	} else {
33496442e42SJason Wang 		spin_lock_bh(&tun->lock);
335b8732fb7SJason Wang 		if (!tun_flow_find(head, rxhash) &&
336b8732fb7SJason Wang 		    tun->flow_count < MAX_TAP_FLOWS)
33796442e42SJason Wang 			tun_flow_create(tun, head, rxhash, queue_index);
33896442e42SJason Wang 
33996442e42SJason Wang 		if (!timer_pending(&tun->flow_gc_timer))
34096442e42SJason Wang 			mod_timer(&tun->flow_gc_timer,
34196442e42SJason Wang 				  round_jiffies_up(jiffies + delay));
34296442e42SJason Wang 		spin_unlock_bh(&tun->lock);
34396442e42SJason Wang 	}
34496442e42SJason Wang 
34596442e42SJason Wang unlock:
34696442e42SJason Wang 	rcu_read_unlock();
34796442e42SJason Wang }
34896442e42SJason Wang 
3499bc88939STom Herbert /**
3509bc88939STom Herbert  * Save the hash received in the stack receive path and update the
3519bc88939STom Herbert  * flow_hash table accordingly.
3529bc88939STom Herbert  */
3539bc88939STom Herbert static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
3549bc88939STom Herbert {
3559bc88939STom Herbert 	if (unlikely(e->rps_rxhash != hash)) {
3569bc88939STom Herbert 		sock_rps_reset_flow_hash(e->rps_rxhash);
3579bc88939STom Herbert 		e->rps_rxhash = hash;
3589bc88939STom Herbert 	}
3599bc88939STom Herbert }
3609bc88939STom Herbert 
361c8d68e6bSJason Wang /* We try to identify a flow through its rxhash first. The reason that
36292d4ea6eSstephen hemminger  * we do not check rxq no. is because some cards(e.g 82599), chooses
363c8d68e6bSJason Wang  * the rxq based on the txq where the last packet of the flow comes. As
364c8d68e6bSJason Wang  * the userspace application move between processors, we may get a
365c8d68e6bSJason Wang  * different rxq no. here. If we could not get rxhash, then we would
366c8d68e6bSJason Wang  * hope the rxq no. may help here.
367c8d68e6bSJason Wang  */
368f663dd9aSJason Wang static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
36999932d4fSDaniel Borkmann 			    void *accel_priv, select_queue_fallback_t fallback)
370c8d68e6bSJason Wang {
371c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
37296442e42SJason Wang 	struct tun_flow_entry *e;
373c8d68e6bSJason Wang 	u32 txq = 0;
374c8d68e6bSJason Wang 	u32 numqueues = 0;
375c8d68e6bSJason Wang 
376c8d68e6bSJason Wang 	rcu_read_lock();
37792bb73eaSJason Wang 	numqueues = ACCESS_ONCE(tun->numqueues);
378c8d68e6bSJason Wang 
3793958afa1STom Herbert 	txq = skb_get_hash(skb);
380c8d68e6bSJason Wang 	if (txq) {
38196442e42SJason Wang 		e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
3829bc88939STom Herbert 		if (e) {
3839bc88939STom Herbert 			tun_flow_save_rps_rxhash(e, txq);
384fbe4d456SZhi Yong Wu 			txq = e->queue_index;
3859bc88939STom Herbert 		} else
386c8d68e6bSJason Wang 			/* use multiply and shift instead of expensive divide */
387c8d68e6bSJason Wang 			txq = ((u64)txq * numqueues) >> 32;
388c8d68e6bSJason Wang 	} else if (likely(skb_rx_queue_recorded(skb))) {
389c8d68e6bSJason Wang 		txq = skb_get_rx_queue(skb);
390c8d68e6bSJason Wang 		while (unlikely(txq >= numqueues))
391c8d68e6bSJason Wang 			txq -= numqueues;
392c8d68e6bSJason Wang 	}
393c8d68e6bSJason Wang 
394c8d68e6bSJason Wang 	rcu_read_unlock();
395c8d68e6bSJason Wang 	return txq;
396c8d68e6bSJason Wang }
397c8d68e6bSJason Wang 
398cde8b15fSJason Wang static inline bool tun_not_capable(struct tun_struct *tun)
399cde8b15fSJason Wang {
400cde8b15fSJason Wang 	const struct cred *cred = current_cred();
401c260b772SEric W. Biederman 	struct net *net = dev_net(tun->dev);
402cde8b15fSJason Wang 
403cde8b15fSJason Wang 	return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
404cde8b15fSJason Wang 		  (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
405c260b772SEric W. Biederman 		!ns_capable(net->user_ns, CAP_NET_ADMIN);
406cde8b15fSJason Wang }
407cde8b15fSJason Wang 
408c8d68e6bSJason Wang static void tun_set_real_num_queues(struct tun_struct *tun)
409c8d68e6bSJason Wang {
410c8d68e6bSJason Wang 	netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
411c8d68e6bSJason Wang 	netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
412c8d68e6bSJason Wang }
413c8d68e6bSJason Wang 
4144008e97fSJason Wang static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
4154008e97fSJason Wang {
4164008e97fSJason Wang 	tfile->detached = tun;
4174008e97fSJason Wang 	list_add_tail(&tfile->next, &tun->disabled);
4184008e97fSJason Wang 	++tun->numdisabled;
4194008e97fSJason Wang }
4204008e97fSJason Wang 
421d32649d1SJason Wang static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
4224008e97fSJason Wang {
4234008e97fSJason Wang 	struct tun_struct *tun = tfile->detached;
4244008e97fSJason Wang 
4254008e97fSJason Wang 	tfile->detached = NULL;
4264008e97fSJason Wang 	list_del_init(&tfile->next);
4274008e97fSJason Wang 	--tun->numdisabled;
4284008e97fSJason Wang 	return tun;
4294008e97fSJason Wang }
4304008e97fSJason Wang 
4314bfb0513SJason Wang static void tun_queue_purge(struct tun_file *tfile)
4324bfb0513SJason Wang {
4334bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_receive_queue);
4344bfb0513SJason Wang 	skb_queue_purge(&tfile->sk.sk_error_queue);
4354bfb0513SJason Wang }
4364bfb0513SJason Wang 
437c8d68e6bSJason Wang static void __tun_detach(struct tun_file *tfile, bool clean)
438c8d68e6bSJason Wang {
439c8d68e6bSJason Wang 	struct tun_file *ntfile;
440c8d68e6bSJason Wang 	struct tun_struct *tun;
441c8d68e6bSJason Wang 
442b8deabd3SJason Wang 	tun = rtnl_dereference(tfile->tun);
443b8deabd3SJason Wang 
4449e85722dSJason Wang 	if (tun && !tfile->detached) {
445c8d68e6bSJason Wang 		u16 index = tfile->queue_index;
446c8d68e6bSJason Wang 		BUG_ON(index >= tun->numqueues);
447c8d68e6bSJason Wang 
448c8d68e6bSJason Wang 		rcu_assign_pointer(tun->tfiles[index],
449c8d68e6bSJason Wang 				   tun->tfiles[tun->numqueues - 1]);
450b8deabd3SJason Wang 		ntfile = rtnl_dereference(tun->tfiles[index]);
451c8d68e6bSJason Wang 		ntfile->queue_index = index;
452c8d68e6bSJason Wang 
453c8d68e6bSJason Wang 		--tun->numqueues;
4549e85722dSJason Wang 		if (clean) {
455c956674bSMonam Agarwal 			RCU_INIT_POINTER(tfile->tun, NULL);
456c8d68e6bSJason Wang 			sock_put(&tfile->sk);
4579e85722dSJason Wang 		} else
4584008e97fSJason Wang 			tun_disable_queue(tun, tfile);
459c8d68e6bSJason Wang 
460c8d68e6bSJason Wang 		synchronize_net();
46196442e42SJason Wang 		tun_flow_delete_by_queue(tun, tun->numqueues + 1);
462c8d68e6bSJason Wang 		/* Drop read queue */
4634bfb0513SJason Wang 		tun_queue_purge(tfile);
464c8d68e6bSJason Wang 		tun_set_real_num_queues(tun);
465dd38bd85SJason Wang 	} else if (tfile->detached && clean) {
4664008e97fSJason Wang 		tun = tun_enable_queue(tfile);
467dd38bd85SJason Wang 		sock_put(&tfile->sk);
468dd38bd85SJason Wang 	}
469c8d68e6bSJason Wang 
470c8d68e6bSJason Wang 	if (clean) {
471af668b3cSMichael S. Tsirkin 		if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
472af668b3cSMichael S. Tsirkin 			netif_carrier_off(tun->dev);
473af668b3cSMichael S. Tsirkin 
474af668b3cSMichael S. Tsirkin 			if (!(tun->flags & TUN_PERSIST) &&
475af668b3cSMichael S. Tsirkin 			    tun->dev->reg_state == NETREG_REGISTERED)
4764008e97fSJason Wang 				unregister_netdevice(tun->dev);
477af668b3cSMichael S. Tsirkin 		}
4784008e97fSJason Wang 
479c8d68e6bSJason Wang 		BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
480c8d68e6bSJason Wang 				 &tfile->socket.flags));
481c8d68e6bSJason Wang 		sk_release_kernel(&tfile->sk);
482c8d68e6bSJason Wang 	}
483c8d68e6bSJason Wang }
484c8d68e6bSJason Wang 
485c8d68e6bSJason Wang static void tun_detach(struct tun_file *tfile, bool clean)
486c8d68e6bSJason Wang {
487c8d68e6bSJason Wang 	rtnl_lock();
488c8d68e6bSJason Wang 	__tun_detach(tfile, clean);
489c8d68e6bSJason Wang 	rtnl_unlock();
490c8d68e6bSJason Wang }
491c8d68e6bSJason Wang 
492c8d68e6bSJason Wang static void tun_detach_all(struct net_device *dev)
493c8d68e6bSJason Wang {
494c8d68e6bSJason Wang 	struct tun_struct *tun = netdev_priv(dev);
4954008e97fSJason Wang 	struct tun_file *tfile, *tmp;
496c8d68e6bSJason Wang 	int i, n = tun->numqueues;
497c8d68e6bSJason Wang 
498c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
499b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
500c8d68e6bSJason Wang 		BUG_ON(!tfile);
5019e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
502c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
503c8d68e6bSJason Wang 		--tun->numqueues;
504c8d68e6bSJason Wang 	}
5059e85722dSJason Wang 	list_for_each_entry(tfile, &tun->disabled, next) {
5069e641bdcSXi Wang 		tfile->socket.sk->sk_data_ready(tfile->socket.sk);
507c956674bSMonam Agarwal 		RCU_INIT_POINTER(tfile->tun, NULL);
5089e85722dSJason Wang 	}
509c8d68e6bSJason Wang 	BUG_ON(tun->numqueues != 0);
510c8d68e6bSJason Wang 
511c8d68e6bSJason Wang 	synchronize_net();
512c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
513b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
514c8d68e6bSJason Wang 		/* Drop read queue */
5154bfb0513SJason Wang 		tun_queue_purge(tfile);
516c8d68e6bSJason Wang 		sock_put(&tfile->sk);
517c8d68e6bSJason Wang 	}
5184008e97fSJason Wang 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
5194008e97fSJason Wang 		tun_enable_queue(tfile);
5204bfb0513SJason Wang 		tun_queue_purge(tfile);
5214008e97fSJason Wang 		sock_put(&tfile->sk);
5224008e97fSJason Wang 	}
5234008e97fSJason Wang 	BUG_ON(tun->numdisabled != 0);
524dd38bd85SJason Wang 
525dd38bd85SJason Wang 	if (tun->flags & TUN_PERSIST)
526dd38bd85SJason Wang 		module_put(THIS_MODULE);
527c8d68e6bSJason Wang }
528c8d68e6bSJason Wang 
529849c9b6fSPavel Emelyanov static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter)
530a7385ba2SEric W. Biederman {
531631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
53238231b7aSEric W. Biederman 	int err;
533a7385ba2SEric W. Biederman 
5345dbbaf2dSPaul Moore 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
5355dbbaf2dSPaul Moore 	if (err < 0)
5365dbbaf2dSPaul Moore 		goto out;
5375dbbaf2dSPaul Moore 
53838231b7aSEric W. Biederman 	err = -EINVAL;
5399e85722dSJason Wang 	if (rtnl_dereference(tfile->tun) && !tfile->detached)
54038231b7aSEric W. Biederman 		goto out;
54138231b7aSEric W. Biederman 
54238231b7aSEric W. Biederman 	err = -EBUSY;
543c8d68e6bSJason Wang 	if (!(tun->flags & TUN_TAP_MQ) && tun->numqueues == 1)
544c8d68e6bSJason Wang 		goto out;
545c8d68e6bSJason Wang 
546c8d68e6bSJason Wang 	err = -E2BIG;
5474008e97fSJason Wang 	if (!tfile->detached &&
5484008e97fSJason Wang 	    tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
54938231b7aSEric W. Biederman 		goto out;
55038231b7aSEric W. Biederman 
55138231b7aSEric W. Biederman 	err = 0;
55254f968d6SJason Wang 
55392d4ea6eSstephen hemminger 	/* Re-attach the filter to persist device */
554849c9b6fSPavel Emelyanov 	if (!skip_filter && (tun->filter_attached == true)) {
55554f968d6SJason Wang 		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
55654f968d6SJason Wang 		if (!err)
55754f968d6SJason Wang 			goto out;
55854f968d6SJason Wang 	}
559c8d68e6bSJason Wang 	tfile->queue_index = tun->numqueues;
5606e914fc7SJason Wang 	rcu_assign_pointer(tfile->tun, tun);
561c8d68e6bSJason Wang 	rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
562c8d68e6bSJason Wang 	tun->numqueues++;
563c8d68e6bSJason Wang 
5644008e97fSJason Wang 	if (tfile->detached)
5654008e97fSJason Wang 		tun_enable_queue(tfile);
5664008e97fSJason Wang 	else
5674008e97fSJason Wang 		sock_hold(&tfile->sk);
5684008e97fSJason Wang 
569c8d68e6bSJason Wang 	tun_set_real_num_queues(tun);
570c8d68e6bSJason Wang 
571c8d68e6bSJason Wang 	/* device is allowed to go away first, so no need to hold extra
572c8d68e6bSJason Wang 	 * refcnt.
573c8d68e6bSJason Wang 	 */
574a7385ba2SEric W. Biederman 
57538231b7aSEric W. Biederman out:
57638231b7aSEric W. Biederman 	return err;
577a7385ba2SEric W. Biederman }
578a7385ba2SEric W. Biederman 
579631ab46bSEric W. Biederman static struct tun_struct *__tun_get(struct tun_file *tfile)
580631ab46bSEric W. Biederman {
5816e914fc7SJason Wang 	struct tun_struct *tun;
582c70f1829SEric W. Biederman 
5836e914fc7SJason Wang 	rcu_read_lock();
5846e914fc7SJason Wang 	tun = rcu_dereference(tfile->tun);
5856e914fc7SJason Wang 	if (tun)
5866e914fc7SJason Wang 		dev_hold(tun->dev);
5876e914fc7SJason Wang 	rcu_read_unlock();
588c70f1829SEric W. Biederman 
589c70f1829SEric W. Biederman 	return tun;
590631ab46bSEric W. Biederman }
591631ab46bSEric W. Biederman 
592631ab46bSEric W. Biederman static struct tun_struct *tun_get(struct file *file)
593631ab46bSEric W. Biederman {
594631ab46bSEric W. Biederman 	return __tun_get(file->private_data);
595631ab46bSEric W. Biederman }
596631ab46bSEric W. Biederman 
597631ab46bSEric W. Biederman static void tun_put(struct tun_struct *tun)
598631ab46bSEric W. Biederman {
5996e914fc7SJason Wang 	dev_put(tun->dev);
600631ab46bSEric W. Biederman }
601631ab46bSEric W. Biederman 
6026b8a66eeSJoe Perches /* TAP filtering */
603f271b2ccSMax Krasnyansky static void addr_hash_set(u32 *mask, const u8 *addr)
604f271b2ccSMax Krasnyansky {
605f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
606f271b2ccSMax Krasnyansky 	mask[n >> 5] |= (1 << (n & 31));
607f271b2ccSMax Krasnyansky }
608f271b2ccSMax Krasnyansky 
609f271b2ccSMax Krasnyansky static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
610f271b2ccSMax Krasnyansky {
611f271b2ccSMax Krasnyansky 	int n = ether_crc(ETH_ALEN, addr) >> 26;
612f271b2ccSMax Krasnyansky 	return mask[n >> 5] & (1 << (n & 31));
613f271b2ccSMax Krasnyansky }
614f271b2ccSMax Krasnyansky 
615f271b2ccSMax Krasnyansky static int update_filter(struct tap_filter *filter, void __user *arg)
616f271b2ccSMax Krasnyansky {
617f271b2ccSMax Krasnyansky 	struct { u8 u[ETH_ALEN]; } *addr;
618f271b2ccSMax Krasnyansky 	struct tun_filter uf;
619f271b2ccSMax Krasnyansky 	int err, alen, n, nexact;
620f271b2ccSMax Krasnyansky 
621f271b2ccSMax Krasnyansky 	if (copy_from_user(&uf, arg, sizeof(uf)))
622f271b2ccSMax Krasnyansky 		return -EFAULT;
623f271b2ccSMax Krasnyansky 
624f271b2ccSMax Krasnyansky 	if (!uf.count) {
625f271b2ccSMax Krasnyansky 		/* Disabled */
626f271b2ccSMax Krasnyansky 		filter->count = 0;
627f271b2ccSMax Krasnyansky 		return 0;
628f271b2ccSMax Krasnyansky 	}
629f271b2ccSMax Krasnyansky 
630f271b2ccSMax Krasnyansky 	alen = ETH_ALEN * uf.count;
631f271b2ccSMax Krasnyansky 	addr = kmalloc(alen, GFP_KERNEL);
632f271b2ccSMax Krasnyansky 	if (!addr)
633f271b2ccSMax Krasnyansky 		return -ENOMEM;
634f271b2ccSMax Krasnyansky 
635f271b2ccSMax Krasnyansky 	if (copy_from_user(addr, arg + sizeof(uf), alen)) {
636f271b2ccSMax Krasnyansky 		err = -EFAULT;
637f271b2ccSMax Krasnyansky 		goto done;
638f271b2ccSMax Krasnyansky 	}
639f271b2ccSMax Krasnyansky 
640f271b2ccSMax Krasnyansky 	/* The filter is updated without holding any locks. Which is
641f271b2ccSMax Krasnyansky 	 * perfectly safe. We disable it first and in the worst
642f271b2ccSMax Krasnyansky 	 * case we'll accept a few undesired packets. */
643f271b2ccSMax Krasnyansky 	filter->count = 0;
644f271b2ccSMax Krasnyansky 	wmb();
645f271b2ccSMax Krasnyansky 
646f271b2ccSMax Krasnyansky 	/* Use first set of addresses as an exact filter */
647f271b2ccSMax Krasnyansky 	for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
648f271b2ccSMax Krasnyansky 		memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
649f271b2ccSMax Krasnyansky 
650f271b2ccSMax Krasnyansky 	nexact = n;
651f271b2ccSMax Krasnyansky 
652cfbf84fcSAlex Williamson 	/* Remaining multicast addresses are hashed,
653cfbf84fcSAlex Williamson 	 * unicast will leave the filter disabled. */
654f271b2ccSMax Krasnyansky 	memset(filter->mask, 0, sizeof(filter->mask));
655cfbf84fcSAlex Williamson 	for (; n < uf.count; n++) {
656cfbf84fcSAlex Williamson 		if (!is_multicast_ether_addr(addr[n].u)) {
657cfbf84fcSAlex Williamson 			err = 0; /* no filter */
658cfbf84fcSAlex Williamson 			goto done;
659cfbf84fcSAlex Williamson 		}
660f271b2ccSMax Krasnyansky 		addr_hash_set(filter->mask, addr[n].u);
661cfbf84fcSAlex Williamson 	}
662f271b2ccSMax Krasnyansky 
663f271b2ccSMax Krasnyansky 	/* For ALLMULTI just set the mask to all ones.
664f271b2ccSMax Krasnyansky 	 * This overrides the mask populated above. */
665f271b2ccSMax Krasnyansky 	if ((uf.flags & TUN_FLT_ALLMULTI))
666f271b2ccSMax Krasnyansky 		memset(filter->mask, ~0, sizeof(filter->mask));
667f271b2ccSMax Krasnyansky 
668f271b2ccSMax Krasnyansky 	/* Now enable the filter */
669f271b2ccSMax Krasnyansky 	wmb();
670f271b2ccSMax Krasnyansky 	filter->count = nexact;
671f271b2ccSMax Krasnyansky 
672f271b2ccSMax Krasnyansky 	/* Return the number of exact filters */
673f271b2ccSMax Krasnyansky 	err = nexact;
674f271b2ccSMax Krasnyansky 
675f271b2ccSMax Krasnyansky done:
676f271b2ccSMax Krasnyansky 	kfree(addr);
677f271b2ccSMax Krasnyansky 	return err;
678f271b2ccSMax Krasnyansky }
679f271b2ccSMax Krasnyansky 
680f271b2ccSMax Krasnyansky /* Returns: 0 - drop, !=0 - accept */
681f271b2ccSMax Krasnyansky static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
682f271b2ccSMax Krasnyansky {
683f271b2ccSMax Krasnyansky 	/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
684f271b2ccSMax Krasnyansky 	 * at this point. */
685f271b2ccSMax Krasnyansky 	struct ethhdr *eh = (struct ethhdr *) skb->data;
686f271b2ccSMax Krasnyansky 	int i;
687f271b2ccSMax Krasnyansky 
688f271b2ccSMax Krasnyansky 	/* Exact match */
689f271b2ccSMax Krasnyansky 	for (i = 0; i < filter->count; i++)
6902e42e474SJoe Perches 		if (ether_addr_equal(eh->h_dest, filter->addr[i]))
691f271b2ccSMax Krasnyansky 			return 1;
692f271b2ccSMax Krasnyansky 
693f271b2ccSMax Krasnyansky 	/* Inexact match (multicast only) */
694f271b2ccSMax Krasnyansky 	if (is_multicast_ether_addr(eh->h_dest))
695f271b2ccSMax Krasnyansky 		return addr_hash_test(filter->mask, eh->h_dest);
696f271b2ccSMax Krasnyansky 
697f271b2ccSMax Krasnyansky 	return 0;
698f271b2ccSMax Krasnyansky }
699f271b2ccSMax Krasnyansky 
700f271b2ccSMax Krasnyansky /*
701f271b2ccSMax Krasnyansky  * Checks whether the packet is accepted or not.
702f271b2ccSMax Krasnyansky  * Returns: 0 - drop, !=0 - accept
703f271b2ccSMax Krasnyansky  */
704f271b2ccSMax Krasnyansky static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
705f271b2ccSMax Krasnyansky {
706f271b2ccSMax Krasnyansky 	if (!filter->count)
707f271b2ccSMax Krasnyansky 		return 1;
708f271b2ccSMax Krasnyansky 
709f271b2ccSMax Krasnyansky 	return run_filter(filter, skb);
710f271b2ccSMax Krasnyansky }
711f271b2ccSMax Krasnyansky 
7121da177e4SLinus Torvalds /* Network device part of the driver */
7131da177e4SLinus Torvalds 
7147282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops;
7151da177e4SLinus Torvalds 
716c70f1829SEric W. Biederman /* Net device detach from fd. */
717c70f1829SEric W. Biederman static void tun_net_uninit(struct net_device *dev)
718c70f1829SEric W. Biederman {
719c8d68e6bSJason Wang 	tun_detach_all(dev);
720c70f1829SEric W. Biederman }
721c70f1829SEric W. Biederman 
7221da177e4SLinus Torvalds /* Net device open. */
7231da177e4SLinus Torvalds static int tun_net_open(struct net_device *dev)
7241da177e4SLinus Torvalds {
725c8d68e6bSJason Wang 	netif_tx_start_all_queues(dev);
7261da177e4SLinus Torvalds 	return 0;
7271da177e4SLinus Torvalds }
7281da177e4SLinus Torvalds 
7291da177e4SLinus Torvalds /* Net device close. */
7301da177e4SLinus Torvalds static int tun_net_close(struct net_device *dev)
7311da177e4SLinus Torvalds {
732c8d68e6bSJason Wang 	netif_tx_stop_all_queues(dev);
7331da177e4SLinus Torvalds 	return 0;
7341da177e4SLinus Torvalds }
7351da177e4SLinus Torvalds 
7361da177e4SLinus Torvalds /* Net device start xmit */
737424efe9cSStephen Hemminger static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
7381da177e4SLinus Torvalds {
7391da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
740c8d68e6bSJason Wang 	int txq = skb->queue_mapping;
7416e914fc7SJason Wang 	struct tun_file *tfile;
742fa35864eSDominic Curran 	u32 numqueues = 0;
7431da177e4SLinus Torvalds 
7446e914fc7SJason Wang 	rcu_read_lock();
745c8d68e6bSJason Wang 	tfile = rcu_dereference(tun->tfiles[txq]);
746fa35864eSDominic Curran 	numqueues = ACCESS_ONCE(tun->numqueues);
747c8d68e6bSJason Wang 
7481da177e4SLinus Torvalds 	/* Drop packet if interface is not attached */
749fa35864eSDominic Curran 	if (txq >= numqueues)
7501da177e4SLinus Torvalds 		goto drop;
7511da177e4SLinus Torvalds 
752fa35864eSDominic Curran 	if (numqueues == 1) {
7539bc88939STom Herbert 		/* Select queue was not called for the skbuff, so we extract the
7549bc88939STom Herbert 		 * RPS hash and save it into the flow_table here.
7559bc88939STom Herbert 		 */
7569bc88939STom Herbert 		__u32 rxhash;
7579bc88939STom Herbert 
7589bc88939STom Herbert 		rxhash = skb_get_hash(skb);
7599bc88939STom Herbert 		if (rxhash) {
7609bc88939STom Herbert 			struct tun_flow_entry *e;
7619bc88939STom Herbert 			e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
7629bc88939STom Herbert 					rxhash);
7639bc88939STom Herbert 			if (e)
7649bc88939STom Herbert 				tun_flow_save_rps_rxhash(e, rxhash);
7659bc88939STom Herbert 		}
7669bc88939STom Herbert 	}
7679bc88939STom Herbert 
7686e914fc7SJason Wang 	tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
7696e914fc7SJason Wang 
770c8d68e6bSJason Wang 	BUG_ON(!tfile);
771c8d68e6bSJason Wang 
772f271b2ccSMax Krasnyansky 	/* Drop if the filter does not like it.
773f271b2ccSMax Krasnyansky 	 * This is a noop if the filter is disabled.
774f271b2ccSMax Krasnyansky 	 * Filter can be enabled only for the TAP devices. */
775f271b2ccSMax Krasnyansky 	if (!check_filter(&tun->txflt, skb))
776f271b2ccSMax Krasnyansky 		goto drop;
777f271b2ccSMax Krasnyansky 
77854f968d6SJason Wang 	if (tfile->socket.sk->sk_filter &&
77954f968d6SJason Wang 	    sk_filter(tfile->socket.sk, skb))
78099405162SMichael S. Tsirkin 		goto drop;
78199405162SMichael S. Tsirkin 
78236fe8c09SRami Rosen 	/* Limit the number of packets queued by dividing txq length with the
783c8d68e6bSJason Wang 	 * number of queues.
784c8d68e6bSJason Wang 	 */
785fa35864eSDominic Curran 	if (skb_queue_len(&tfile->socket.sk->sk_receive_queue) * numqueues
786fa35864eSDominic Curran 			  >= dev->tx_queue_len)
7871da177e4SLinus Torvalds 		goto drop;
7881da177e4SLinus Torvalds 
7897bf66305SJason Wang 	if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
7907bf66305SJason Wang 		goto drop;
7917bf66305SJason Wang 
792eda29772SRichard Cochran 	if (skb->sk) {
793eda29772SRichard Cochran 		sock_tx_timestamp(skb->sk, &skb_shinfo(skb)->tx_flags);
794eda29772SRichard Cochran 		sw_tx_timestamp(skb);
795eda29772SRichard Cochran 	}
796eda29772SRichard Cochran 
7970110d6f2SMichael S. Tsirkin 	/* Orphan the skb - required as we might hang on to it
7987bf66305SJason Wang 	 * for indefinite time.
7997bf66305SJason Wang 	 */
8000110d6f2SMichael S. Tsirkin 	skb_orphan(skb);
8010110d6f2SMichael S. Tsirkin 
802f8af75f3SEric Dumazet 	nf_reset(skb);
803f8af75f3SEric Dumazet 
804f271b2ccSMax Krasnyansky 	/* Enqueue packet */
80554f968d6SJason Wang 	skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
8061da177e4SLinus Torvalds 
8071da177e4SLinus Torvalds 	/* Notify and wake up reader process */
80854f968d6SJason Wang 	if (tfile->flags & TUN_FASYNC)
80954f968d6SJason Wang 		kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
8109e641bdcSXi Wang 	tfile->socket.sk->sk_data_ready(tfile->socket.sk);
8116e914fc7SJason Wang 
8126e914fc7SJason Wang 	rcu_read_unlock();
8136ed10654SPatrick McHardy 	return NETDEV_TX_OK;
8141da177e4SLinus Torvalds 
8151da177e4SLinus Torvalds drop:
81609f75cd7SJeff Garzik 	dev->stats.tx_dropped++;
817149d36f7SMichael S. Tsirkin 	skb_tx_error(skb);
8181da177e4SLinus Torvalds 	kfree_skb(skb);
8196e914fc7SJason Wang 	rcu_read_unlock();
8206ed10654SPatrick McHardy 	return NETDEV_TX_OK;
8211da177e4SLinus Torvalds }
8221da177e4SLinus Torvalds 
823f271b2ccSMax Krasnyansky static void tun_net_mclist(struct net_device *dev)
8241da177e4SLinus Torvalds {
825f271b2ccSMax Krasnyansky 	/*
826f271b2ccSMax Krasnyansky 	 * This callback is supposed to deal with mc filter in
827f271b2ccSMax Krasnyansky 	 * _rx_ path and has nothing to do with the _tx_ path.
828f271b2ccSMax Krasnyansky 	 * In rx path we always accept everything userspace gives us.
829f271b2ccSMax Krasnyansky 	 */
8301da177e4SLinus Torvalds }
8311da177e4SLinus Torvalds 
8324885a504SEd Swierk #define MIN_MTU 68
8334885a504SEd Swierk #define MAX_MTU 65535
8344885a504SEd Swierk 
8354885a504SEd Swierk static int
8364885a504SEd Swierk tun_net_change_mtu(struct net_device *dev, int new_mtu)
8374885a504SEd Swierk {
8384885a504SEd Swierk 	if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
8394885a504SEd Swierk 		return -EINVAL;
8404885a504SEd Swierk 	dev->mtu = new_mtu;
8414885a504SEd Swierk 	return 0;
8424885a504SEd Swierk }
8434885a504SEd Swierk 
844c8f44affSMichał Mirosław static netdev_features_t tun_net_fix_features(struct net_device *dev,
845c8f44affSMichał Mirosław 	netdev_features_t features)
84688255375SMichał Mirosław {
84788255375SMichał Mirosław 	struct tun_struct *tun = netdev_priv(dev);
84888255375SMichał Mirosław 
84988255375SMichał Mirosław 	return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
85088255375SMichał Mirosław }
851bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
852bebd097aSNeil Horman static void tun_poll_controller(struct net_device *dev)
853bebd097aSNeil Horman {
854bebd097aSNeil Horman 	/*
855bebd097aSNeil Horman 	 * Tun only receives frames when:
856bebd097aSNeil Horman 	 * 1) the char device endpoint gets data from user space
857bebd097aSNeil Horman 	 * 2) the tun socket gets a sendmsg call from user space
85892d4ea6eSstephen hemminger 	 * Since both of those are synchronous operations, we are guaranteed
859bebd097aSNeil Horman 	 * never to have pending data when we poll for it
86092d4ea6eSstephen hemminger 	 * so there is nothing to do here but return.
861bebd097aSNeil Horman 	 * We need this though so netpoll recognizes us as an interface that
862bebd097aSNeil Horman 	 * supports polling, which enables bridge devices in virt setups to
863bebd097aSNeil Horman 	 * still use netconsole
864bebd097aSNeil Horman 	 */
865bebd097aSNeil Horman 	return;
866bebd097aSNeil Horman }
867bebd097aSNeil Horman #endif
868758e43b7SStephen Hemminger static const struct net_device_ops tun_netdev_ops = {
869c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
870758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
871758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
87200829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
873758e43b7SStephen Hemminger 	.ndo_change_mtu		= tun_net_change_mtu,
87488255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
875c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
876bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
877bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
878bebd097aSNeil Horman #endif
879758e43b7SStephen Hemminger };
880758e43b7SStephen Hemminger 
881758e43b7SStephen Hemminger static const struct net_device_ops tap_netdev_ops = {
882c70f1829SEric W. Biederman 	.ndo_uninit		= tun_net_uninit,
883758e43b7SStephen Hemminger 	.ndo_open		= tun_net_open,
884758e43b7SStephen Hemminger 	.ndo_stop		= tun_net_close,
88500829823SStephen Hemminger 	.ndo_start_xmit		= tun_net_xmit,
886758e43b7SStephen Hemminger 	.ndo_change_mtu		= tun_net_change_mtu,
88788255375SMichał Mirosław 	.ndo_fix_features	= tun_net_fix_features,
888afc4b13dSJiri Pirko 	.ndo_set_rx_mode	= tun_net_mclist,
889758e43b7SStephen Hemminger 	.ndo_set_mac_address	= eth_mac_addr,
890758e43b7SStephen Hemminger 	.ndo_validate_addr	= eth_validate_addr,
891c8d68e6bSJason Wang 	.ndo_select_queue	= tun_select_queue,
892bebd097aSNeil Horman #ifdef CONFIG_NET_POLL_CONTROLLER
893bebd097aSNeil Horman 	.ndo_poll_controller	= tun_poll_controller,
894bebd097aSNeil Horman #endif
895758e43b7SStephen Hemminger };
896758e43b7SStephen Hemminger 
897944a1376SPavel Emelyanov static void tun_flow_init(struct tun_struct *tun)
89896442e42SJason Wang {
89996442e42SJason Wang 	int i;
90096442e42SJason Wang 
90196442e42SJason Wang 	for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
90296442e42SJason Wang 		INIT_HLIST_HEAD(&tun->flows[i]);
90396442e42SJason Wang 
90496442e42SJason Wang 	tun->ageing_time = TUN_FLOW_EXPIRE;
90596442e42SJason Wang 	setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
90696442e42SJason Wang 	mod_timer(&tun->flow_gc_timer,
90796442e42SJason Wang 		  round_jiffies_up(jiffies + tun->ageing_time));
90896442e42SJason Wang }
90996442e42SJason Wang 
91096442e42SJason Wang static void tun_flow_uninit(struct tun_struct *tun)
91196442e42SJason Wang {
91296442e42SJason Wang 	del_timer_sync(&tun->flow_gc_timer);
91396442e42SJason Wang 	tun_flow_flush(tun);
91496442e42SJason Wang }
91596442e42SJason Wang 
9161da177e4SLinus Torvalds /* Initialize net device. */
9171da177e4SLinus Torvalds static void tun_net_init(struct net_device *dev)
9181da177e4SLinus Torvalds {
9191da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
9201da177e4SLinus Torvalds 
9211da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
9221da177e4SLinus Torvalds 	case TUN_TUN_DEV:
923758e43b7SStephen Hemminger 		dev->netdev_ops = &tun_netdev_ops;
924758e43b7SStephen Hemminger 
9251da177e4SLinus Torvalds 		/* Point-to-Point TUN Device */
9261da177e4SLinus Torvalds 		dev->hard_header_len = 0;
9271da177e4SLinus Torvalds 		dev->addr_len = 0;
9281da177e4SLinus Torvalds 		dev->mtu = 1500;
9291da177e4SLinus Torvalds 
9301da177e4SLinus Torvalds 		/* Zero header length */
9311da177e4SLinus Torvalds 		dev->type = ARPHRD_NONE;
9321da177e4SLinus Torvalds 		dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
9331da177e4SLinus Torvalds 		dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
9341da177e4SLinus Torvalds 		break;
9351da177e4SLinus Torvalds 
9361da177e4SLinus Torvalds 	case TUN_TAP_DEV:
9377a0a9608SKusanagi Kouichi 		dev->netdev_ops = &tap_netdev_ops;
9381da177e4SLinus Torvalds 		/* Ethernet TAP Device */
9391da177e4SLinus Torvalds 		ether_setup(dev);
940550fd08cSNeil Horman 		dev->priv_flags &= ~IFF_TX_SKB_SHARING;
941a676847bSstephen hemminger 		dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
94236226a8dSBrian Braunstein 
943f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
94436226a8dSBrian Braunstein 
9451da177e4SLinus Torvalds 		dev->tx_queue_len = TUN_READQ_SIZE;  /* We prefer our own queue length */
9461da177e4SLinus Torvalds 		break;
9471da177e4SLinus Torvalds 	}
9481da177e4SLinus Torvalds }
9491da177e4SLinus Torvalds 
9501da177e4SLinus Torvalds /* Character device part */
9511da177e4SLinus Torvalds 
9521da177e4SLinus Torvalds /* Poll */
9531da177e4SLinus Torvalds static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
9541da177e4SLinus Torvalds {
955b2430de3SEric W. Biederman 	struct tun_file *tfile = file->private_data;
956b2430de3SEric W. Biederman 	struct tun_struct *tun = __tun_get(tfile);
9573c8a9c63SMariusz Kozlowski 	struct sock *sk;
95833dccbb0SHerbert Xu 	unsigned int mask = 0;
9591da177e4SLinus Torvalds 
9601da177e4SLinus Torvalds 	if (!tun)
961eac9e902SEric W. Biederman 		return POLLERR;
9621da177e4SLinus Torvalds 
96354f968d6SJason Wang 	sk = tfile->socket.sk;
9643c8a9c63SMariusz Kozlowski 
9656b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
9661da177e4SLinus Torvalds 
9679e641bdcSXi Wang 	poll_wait(file, sk_sleep(sk), wait);
9681da177e4SLinus Torvalds 
96989f56d1eSMichael S. Tsirkin 	if (!skb_queue_empty(&sk->sk_receive_queue))
9701da177e4SLinus Torvalds 		mask |= POLLIN | POLLRDNORM;
9711da177e4SLinus Torvalds 
97233dccbb0SHerbert Xu 	if (sock_writeable(sk) ||
97333dccbb0SHerbert Xu 	    (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
97433dccbb0SHerbert Xu 	     sock_writeable(sk)))
97533dccbb0SHerbert Xu 		mask |= POLLOUT | POLLWRNORM;
97633dccbb0SHerbert Xu 
977c70f1829SEric W. Biederman 	if (tun->dev->reg_state != NETREG_REGISTERED)
978c70f1829SEric W. Biederman 		mask = POLLERR;
979c70f1829SEric W. Biederman 
980631ab46bSEric W. Biederman 	tun_put(tun);
9811da177e4SLinus Torvalds 	return mask;
9821da177e4SLinus Torvalds }
9831da177e4SLinus Torvalds 
984f42157cbSRusty Russell /* prepad is the amount to reserve at front.  len is length after that.
985f42157cbSRusty Russell  * linear is a hint as to how much to copy (usually headers). */
98654f968d6SJason Wang static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
98733dccbb0SHerbert Xu 				     size_t prepad, size_t len,
98833dccbb0SHerbert Xu 				     size_t linear, int noblock)
989f42157cbSRusty Russell {
99054f968d6SJason Wang 	struct sock *sk = tfile->socket.sk;
991f42157cbSRusty Russell 	struct sk_buff *skb;
99233dccbb0SHerbert Xu 	int err;
993f42157cbSRusty Russell 
994f42157cbSRusty Russell 	/* Under a page?  Don't bother with paged skb. */
9950eca93bcSHerbert Xu 	if (prepad + len < PAGE_SIZE || !linear)
99633dccbb0SHerbert Xu 		linear = len;
997f42157cbSRusty Russell 
99833dccbb0SHerbert Xu 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
99928d64271SEric Dumazet 				   &err, 0);
1000f42157cbSRusty Russell 	if (!skb)
100133dccbb0SHerbert Xu 		return ERR_PTR(err);
1002f42157cbSRusty Russell 
1003f42157cbSRusty Russell 	skb_reserve(skb, prepad);
1004f42157cbSRusty Russell 	skb_put(skb, linear);
100533dccbb0SHerbert Xu 	skb->data_len = len - linear;
100633dccbb0SHerbert Xu 	skb->len += len - linear;
1007f42157cbSRusty Russell 
1008f42157cbSRusty Russell 	return skb;
1009f42157cbSRusty Russell }
1010f42157cbSRusty Russell 
10111da177e4SLinus Torvalds /* Get packet from user space buffer */
101254f968d6SJason Wang static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
101354f968d6SJason Wang 			    void *msg_control, const struct iovec *iv,
101454f968d6SJason Wang 			    size_t total_len, size_t count, int noblock)
10151da177e4SLinus Torvalds {
101609640e63SHarvey Harrison 	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
10171da177e4SLinus Torvalds 	struct sk_buff *skb;
10183dd5c330SJason Wang 	size_t len = total_len, align = NET_SKB_PAD, linear;
1019f43798c2SRusty Russell 	struct virtio_net_hdr gso = { 0 };
102096f8d9ecSJason Wang 	int good_linear;
10216f26c9a7SMichael S. Tsirkin 	int offset = 0;
10220690899bSMichael S. Tsirkin 	int copylen;
10230690899bSMichael S. Tsirkin 	bool zerocopy = false;
10240690899bSMichael S. Tsirkin 	int err;
102549974420SEric Dumazet 	u32 rxhash;
10261da177e4SLinus Torvalds 
10271da177e4SLinus Torvalds 	if (!(tun->flags & TUN_NO_PI)) {
102815718ea0SDan Carpenter 		if (len < sizeof(pi))
10291da177e4SLinus Torvalds 			return -EINVAL;
103015718ea0SDan Carpenter 		len -= sizeof(pi);
10311da177e4SLinus Torvalds 
10326f26c9a7SMichael S. Tsirkin 		if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
10331da177e4SLinus Torvalds 			return -EFAULT;
10346f26c9a7SMichael S. Tsirkin 		offset += sizeof(pi);
10351da177e4SLinus Torvalds 	}
10361da177e4SLinus Torvalds 
1037f43798c2SRusty Russell 	if (tun->flags & TUN_VNET_HDR) {
103815718ea0SDan Carpenter 		if (len < tun->vnet_hdr_sz)
1039f43798c2SRusty Russell 			return -EINVAL;
104015718ea0SDan Carpenter 		len -= tun->vnet_hdr_sz;
1041f43798c2SRusty Russell 
10426f26c9a7SMichael S. Tsirkin 		if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
1043f43798c2SRusty Russell 			return -EFAULT;
1044f43798c2SRusty Russell 
10454909122fSHerbert Xu 		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
10464909122fSHerbert Xu 		    gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
10474909122fSHerbert Xu 			gso.hdr_len = gso.csum_start + gso.csum_offset + 2;
10484909122fSHerbert Xu 
1049f43798c2SRusty Russell 		if (gso.hdr_len > len)
1050f43798c2SRusty Russell 			return -EINVAL;
1051d9d52b51SMichael S. Tsirkin 		offset += tun->vnet_hdr_sz;
1052f43798c2SRusty Russell 	}
1053f43798c2SRusty Russell 
1054e01bf1c8SRusty Russell 	if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
1055a504b86eSstephen hemminger 		align += NET_IP_ALIGN;
10560eca93bcSHerbert Xu 		if (unlikely(len < ETH_HLEN ||
10570eca93bcSHerbert Xu 			     (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
1058e01bf1c8SRusty Russell 			return -EINVAL;
1059e01bf1c8SRusty Russell 	}
10601da177e4SLinus Torvalds 
106196f8d9ecSJason Wang 	good_linear = SKB_MAX_HEAD(align);
106296f8d9ecSJason Wang 
106388529176SJason Wang 	if (msg_control) {
106488529176SJason Wang 		/* There are 256 bytes to be copied in skb, so there is
106588529176SJason Wang 		 * enough room for skb expand head in case it is used.
10660690899bSMichael S. Tsirkin 		 * The rest of the buffer is mapped from userspace.
10670690899bSMichael S. Tsirkin 		 */
106888529176SJason Wang 		copylen = gso.hdr_len ? gso.hdr_len : GOODCOPY_LEN;
106996f8d9ecSJason Wang 		if (copylen > good_linear)
107096f8d9ecSJason Wang 			copylen = good_linear;
10713dd5c330SJason Wang 		linear = copylen;
107288529176SJason Wang 		if (iov_pages(iv, offset + copylen, count) <= MAX_SKB_FRAGS)
107388529176SJason Wang 			zerocopy = true;
107488529176SJason Wang 	}
107588529176SJason Wang 
107688529176SJason Wang 	if (!zerocopy) {
10770690899bSMichael S. Tsirkin 		copylen = len;
107896f8d9ecSJason Wang 		if (gso.hdr_len > good_linear)
107996f8d9ecSJason Wang 			linear = good_linear;
108096f8d9ecSJason Wang 		else
10813dd5c330SJason Wang 			linear = gso.hdr_len;
10823dd5c330SJason Wang 	}
10830690899bSMichael S. Tsirkin 
10843dd5c330SJason Wang 	skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
108533dccbb0SHerbert Xu 	if (IS_ERR(skb)) {
108633dccbb0SHerbert Xu 		if (PTR_ERR(skb) != -EAGAIN)
108709f75cd7SJeff Garzik 			tun->dev->stats.rx_dropped++;
108833dccbb0SHerbert Xu 		return PTR_ERR(skb);
10891da177e4SLinus Torvalds 	}
10901da177e4SLinus Torvalds 
10910690899bSMichael S. Tsirkin 	if (zerocopy)
10920690899bSMichael S. Tsirkin 		err = zerocopy_sg_from_iovec(skb, iv, offset, count);
109388529176SJason Wang 	else {
10940690899bSMichael S. Tsirkin 		err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
109588529176SJason Wang 		if (!err && msg_control) {
109688529176SJason Wang 			struct ubuf_info *uarg = msg_control;
109788529176SJason Wang 			uarg->callback(uarg, false);
109888529176SJason Wang 		}
109988529176SJason Wang 	}
11000690899bSMichael S. Tsirkin 
11010690899bSMichael S. Tsirkin 	if (err) {
110209f75cd7SJeff Garzik 		tun->dev->stats.rx_dropped++;
11038f22757eSDave Jones 		kfree_skb(skb);
11041da177e4SLinus Torvalds 		return -EFAULT;
11058f22757eSDave Jones 	}
11061da177e4SLinus Torvalds 
1107f43798c2SRusty Russell 	if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1108f43798c2SRusty Russell 		if (!skb_partial_csum_set(skb, gso.csum_start,
1109f43798c2SRusty Russell 					  gso.csum_offset)) {
1110f43798c2SRusty Russell 			tun->dev->stats.rx_frame_errors++;
1111f43798c2SRusty Russell 			kfree_skb(skb);
1112f43798c2SRusty Russell 			return -EINVAL;
1113f43798c2SRusty Russell 		}
111488255375SMichał Mirosław 	}
1115f43798c2SRusty Russell 
11161da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
11171da177e4SLinus Torvalds 	case TUN_TUN_DEV:
1118f09f7ee2SAng Way Chuang 		if (tun->flags & TUN_NO_PI) {
1119f09f7ee2SAng Way Chuang 			switch (skb->data[0] & 0xf0) {
1120f09f7ee2SAng Way Chuang 			case 0x40:
1121f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IP);
1122f09f7ee2SAng Way Chuang 				break;
1123f09f7ee2SAng Way Chuang 			case 0x60:
1124f09f7ee2SAng Way Chuang 				pi.proto = htons(ETH_P_IPV6);
1125f09f7ee2SAng Way Chuang 				break;
1126f09f7ee2SAng Way Chuang 			default:
1127f09f7ee2SAng Way Chuang 				tun->dev->stats.rx_dropped++;
1128f09f7ee2SAng Way Chuang 				kfree_skb(skb);
1129f09f7ee2SAng Way Chuang 				return -EINVAL;
1130f09f7ee2SAng Way Chuang 			}
1131f09f7ee2SAng Way Chuang 		}
1132f09f7ee2SAng Way Chuang 
1133459a98edSArnaldo Carvalho de Melo 		skb_reset_mac_header(skb);
11341da177e4SLinus Torvalds 		skb->protocol = pi.proto;
11354c13eb66SArnaldo Carvalho de Melo 		skb->dev = tun->dev;
11361da177e4SLinus Torvalds 		break;
11371da177e4SLinus Torvalds 	case TUN_TAP_DEV:
11381da177e4SLinus Torvalds 		skb->protocol = eth_type_trans(skb, tun->dev);
11391da177e4SLinus Torvalds 		break;
11406403eab1SJoe Perches 	}
11411da177e4SLinus Torvalds 
1142f43798c2SRusty Russell 	if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1143f43798c2SRusty Russell 		pr_debug("GSO!\n");
1144f43798c2SRusty Russell 		switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1145f43798c2SRusty Russell 		case VIRTIO_NET_HDR_GSO_TCPV4:
1146c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1147f43798c2SRusty Russell 			break;
1148f43798c2SRusty Russell 		case VIRTIO_NET_HDR_GSO_TCPV6:
1149c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1150f43798c2SRusty Russell 			break;
1151e36aa25aSSridhar Samudrala 		case VIRTIO_NET_HDR_GSO_UDP:
1152c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
1153e36aa25aSSridhar Samudrala 			break;
1154f43798c2SRusty Russell 		default:
1155f43798c2SRusty Russell 			tun->dev->stats.rx_frame_errors++;
1156f43798c2SRusty Russell 			kfree_skb(skb);
1157f43798c2SRusty Russell 			return -EINVAL;
1158f43798c2SRusty Russell 		}
1159f43798c2SRusty Russell 
1160f43798c2SRusty Russell 		if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1161c9af6db4SPravin B Shelar 			skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
1162f43798c2SRusty Russell 
1163f43798c2SRusty Russell 		skb_shinfo(skb)->gso_size = gso.gso_size;
1164f43798c2SRusty Russell 		if (skb_shinfo(skb)->gso_size == 0) {
1165f43798c2SRusty Russell 			tun->dev->stats.rx_frame_errors++;
1166f43798c2SRusty Russell 			kfree_skb(skb);
1167f43798c2SRusty Russell 			return -EINVAL;
1168f43798c2SRusty Russell 		}
1169f43798c2SRusty Russell 
1170f43798c2SRusty Russell 		/* Header must be checked, and gso_segs computed. */
1171f43798c2SRusty Russell 		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1172f43798c2SRusty Russell 		skb_shinfo(skb)->gso_segs = 0;
1173f43798c2SRusty Russell 	}
11741da177e4SLinus Torvalds 
11750690899bSMichael S. Tsirkin 	/* copy skb_ubuf_info for callback when skb has no error */
11760690899bSMichael S. Tsirkin 	if (zerocopy) {
11770690899bSMichael S. Tsirkin 		skb_shinfo(skb)->destructor_arg = msg_control;
11780690899bSMichael S. Tsirkin 		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1179c9af6db4SPravin B Shelar 		skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
11800690899bSMichael S. Tsirkin 	}
11810690899bSMichael S. Tsirkin 
118276fe4581SEric Dumazet 	skb_reset_network_header(skb);
118340893fd0SJason Wang 	skb_probe_transport_header(skb, 0);
118438502af7SJason Wang 
11853958afa1STom Herbert 	rxhash = skb_get_hash(skb);
11861da177e4SLinus Torvalds 	netif_rx_ni(skb);
11871da177e4SLinus Torvalds 
118809f75cd7SJeff Garzik 	tun->dev->stats.rx_packets++;
118909f75cd7SJeff Garzik 	tun->dev->stats.rx_bytes += len;
11901da177e4SLinus Torvalds 
11919e85722dSJason Wang 	tun_flow_update(tun, rxhash, tfile);
11920690899bSMichael S. Tsirkin 	return total_len;
11931da177e4SLinus Torvalds }
11941da177e4SLinus Torvalds 
1195ee0b3e67SBadari Pulavarty static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
1196ee0b3e67SBadari Pulavarty 			      unsigned long count, loff_t pos)
11971da177e4SLinus Torvalds {
119833dccbb0SHerbert Xu 	struct file *file = iocb->ki_filp;
1199ab46d779SHerbert Xu 	struct tun_struct *tun = tun_get(file);
120054f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
1201631ab46bSEric W. Biederman 	ssize_t result;
12021da177e4SLinus Torvalds 
12031da177e4SLinus Torvalds 	if (!tun)
12041da177e4SLinus Torvalds 		return -EBADFD;
12051da177e4SLinus Torvalds 
12066b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
12071da177e4SLinus Torvalds 
120854f968d6SJason Wang 	result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
120954f968d6SJason Wang 			      count, file->f_flags & O_NONBLOCK);
1210631ab46bSEric W. Biederman 
1211631ab46bSEric W. Biederman 	tun_put(tun);
1212631ab46bSEric W. Biederman 	return result;
12131da177e4SLinus Torvalds }
12141da177e4SLinus Torvalds 
12151da177e4SLinus Torvalds /* Put packet to the user space buffer */
12166f7c156cSstephen hemminger static ssize_t tun_put_user(struct tun_struct *tun,
121754f968d6SJason Wang 			    struct tun_file *tfile,
12181da177e4SLinus Torvalds 			    struct sk_buff *skb,
121943b39dcdSMichael S. Tsirkin 			    const struct iovec *iv, int len)
12201da177e4SLinus Torvalds {
12211da177e4SLinus Torvalds 	struct tun_pi pi = { 0, skb->protocol };
12221da177e4SLinus Torvalds 	ssize_t total = 0;
1223e6fd07c8SJason Wang 	int vlan_offset = 0, copied;
12241da177e4SLinus Torvalds 
12251da177e4SLinus Torvalds 	if (!(tun->flags & TUN_NO_PI)) {
12261da177e4SLinus Torvalds 		if ((len -= sizeof(pi)) < 0)
12271da177e4SLinus Torvalds 			return -EINVAL;
12281da177e4SLinus Torvalds 
12291da177e4SLinus Torvalds 		if (len < skb->len) {
12301da177e4SLinus Torvalds 			/* Packet will be striped */
12311da177e4SLinus Torvalds 			pi.flags |= TUN_PKT_STRIP;
12321da177e4SLinus Torvalds 		}
12331da177e4SLinus Torvalds 
123443b39dcdSMichael S. Tsirkin 		if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
12351da177e4SLinus Torvalds 			return -EFAULT;
12361da177e4SLinus Torvalds 		total += sizeof(pi);
12371da177e4SLinus Torvalds 	}
12381da177e4SLinus Torvalds 
1239f43798c2SRusty Russell 	if (tun->flags & TUN_VNET_HDR) {
1240f43798c2SRusty Russell 		struct virtio_net_hdr gso = { 0 }; /* no info leak */
1241d9d52b51SMichael S. Tsirkin 		if ((len -= tun->vnet_hdr_sz) < 0)
1242f43798c2SRusty Russell 			return -EINVAL;
1243f43798c2SRusty Russell 
1244f43798c2SRusty Russell 		if (skb_is_gso(skb)) {
1245f43798c2SRusty Russell 			struct skb_shared_info *sinfo = skb_shinfo(skb);
1246f43798c2SRusty Russell 
1247f43798c2SRusty Russell 			/* This is a hint as to how much should be linear. */
1248f43798c2SRusty Russell 			gso.hdr_len = skb_headlen(skb);
1249f43798c2SRusty Russell 			gso.gso_size = sinfo->gso_size;
1250f43798c2SRusty Russell 			if (sinfo->gso_type & SKB_GSO_TCPV4)
1251f43798c2SRusty Russell 				gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1252f43798c2SRusty Russell 			else if (sinfo->gso_type & SKB_GSO_TCPV6)
1253f43798c2SRusty Russell 				gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1254e36aa25aSSridhar Samudrala 			else if (sinfo->gso_type & SKB_GSO_UDP)
1255e36aa25aSSridhar Samudrala 				gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1256ef3db4a5SMichael S. Tsirkin 			else {
12576b8a66eeSJoe Perches 				pr_err("unexpected GSO type: "
1258ef3db4a5SMichael S. Tsirkin 				       "0x%x, gso_size %d, hdr_len %d\n",
1259ef3db4a5SMichael S. Tsirkin 				       sinfo->gso_type, gso.gso_size,
1260ef3db4a5SMichael S. Tsirkin 				       gso.hdr_len);
1261ef3db4a5SMichael S. Tsirkin 				print_hex_dump(KERN_ERR, "tun: ",
1262ef3db4a5SMichael S. Tsirkin 					       DUMP_PREFIX_NONE,
1263ef3db4a5SMichael S. Tsirkin 					       16, 1, skb->head,
1264ef3db4a5SMichael S. Tsirkin 					       min((int)gso.hdr_len, 64), true);
1265ef3db4a5SMichael S. Tsirkin 				WARN_ON_ONCE(1);
1266ef3db4a5SMichael S. Tsirkin 				return -EINVAL;
1267ef3db4a5SMichael S. Tsirkin 			}
1268f43798c2SRusty Russell 			if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1269f43798c2SRusty Russell 				gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1270f43798c2SRusty Russell 		} else
1271f43798c2SRusty Russell 			gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1272f43798c2SRusty Russell 
1273f43798c2SRusty Russell 		if (skb->ip_summed == CHECKSUM_PARTIAL) {
1274f43798c2SRusty Russell 			gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
127555508d60SMichał Mirosław 			gso.csum_start = skb_checksum_start_offset(skb);
1276f43798c2SRusty Russell 			gso.csum_offset = skb->csum_offset;
127710a8d94aSJason Wang 		} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
127810a8d94aSJason Wang 			gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1279f43798c2SRusty Russell 		} /* else everything is zero */
1280f43798c2SRusty Russell 
128143b39dcdSMichael S. Tsirkin 		if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
128243b39dcdSMichael S. Tsirkin 					       sizeof(gso))))
1283f43798c2SRusty Russell 			return -EFAULT;
1284d9d52b51SMichael S. Tsirkin 		total += tun->vnet_hdr_sz;
1285f43798c2SRusty Russell 	}
1286f43798c2SRusty Russell 
1287e6fd07c8SJason Wang 	copied = total;
1288e6fd07c8SJason Wang 	total += skb->len;
12896680ec68SJason Wang 	if (!vlan_tx_tag_present(skb)) {
12901da177e4SLinus Torvalds 		len = min_t(int, skb->len, len);
12916680ec68SJason Wang 	} else {
12926680ec68SJason Wang 		int copy, ret;
12936680ec68SJason Wang 		struct {
12946680ec68SJason Wang 			__be16 h_vlan_proto;
12956680ec68SJason Wang 			__be16 h_vlan_TCI;
12966680ec68SJason Wang 		} veth;
12971da177e4SLinus Torvalds 
12986680ec68SJason Wang 		veth.h_vlan_proto = skb->vlan_proto;
12996680ec68SJason Wang 		veth.h_vlan_TCI = htons(vlan_tx_tag_get(skb));
13001da177e4SLinus Torvalds 
13016680ec68SJason Wang 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
13026680ec68SJason Wang 		len = min_t(int, skb->len + VLAN_HLEN, len);
1303e6fd07c8SJason Wang 		total += VLAN_HLEN;
13046680ec68SJason Wang 
13056680ec68SJason Wang 		copy = min_t(int, vlan_offset, len);
1306e6fd07c8SJason Wang 		ret = skb_copy_datagram_const_iovec(skb, 0, iv, copied, copy);
13076680ec68SJason Wang 		len -= copy;
1308e6fd07c8SJason Wang 		copied += copy;
13096680ec68SJason Wang 		if (ret || !len)
13106680ec68SJason Wang 			goto done;
13116680ec68SJason Wang 
13126680ec68SJason Wang 		copy = min_t(int, sizeof(veth), len);
1313e6fd07c8SJason Wang 		ret = memcpy_toiovecend(iv, (void *)&veth, copied, copy);
13146680ec68SJason Wang 		len -= copy;
1315e6fd07c8SJason Wang 		copied += copy;
13166680ec68SJason Wang 		if (ret || !len)
13176680ec68SJason Wang 			goto done;
13186680ec68SJason Wang 	}
13196680ec68SJason Wang 
1320e6fd07c8SJason Wang 	skb_copy_datagram_const_iovec(skb, vlan_offset, iv, copied, len);
13216680ec68SJason Wang 
13226680ec68SJason Wang done:
132309f75cd7SJeff Garzik 	tun->dev->stats.tx_packets++;
132409f75cd7SJeff Garzik 	tun->dev->stats.tx_bytes += len;
13251da177e4SLinus Torvalds 
13261da177e4SLinus Torvalds 	return total;
13271da177e4SLinus Torvalds }
13281da177e4SLinus Torvalds 
132954f968d6SJason Wang static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1330f96eb74cSZhi Yong Wu 			   const struct iovec *iv, ssize_t len, int noblock)
13311da177e4SLinus Torvalds {
13321da177e4SLinus Torvalds 	struct sk_buff *skb;
133305c2828cSMichael S. Tsirkin 	ssize_t ret = 0;
13349e641bdcSXi Wang 	int peeked, err, off = 0;
13351da177e4SLinus Torvalds 
13363872baf6SRami Rosen 	tun_debug(KERN_INFO, tun, "tun_do_read\n");
13371da177e4SLinus Torvalds 
13389e641bdcSXi Wang 	if (!len)
13399e641bdcSXi Wang 		return ret;
13401da177e4SLinus Torvalds 
13419e641bdcSXi Wang 	if (tun->dev->reg_state != NETREG_REGISTERED)
13429e641bdcSXi Wang 		return -EIO;
13431da177e4SLinus Torvalds 
13449e641bdcSXi Wang 	/* Read frames from queue */
13459e641bdcSXi Wang 	skb = __skb_recv_datagram(tfile->socket.sk, noblock ? MSG_DONTWAIT : 0,
13469e641bdcSXi Wang 				  &peeked, &off, &err);
13479e641bdcSXi Wang 	if (skb) {
134854f968d6SJason Wang 		ret = tun_put_user(tun, tfile, skb, iv, len);
13491da177e4SLinus Torvalds 		kfree_skb(skb);
13509e641bdcSXi Wang 	} else
13519e641bdcSXi Wang 		ret = err;
13521da177e4SLinus Torvalds 
135305c2828cSMichael S. Tsirkin 	return ret;
135405c2828cSMichael S. Tsirkin }
135505c2828cSMichael S. Tsirkin 
135605c2828cSMichael S. Tsirkin static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
135705c2828cSMichael S. Tsirkin 			    unsigned long count, loff_t pos)
135805c2828cSMichael S. Tsirkin {
135905c2828cSMichael S. Tsirkin 	struct file *file = iocb->ki_filp;
136005c2828cSMichael S. Tsirkin 	struct tun_file *tfile = file->private_data;
136105c2828cSMichael S. Tsirkin 	struct tun_struct *tun = __tun_get(tfile);
136205c2828cSMichael S. Tsirkin 	ssize_t len, ret;
136305c2828cSMichael S. Tsirkin 
136405c2828cSMichael S. Tsirkin 	if (!tun)
136505c2828cSMichael S. Tsirkin 		return -EBADFD;
136605c2828cSMichael S. Tsirkin 	len = iov_length(iv, count);
136705c2828cSMichael S. Tsirkin 	if (len < 0) {
136805c2828cSMichael S. Tsirkin 		ret = -EINVAL;
136905c2828cSMichael S. Tsirkin 		goto out;
137005c2828cSMichael S. Tsirkin 	}
137105c2828cSMichael S. Tsirkin 
1372f96eb74cSZhi Yong Wu 	ret = tun_do_read(tun, tfile, iv, len,
137354f968d6SJason Wang 			  file->f_flags & O_NONBLOCK);
137442404c09SDavid S. Miller 	ret = min_t(ssize_t, ret, len);
1375d0b7da8aSZhi Yong Wu 	if (ret > 0)
1376d0b7da8aSZhi Yong Wu 		iocb->ki_pos = ret;
1377631ab46bSEric W. Biederman out:
1378631ab46bSEric W. Biederman 	tun_put(tun);
13791da177e4SLinus Torvalds 	return ret;
13801da177e4SLinus Torvalds }
13811da177e4SLinus Torvalds 
138296442e42SJason Wang static void tun_free_netdev(struct net_device *dev)
138396442e42SJason Wang {
138496442e42SJason Wang 	struct tun_struct *tun = netdev_priv(dev);
138596442e42SJason Wang 
13864008e97fSJason Wang 	BUG_ON(!(list_empty(&tun->disabled)));
138796442e42SJason Wang 	tun_flow_uninit(tun);
13885dbbaf2dSPaul Moore 	security_tun_dev_free_security(tun->security);
138996442e42SJason Wang 	free_netdev(dev);
139096442e42SJason Wang }
139196442e42SJason Wang 
13921da177e4SLinus Torvalds static void tun_setup(struct net_device *dev)
13931da177e4SLinus Torvalds {
13941da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
13951da177e4SLinus Torvalds 
13960625c883SEric W. Biederman 	tun->owner = INVALID_UID;
13970625c883SEric W. Biederman 	tun->group = INVALID_GID;
13981da177e4SLinus Torvalds 
13991da177e4SLinus Torvalds 	dev->ethtool_ops = &tun_ethtool_ops;
140096442e42SJason Wang 	dev->destructor = tun_free_netdev;
14011da177e4SLinus Torvalds }
14021da177e4SLinus Torvalds 
1403f019a7a5SEric W. Biederman /* Trivial set of netlink ops to allow deleting tun or tap
1404f019a7a5SEric W. Biederman  * device with netlink.
1405f019a7a5SEric W. Biederman  */
1406f019a7a5SEric W. Biederman static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1407f019a7a5SEric W. Biederman {
1408f019a7a5SEric W. Biederman 	return -EINVAL;
1409f019a7a5SEric W. Biederman }
1410f019a7a5SEric W. Biederman 
1411f019a7a5SEric W. Biederman static struct rtnl_link_ops tun_link_ops __read_mostly = {
1412f019a7a5SEric W. Biederman 	.kind		= DRV_NAME,
1413f019a7a5SEric W. Biederman 	.priv_size	= sizeof(struct tun_struct),
1414f019a7a5SEric W. Biederman 	.setup		= tun_setup,
1415f019a7a5SEric W. Biederman 	.validate	= tun_validate,
1416f019a7a5SEric W. Biederman };
1417f019a7a5SEric W. Biederman 
141833dccbb0SHerbert Xu static void tun_sock_write_space(struct sock *sk)
141933dccbb0SHerbert Xu {
142054f968d6SJason Wang 	struct tun_file *tfile;
142143815482SEric Dumazet 	wait_queue_head_t *wqueue;
142233dccbb0SHerbert Xu 
142333dccbb0SHerbert Xu 	if (!sock_writeable(sk))
142433dccbb0SHerbert Xu 		return;
142533dccbb0SHerbert Xu 
142633dccbb0SHerbert Xu 	if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
142733dccbb0SHerbert Xu 		return;
142833dccbb0SHerbert Xu 
142943815482SEric Dumazet 	wqueue = sk_sleep(sk);
143043815482SEric Dumazet 	if (wqueue && waitqueue_active(wqueue))
143143815482SEric Dumazet 		wake_up_interruptible_sync_poll(wqueue, POLLOUT |
143205c2828cSMichael S. Tsirkin 						POLLWRNORM | POLLWRBAND);
1433c722c625SHerbert Xu 
143454f968d6SJason Wang 	tfile = container_of(sk, struct tun_file, sk);
143554f968d6SJason Wang 	kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
143633dccbb0SHerbert Xu }
143733dccbb0SHerbert Xu 
143805c2828cSMichael S. Tsirkin static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
143905c2828cSMichael S. Tsirkin 		       struct msghdr *m, size_t total_len)
144005c2828cSMichael S. Tsirkin {
144154f968d6SJason Wang 	int ret;
144254f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
144354f968d6SJason Wang 	struct tun_struct *tun = __tun_get(tfile);
144454f968d6SJason Wang 
144554f968d6SJason Wang 	if (!tun)
144654f968d6SJason Wang 		return -EBADFD;
144754f968d6SJason Wang 	ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
14480690899bSMichael S. Tsirkin 			   m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
144954f968d6SJason Wang 	tun_put(tun);
145054f968d6SJason Wang 	return ret;
145105c2828cSMichael S. Tsirkin }
145205c2828cSMichael S. Tsirkin 
145305c2828cSMichael S. Tsirkin static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
145405c2828cSMichael S. Tsirkin 		       struct msghdr *m, size_t total_len,
145505c2828cSMichael S. Tsirkin 		       int flags)
145605c2828cSMichael S. Tsirkin {
145754f968d6SJason Wang 	struct tun_file *tfile = container_of(sock, struct tun_file, socket);
145854f968d6SJason Wang 	struct tun_struct *tun = __tun_get(tfile);
145905c2828cSMichael S. Tsirkin 	int ret;
146054f968d6SJason Wang 
146154f968d6SJason Wang 	if (!tun)
146254f968d6SJason Wang 		return -EBADFD;
146354f968d6SJason Wang 
1464eda29772SRichard Cochran 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
14653811ae76SGao feng 		ret = -EINVAL;
14663811ae76SGao feng 		goto out;
14673811ae76SGao feng 	}
1468eda29772SRichard Cochran 	if (flags & MSG_ERRQUEUE) {
1469eda29772SRichard Cochran 		ret = sock_recv_errqueue(sock->sk, m, total_len,
1470eda29772SRichard Cochran 					 SOL_PACKET, TUN_TX_TIMESTAMP);
1471eda29772SRichard Cochran 		goto out;
1472eda29772SRichard Cochran 	}
1473f96eb74cSZhi Yong Wu 	ret = tun_do_read(tun, tfile, m->msg_iov, total_len,
147405c2828cSMichael S. Tsirkin 			  flags & MSG_DONTWAIT);
147542404c09SDavid S. Miller 	if (ret > total_len) {
147642404c09SDavid S. Miller 		m->msg_flags |= MSG_TRUNC;
147742404c09SDavid S. Miller 		ret = flags & MSG_TRUNC ? ret : total_len;
147842404c09SDavid S. Miller 	}
14793811ae76SGao feng out:
148054f968d6SJason Wang 	tun_put(tun);
148105c2828cSMichael S. Tsirkin 	return ret;
148205c2828cSMichael S. Tsirkin }
148305c2828cSMichael S. Tsirkin 
14841ab5ecb9SStanislav Kinsbursky static int tun_release(struct socket *sock)
14851ab5ecb9SStanislav Kinsbursky {
14861ab5ecb9SStanislav Kinsbursky 	if (sock->sk)
14871ab5ecb9SStanislav Kinsbursky 		sock_put(sock->sk);
14881ab5ecb9SStanislav Kinsbursky 	return 0;
14891ab5ecb9SStanislav Kinsbursky }
14901ab5ecb9SStanislav Kinsbursky 
149105c2828cSMichael S. Tsirkin /* Ops structure to mimic raw sockets with tun */
149205c2828cSMichael S. Tsirkin static const struct proto_ops tun_socket_ops = {
149305c2828cSMichael S. Tsirkin 	.sendmsg = tun_sendmsg,
149405c2828cSMichael S. Tsirkin 	.recvmsg = tun_recvmsg,
14951ab5ecb9SStanislav Kinsbursky 	.release = tun_release,
149605c2828cSMichael S. Tsirkin };
149705c2828cSMichael S. Tsirkin 
149833dccbb0SHerbert Xu static struct proto tun_proto = {
149933dccbb0SHerbert Xu 	.name		= "tun",
150033dccbb0SHerbert Xu 	.owner		= THIS_MODULE,
150154f968d6SJason Wang 	.obj_size	= sizeof(struct tun_file),
150233dccbb0SHerbert Xu };
1503f019a7a5SEric W. Biederman 
1504980c9e8cSDavid Woodhouse static int tun_flags(struct tun_struct *tun)
1505980c9e8cSDavid Woodhouse {
1506980c9e8cSDavid Woodhouse 	int flags = 0;
1507980c9e8cSDavid Woodhouse 
1508980c9e8cSDavid Woodhouse 	if (tun->flags & TUN_TUN_DEV)
1509980c9e8cSDavid Woodhouse 		flags |= IFF_TUN;
1510980c9e8cSDavid Woodhouse 	else
1511980c9e8cSDavid Woodhouse 		flags |= IFF_TAP;
1512980c9e8cSDavid Woodhouse 
1513980c9e8cSDavid Woodhouse 	if (tun->flags & TUN_NO_PI)
1514980c9e8cSDavid Woodhouse 		flags |= IFF_NO_PI;
1515980c9e8cSDavid Woodhouse 
15165d097109SMichael S. Tsirkin 	/* This flag has no real effect.  We track the value for backwards
15175d097109SMichael S. Tsirkin 	 * compatibility.
15185d097109SMichael S. Tsirkin 	 */
1519980c9e8cSDavid Woodhouse 	if (tun->flags & TUN_ONE_QUEUE)
1520980c9e8cSDavid Woodhouse 		flags |= IFF_ONE_QUEUE;
1521980c9e8cSDavid Woodhouse 
1522980c9e8cSDavid Woodhouse 	if (tun->flags & TUN_VNET_HDR)
1523980c9e8cSDavid Woodhouse 		flags |= IFF_VNET_HDR;
1524980c9e8cSDavid Woodhouse 
1525c8d68e6bSJason Wang 	if (tun->flags & TUN_TAP_MQ)
1526c8d68e6bSJason Wang 		flags |= IFF_MULTI_QUEUE;
1527c8d68e6bSJason Wang 
1528274038f8SPavel Emelyanov 	if (tun->flags & TUN_PERSIST)
1529274038f8SPavel Emelyanov 		flags |= IFF_PERSIST;
1530274038f8SPavel Emelyanov 
1531980c9e8cSDavid Woodhouse 	return flags;
1532980c9e8cSDavid Woodhouse }
1533980c9e8cSDavid Woodhouse 
1534980c9e8cSDavid Woodhouse static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1535980c9e8cSDavid Woodhouse 			      char *buf)
1536980c9e8cSDavid Woodhouse {
1537980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1538980c9e8cSDavid Woodhouse 	return sprintf(buf, "0x%x\n", tun_flags(tun));
1539980c9e8cSDavid Woodhouse }
1540980c9e8cSDavid Woodhouse 
1541980c9e8cSDavid Woodhouse static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1542980c9e8cSDavid Woodhouse 			      char *buf)
1543980c9e8cSDavid Woodhouse {
1544980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
15450625c883SEric W. Biederman 	return uid_valid(tun->owner)?
15460625c883SEric W. Biederman 		sprintf(buf, "%u\n",
15470625c883SEric W. Biederman 			from_kuid_munged(current_user_ns(), tun->owner)):
15480625c883SEric W. Biederman 		sprintf(buf, "-1\n");
1549980c9e8cSDavid Woodhouse }
1550980c9e8cSDavid Woodhouse 
1551980c9e8cSDavid Woodhouse static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1552980c9e8cSDavid Woodhouse 			      char *buf)
1553980c9e8cSDavid Woodhouse {
1554980c9e8cSDavid Woodhouse 	struct tun_struct *tun = netdev_priv(to_net_dev(dev));
15550625c883SEric W. Biederman 	return gid_valid(tun->group) ?
15560625c883SEric W. Biederman 		sprintf(buf, "%u\n",
15570625c883SEric W. Biederman 			from_kgid_munged(current_user_ns(), tun->group)):
15580625c883SEric W. Biederman 		sprintf(buf, "-1\n");
1559980c9e8cSDavid Woodhouse }
1560980c9e8cSDavid Woodhouse 
1561980c9e8cSDavid Woodhouse static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1562980c9e8cSDavid Woodhouse static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1563980c9e8cSDavid Woodhouse static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1564980c9e8cSDavid Woodhouse 
1565d647a591SPavel Emelyanov static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
15661da177e4SLinus Torvalds {
15671da177e4SLinus Torvalds 	struct tun_struct *tun;
156854f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
15691da177e4SLinus Torvalds 	struct net_device *dev;
15701da177e4SLinus Torvalds 	int err;
15711da177e4SLinus Torvalds 
15727c0c3b1aSJason Wang 	if (tfile->detached)
15737c0c3b1aSJason Wang 		return -EINVAL;
15747c0c3b1aSJason Wang 
157574a3e5a7SEric W. Biederman 	dev = __dev_get_by_name(net, ifr->ifr_name);
157674a3e5a7SEric W. Biederman 	if (dev) {
1577f85ba780SDavid Woodhouse 		if (ifr->ifr_flags & IFF_TUN_EXCL)
1578f85ba780SDavid Woodhouse 			return -EBUSY;
157974a3e5a7SEric W. Biederman 		if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
158074a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
158174a3e5a7SEric W. Biederman 		else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
158274a3e5a7SEric W. Biederman 			tun = netdev_priv(dev);
158374a3e5a7SEric W. Biederman 		else
158474a3e5a7SEric W. Biederman 			return -EINVAL;
158574a3e5a7SEric W. Biederman 
15868e6d91aeSJason Wang 		if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
15878e6d91aeSJason Wang 		    !!(tun->flags & TUN_TAP_MQ))
15888e6d91aeSJason Wang 			return -EINVAL;
15898e6d91aeSJason Wang 
1590cde8b15fSJason Wang 		if (tun_not_capable(tun))
15912b980dbdSPaul Moore 			return -EPERM;
15925dbbaf2dSPaul Moore 		err = security_tun_dev_open(tun->security);
15932b980dbdSPaul Moore 		if (err < 0)
15942b980dbdSPaul Moore 			return err;
15952b980dbdSPaul Moore 
1596849c9b6fSPavel Emelyanov 		err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
1597a7385ba2SEric W. Biederman 		if (err < 0)
1598a7385ba2SEric W. Biederman 			return err;
15994008e97fSJason Wang 
16004008e97fSJason Wang 		if (tun->flags & TUN_TAP_MQ &&
1601e8dbad66SJason Wang 		    (tun->numqueues + tun->numdisabled > 1)) {
1602e8dbad66SJason Wang 			/* One or more queue has already been attached, no need
1603e8dbad66SJason Wang 			 * to initialize the device again.
1604e8dbad66SJason Wang 			 */
1605e8dbad66SJason Wang 			return 0;
1606e8dbad66SJason Wang 		}
160786a264abSDavid Howells 	}
16081da177e4SLinus Torvalds 	else {
16091da177e4SLinus Torvalds 		char *name;
16101da177e4SLinus Torvalds 		unsigned long flags = 0;
1611edfb6a14SJason Wang 		int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1612edfb6a14SJason Wang 			     MAX_TAP_QUEUES : 1;
16131da177e4SLinus Torvalds 
1614c260b772SEric W. Biederman 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1615ca6bb5d7SDavid Woodhouse 			return -EPERM;
16162b980dbdSPaul Moore 		err = security_tun_dev_create();
16172b980dbdSPaul Moore 		if (err < 0)
16182b980dbdSPaul Moore 			return err;
1619ca6bb5d7SDavid Woodhouse 
16201da177e4SLinus Torvalds 		/* Set dev type */
16211da177e4SLinus Torvalds 		if (ifr->ifr_flags & IFF_TUN) {
16221da177e4SLinus Torvalds 			/* TUN device */
16231da177e4SLinus Torvalds 			flags |= TUN_TUN_DEV;
16241da177e4SLinus Torvalds 			name = "tun%d";
16251da177e4SLinus Torvalds 		} else if (ifr->ifr_flags & IFF_TAP) {
16261da177e4SLinus Torvalds 			/* TAP device */
16271da177e4SLinus Torvalds 			flags |= TUN_TAP_DEV;
16281da177e4SLinus Torvalds 			name = "tap%d";
16291da177e4SLinus Torvalds 		} else
163036989b90SKusanagi Kouichi 			return -EINVAL;
16311da177e4SLinus Torvalds 
16321da177e4SLinus Torvalds 		if (*ifr->ifr_name)
16331da177e4SLinus Torvalds 			name = ifr->ifr_name;
16341da177e4SLinus Torvalds 
1635c8d68e6bSJason Wang 		dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1636c835a677STom Gundersen 				       NET_NAME_UNKNOWN, tun_setup, queues,
1637c835a677STom Gundersen 				       queues);
1638edfb6a14SJason Wang 
16391da177e4SLinus Torvalds 		if (!dev)
16401da177e4SLinus Torvalds 			return -ENOMEM;
16411da177e4SLinus Torvalds 
1642fc54c658SPavel Emelyanov 		dev_net_set(dev, net);
1643f019a7a5SEric W. Biederman 		dev->rtnl_link_ops = &tun_link_ops;
1644fb7589a1SPavel Emelyanov 		dev->ifindex = tfile->ifindex;
1645758e43b7SStephen Hemminger 
16461da177e4SLinus Torvalds 		tun = netdev_priv(dev);
16471da177e4SLinus Torvalds 		tun->dev = dev;
16481da177e4SLinus Torvalds 		tun->flags = flags;
1649f271b2ccSMax Krasnyansky 		tun->txflt.count = 0;
1650d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
16511da177e4SLinus Torvalds 
165254f968d6SJason Wang 		tun->filter_attached = false;
165354f968d6SJason Wang 		tun->sndbuf = tfile->socket.sk->sk_sndbuf;
165433dccbb0SHerbert Xu 
165596442e42SJason Wang 		spin_lock_init(&tun->lock);
165696442e42SJason Wang 
16575dbbaf2dSPaul Moore 		err = security_tun_dev_alloc_security(&tun->security);
16585dbbaf2dSPaul Moore 		if (err < 0)
16595dbbaf2dSPaul Moore 			goto err_free_dev;
16602b980dbdSPaul Moore 
16611da177e4SLinus Torvalds 		tun_net_init(dev);
1662944a1376SPavel Emelyanov 		tun_flow_init(tun);
166396442e42SJason Wang 
166488255375SMichał Mirosław 		dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
16656680ec68SJason Wang 				   TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
16666680ec68SJason Wang 				   NETIF_F_HW_VLAN_STAG_TX;
166788255375SMichał Mirosław 		dev->features = dev->hw_features;
16686671b224SFernando Luis Vazquez Cao 		dev->vlan_features = dev->features &
16696671b224SFernando Luis Vazquez Cao 				     ~(NETIF_F_HW_VLAN_CTAG_TX |
16706671b224SFernando Luis Vazquez Cao 				       NETIF_F_HW_VLAN_STAG_TX);
167188255375SMichał Mirosław 
16724008e97fSJason Wang 		INIT_LIST_HEAD(&tun->disabled);
1673849c9b6fSPavel Emelyanov 		err = tun_attach(tun, file, false);
1674eb0fb363SJason Wang 		if (err < 0)
1675662ca437SJason Wang 			goto err_free_flow;
1676eb0fb363SJason Wang 
16771da177e4SLinus Torvalds 		err = register_netdevice(tun->dev);
16781da177e4SLinus Torvalds 		if (err < 0)
1679662ca437SJason Wang 			goto err_detach;
16809c3fea6aSHerbert Xu 
1681980c9e8cSDavid Woodhouse 		if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1682980c9e8cSDavid Woodhouse 		    device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1683980c9e8cSDavid Woodhouse 		    device_create_file(&tun->dev->dev, &dev_attr_group))
16846b8a66eeSJoe Perches 			pr_err("Failed to create tun sysfs files\n");
1685af668b3cSMichael S. Tsirkin 	}
1686980c9e8cSDavid Woodhouse 
1687eb0fb363SJason Wang 	netif_carrier_on(tun->dev);
16881da177e4SLinus Torvalds 
16896b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_set_iff\n");
16901da177e4SLinus Torvalds 
16911da177e4SLinus Torvalds 	if (ifr->ifr_flags & IFF_NO_PI)
16921da177e4SLinus Torvalds 		tun->flags |= TUN_NO_PI;
1693a26af1e0SNathaniel Filardo 	else
1694a26af1e0SNathaniel Filardo 		tun->flags &= ~TUN_NO_PI;
16951da177e4SLinus Torvalds 
16965d097109SMichael S. Tsirkin 	/* This flag has no real effect.  We track the value for backwards
16975d097109SMichael S. Tsirkin 	 * compatibility.
16985d097109SMichael S. Tsirkin 	 */
16991da177e4SLinus Torvalds 	if (ifr->ifr_flags & IFF_ONE_QUEUE)
17001da177e4SLinus Torvalds 		tun->flags |= TUN_ONE_QUEUE;
1701a26af1e0SNathaniel Filardo 	else
1702a26af1e0SNathaniel Filardo 		tun->flags &= ~TUN_ONE_QUEUE;
17031da177e4SLinus Torvalds 
1704f43798c2SRusty Russell 	if (ifr->ifr_flags & IFF_VNET_HDR)
1705f43798c2SRusty Russell 		tun->flags |= TUN_VNET_HDR;
1706f43798c2SRusty Russell 	else
1707f43798c2SRusty Russell 		tun->flags &= ~TUN_VNET_HDR;
1708f43798c2SRusty Russell 
1709c8d68e6bSJason Wang 	if (ifr->ifr_flags & IFF_MULTI_QUEUE)
1710c8d68e6bSJason Wang 		tun->flags |= TUN_TAP_MQ;
1711c8d68e6bSJason Wang 	else
1712c8d68e6bSJason Wang 		tun->flags &= ~TUN_TAP_MQ;
1713c8d68e6bSJason Wang 
1714e35259a9SMax Krasnyansky 	/* Make sure persistent devices do not get stuck in
1715e35259a9SMax Krasnyansky 	 * xoff state.
1716e35259a9SMax Krasnyansky 	 */
1717e35259a9SMax Krasnyansky 	if (netif_running(tun->dev))
1718c8d68e6bSJason Wang 		netif_tx_wake_all_queues(tun->dev);
1719e35259a9SMax Krasnyansky 
17201da177e4SLinus Torvalds 	strcpy(ifr->ifr_name, tun->dev->name);
17211da177e4SLinus Torvalds 	return 0;
17221da177e4SLinus Torvalds 
1723662ca437SJason Wang err_detach:
1724662ca437SJason Wang 	tun_detach_all(dev);
1725662ca437SJason Wang err_free_flow:
1726662ca437SJason Wang 	tun_flow_uninit(tun);
1727662ca437SJason Wang 	security_tun_dev_free_security(tun->security);
17281da177e4SLinus Torvalds err_free_dev:
17291da177e4SLinus Torvalds 	free_netdev(dev);
17301da177e4SLinus Torvalds 	return err;
17311da177e4SLinus Torvalds }
17321da177e4SLinus Torvalds 
17339ce99cf6SRami Rosen static void tun_get_iff(struct net *net, struct tun_struct *tun,
1734876bfd4dSHerbert Xu 		       struct ifreq *ifr)
1735e3b99556SMark McLoughlin {
17366b8a66eeSJoe Perches 	tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1737e3b99556SMark McLoughlin 
1738e3b99556SMark McLoughlin 	strcpy(ifr->ifr_name, tun->dev->name);
1739e3b99556SMark McLoughlin 
1740980c9e8cSDavid Woodhouse 	ifr->ifr_flags = tun_flags(tun);
1741e3b99556SMark McLoughlin 
1742e3b99556SMark McLoughlin }
1743e3b99556SMark McLoughlin 
17445228ddc9SRusty Russell /* This is like a cut-down ethtool ops, except done via tun fd so no
17455228ddc9SRusty Russell  * privs required. */
174688255375SMichał Mirosław static int set_offload(struct tun_struct *tun, unsigned long arg)
17475228ddc9SRusty Russell {
1748c8f44affSMichał Mirosław 	netdev_features_t features = 0;
17495228ddc9SRusty Russell 
17505228ddc9SRusty Russell 	if (arg & TUN_F_CSUM) {
175188255375SMichał Mirosław 		features |= NETIF_F_HW_CSUM;
17525228ddc9SRusty Russell 		arg &= ~TUN_F_CSUM;
17535228ddc9SRusty Russell 
17545228ddc9SRusty Russell 		if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
17555228ddc9SRusty Russell 			if (arg & TUN_F_TSO_ECN) {
17565228ddc9SRusty Russell 				features |= NETIF_F_TSO_ECN;
17575228ddc9SRusty Russell 				arg &= ~TUN_F_TSO_ECN;
17585228ddc9SRusty Russell 			}
17595228ddc9SRusty Russell 			if (arg & TUN_F_TSO4)
17605228ddc9SRusty Russell 				features |= NETIF_F_TSO;
17615228ddc9SRusty Russell 			if (arg & TUN_F_TSO6)
17625228ddc9SRusty Russell 				features |= NETIF_F_TSO6;
17635228ddc9SRusty Russell 			arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
17645228ddc9SRusty Russell 		}
1765e36aa25aSSridhar Samudrala 
1766e36aa25aSSridhar Samudrala 		if (arg & TUN_F_UFO) {
1767e36aa25aSSridhar Samudrala 			features |= NETIF_F_UFO;
1768e36aa25aSSridhar Samudrala 			arg &= ~TUN_F_UFO;
1769e36aa25aSSridhar Samudrala 		}
17705228ddc9SRusty Russell 	}
17715228ddc9SRusty Russell 
17725228ddc9SRusty Russell 	/* This gives the user a way to test for new features in future by
17735228ddc9SRusty Russell 	 * trying to set them. */
17745228ddc9SRusty Russell 	if (arg)
17755228ddc9SRusty Russell 		return -EINVAL;
17765228ddc9SRusty Russell 
177788255375SMichał Mirosław 	tun->set_features = features;
177888255375SMichał Mirosław 	netdev_update_features(tun->dev);
17795228ddc9SRusty Russell 
17805228ddc9SRusty Russell 	return 0;
17815228ddc9SRusty Russell }
17825228ddc9SRusty Russell 
1783c8d68e6bSJason Wang static void tun_detach_filter(struct tun_struct *tun, int n)
1784c8d68e6bSJason Wang {
1785c8d68e6bSJason Wang 	int i;
1786c8d68e6bSJason Wang 	struct tun_file *tfile;
1787c8d68e6bSJason Wang 
1788c8d68e6bSJason Wang 	for (i = 0; i < n; i++) {
1789b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1790c8d68e6bSJason Wang 		sk_detach_filter(tfile->socket.sk);
1791c8d68e6bSJason Wang 	}
1792c8d68e6bSJason Wang 
1793c8d68e6bSJason Wang 	tun->filter_attached = false;
1794c8d68e6bSJason Wang }
1795c8d68e6bSJason Wang 
1796c8d68e6bSJason Wang static int tun_attach_filter(struct tun_struct *tun)
1797c8d68e6bSJason Wang {
1798c8d68e6bSJason Wang 	int i, ret = 0;
1799c8d68e6bSJason Wang 	struct tun_file *tfile;
1800c8d68e6bSJason Wang 
1801c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
1802b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1803c8d68e6bSJason Wang 		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1804c8d68e6bSJason Wang 		if (ret) {
1805c8d68e6bSJason Wang 			tun_detach_filter(tun, i);
1806c8d68e6bSJason Wang 			return ret;
1807c8d68e6bSJason Wang 		}
1808c8d68e6bSJason Wang 	}
1809c8d68e6bSJason Wang 
1810c8d68e6bSJason Wang 	tun->filter_attached = true;
1811c8d68e6bSJason Wang 	return ret;
1812c8d68e6bSJason Wang }
1813c8d68e6bSJason Wang 
1814c8d68e6bSJason Wang static void tun_set_sndbuf(struct tun_struct *tun)
1815c8d68e6bSJason Wang {
1816c8d68e6bSJason Wang 	struct tun_file *tfile;
1817c8d68e6bSJason Wang 	int i;
1818c8d68e6bSJason Wang 
1819c8d68e6bSJason Wang 	for (i = 0; i < tun->numqueues; i++) {
1820b8deabd3SJason Wang 		tfile = rtnl_dereference(tun->tfiles[i]);
1821c8d68e6bSJason Wang 		tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1822c8d68e6bSJason Wang 	}
1823c8d68e6bSJason Wang }
1824c8d68e6bSJason Wang 
1825cde8b15fSJason Wang static int tun_set_queue(struct file *file, struct ifreq *ifr)
1826cde8b15fSJason Wang {
1827cde8b15fSJason Wang 	struct tun_file *tfile = file->private_data;
1828cde8b15fSJason Wang 	struct tun_struct *tun;
1829cde8b15fSJason Wang 	int ret = 0;
1830cde8b15fSJason Wang 
1831cde8b15fSJason Wang 	rtnl_lock();
1832cde8b15fSJason Wang 
1833cde8b15fSJason Wang 	if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
18344008e97fSJason Wang 		tun = tfile->detached;
18355dbbaf2dSPaul Moore 		if (!tun) {
1836cde8b15fSJason Wang 			ret = -EINVAL;
18375dbbaf2dSPaul Moore 			goto unlock;
18385dbbaf2dSPaul Moore 		}
18395dbbaf2dSPaul Moore 		ret = security_tun_dev_attach_queue(tun->security);
18405dbbaf2dSPaul Moore 		if (ret < 0)
18415dbbaf2dSPaul Moore 			goto unlock;
1842849c9b6fSPavel Emelyanov 		ret = tun_attach(tun, file, false);
18434008e97fSJason Wang 	} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
1844b8deabd3SJason Wang 		tun = rtnl_dereference(tfile->tun);
18459e85722dSJason Wang 		if (!tun || !(tun->flags & TUN_TAP_MQ) || tfile->detached)
18464008e97fSJason Wang 			ret = -EINVAL;
1847cde8b15fSJason Wang 		else
18484008e97fSJason Wang 			__tun_detach(tfile, false);
18494008e97fSJason Wang 	} else
1850cde8b15fSJason Wang 		ret = -EINVAL;
1851cde8b15fSJason Wang 
18525dbbaf2dSPaul Moore unlock:
1853cde8b15fSJason Wang 	rtnl_unlock();
1854cde8b15fSJason Wang 	return ret;
1855cde8b15fSJason Wang }
1856cde8b15fSJason Wang 
185750857e2aSArnd Bergmann static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
185850857e2aSArnd Bergmann 			    unsigned long arg, int ifreq_len)
18591da177e4SLinus Torvalds {
186036b50babSEric W. Biederman 	struct tun_file *tfile = file->private_data;
1861631ab46bSEric W. Biederman 	struct tun_struct *tun;
18621da177e4SLinus Torvalds 	void __user* argp = (void __user*)arg;
18631da177e4SLinus Torvalds 	struct ifreq ifr;
18640625c883SEric W. Biederman 	kuid_t owner;
18650625c883SEric W. Biederman 	kgid_t group;
186633dccbb0SHerbert Xu 	int sndbuf;
1867d9d52b51SMichael S. Tsirkin 	int vnet_hdr_sz;
1868fb7589a1SPavel Emelyanov 	unsigned int ifindex;
1869f271b2ccSMax Krasnyansky 	int ret;
18701da177e4SLinus Torvalds 
1871cde8b15fSJason Wang 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
187250857e2aSArnd Bergmann 		if (copy_from_user(&ifr, argp, ifreq_len))
18731da177e4SLinus Torvalds 			return -EFAULT;
18748bbb1813SDavid S. Miller 	} else {
1875a117dacdSMathias Krause 		memset(&ifr, 0, sizeof(ifr));
18768bbb1813SDavid S. Miller 	}
1877631ab46bSEric W. Biederman 	if (cmd == TUNGETFEATURES) {
1878631ab46bSEric W. Biederman 		/* Currently this just means: "what IFF flags are valid?".
1879631ab46bSEric W. Biederman 		 * This is needed because we never checked for invalid flags on
1880631ab46bSEric W. Biederman 		 * TUNSETIFF. */
1881631ab46bSEric W. Biederman 		return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
1882cde8b15fSJason Wang 				IFF_VNET_HDR | IFF_MULTI_QUEUE,
1883631ab46bSEric W. Biederman 				(unsigned int __user*)argp);
1884cde8b15fSJason Wang 	} else if (cmd == TUNSETQUEUE)
1885cde8b15fSJason Wang 		return tun_set_queue(file, &ifr);
1886631ab46bSEric W. Biederman 
1887c8d68e6bSJason Wang 	ret = 0;
1888876bfd4dSHerbert Xu 	rtnl_lock();
1889876bfd4dSHerbert Xu 
189036b50babSEric W. Biederman 	tun = __tun_get(tfile);
18911da177e4SLinus Torvalds 	if (cmd == TUNSETIFF && !tun) {
18921da177e4SLinus Torvalds 		ifr.ifr_name[IFNAMSIZ-1] = '\0';
18931da177e4SLinus Torvalds 
1894876bfd4dSHerbert Xu 		ret = tun_set_iff(tfile->net, file, &ifr);
18951da177e4SLinus Torvalds 
1896876bfd4dSHerbert Xu 		if (ret)
1897876bfd4dSHerbert Xu 			goto unlock;
18981da177e4SLinus Torvalds 
189950857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
1900876bfd4dSHerbert Xu 			ret = -EFAULT;
1901876bfd4dSHerbert Xu 		goto unlock;
19021da177e4SLinus Torvalds 	}
1903fb7589a1SPavel Emelyanov 	if (cmd == TUNSETIFINDEX) {
1904fb7589a1SPavel Emelyanov 		ret = -EPERM;
1905fb7589a1SPavel Emelyanov 		if (tun)
1906fb7589a1SPavel Emelyanov 			goto unlock;
1907fb7589a1SPavel Emelyanov 
1908fb7589a1SPavel Emelyanov 		ret = -EFAULT;
1909fb7589a1SPavel Emelyanov 		if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
1910fb7589a1SPavel Emelyanov 			goto unlock;
1911fb7589a1SPavel Emelyanov 
1912fb7589a1SPavel Emelyanov 		ret = 0;
1913fb7589a1SPavel Emelyanov 		tfile->ifindex = ifindex;
1914fb7589a1SPavel Emelyanov 		goto unlock;
1915fb7589a1SPavel Emelyanov 	}
19161da177e4SLinus Torvalds 
1917876bfd4dSHerbert Xu 	ret = -EBADFD;
19181da177e4SLinus Torvalds 	if (!tun)
1919876bfd4dSHerbert Xu 		goto unlock;
19201da177e4SLinus Torvalds 
19211e588338SJason Wang 	tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
19221da177e4SLinus Torvalds 
1923631ab46bSEric W. Biederman 	ret = 0;
19241da177e4SLinus Torvalds 	switch (cmd) {
1925e3b99556SMark McLoughlin 	case TUNGETIFF:
19269ce99cf6SRami Rosen 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1927e3b99556SMark McLoughlin 
19283d407a80SPavel Emelyanov 		if (tfile->detached)
19293d407a80SPavel Emelyanov 			ifr.ifr_flags |= IFF_DETACH_QUEUE;
1930849c9b6fSPavel Emelyanov 		if (!tfile->socket.sk->sk_filter)
1931849c9b6fSPavel Emelyanov 			ifr.ifr_flags |= IFF_NOFILTER;
19323d407a80SPavel Emelyanov 
193350857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
1934631ab46bSEric W. Biederman 			ret = -EFAULT;
1935e3b99556SMark McLoughlin 		break;
1936e3b99556SMark McLoughlin 
19371da177e4SLinus Torvalds 	case TUNSETNOCSUM:
19381da177e4SLinus Torvalds 		/* Disable/Enable checksum */
19391da177e4SLinus Torvalds 
194088255375SMichał Mirosław 		/* [unimplemented] */
194188255375SMichał Mirosław 		tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
19426b8a66eeSJoe Perches 			  arg ? "disabled" : "enabled");
19431da177e4SLinus Torvalds 		break;
19441da177e4SLinus Torvalds 
19451da177e4SLinus Torvalds 	case TUNSETPERSIST:
194654f968d6SJason Wang 		/* Disable/Enable persist mode. Keep an extra reference to the
194754f968d6SJason Wang 		 * module to prevent the module being unprobed.
194854f968d6SJason Wang 		 */
1949dd38bd85SJason Wang 		if (arg && !(tun->flags & TUN_PERSIST)) {
19501da177e4SLinus Torvalds 			tun->flags |= TUN_PERSIST;
195154f968d6SJason Wang 			__module_get(THIS_MODULE);
1952dd38bd85SJason Wang 		}
1953dd38bd85SJason Wang 		if (!arg && (tun->flags & TUN_PERSIST)) {
19541da177e4SLinus Torvalds 			tun->flags &= ~TUN_PERSIST;
195554f968d6SJason Wang 			module_put(THIS_MODULE);
195654f968d6SJason Wang 		}
19571da177e4SLinus Torvalds 
19586b8a66eeSJoe Perches 		tun_debug(KERN_INFO, tun, "persist %s\n",
19596b8a66eeSJoe Perches 			  arg ? "enabled" : "disabled");
19601da177e4SLinus Torvalds 		break;
19611da177e4SLinus Torvalds 
19621da177e4SLinus Torvalds 	case TUNSETOWNER:
19631da177e4SLinus Torvalds 		/* Set owner of the device */
19640625c883SEric W. Biederman 		owner = make_kuid(current_user_ns(), arg);
19650625c883SEric W. Biederman 		if (!uid_valid(owner)) {
19660625c883SEric W. Biederman 			ret = -EINVAL;
19670625c883SEric W. Biederman 			break;
19680625c883SEric W. Biederman 		}
19690625c883SEric W. Biederman 		tun->owner = owner;
19701e588338SJason Wang 		tun_debug(KERN_INFO, tun, "owner set to %u\n",
19710625c883SEric W. Biederman 			  from_kuid(&init_user_ns, tun->owner));
19721da177e4SLinus Torvalds 		break;
19731da177e4SLinus Torvalds 
19748c644623SGuido Guenther 	case TUNSETGROUP:
19758c644623SGuido Guenther 		/* Set group of the device */
19760625c883SEric W. Biederman 		group = make_kgid(current_user_ns(), arg);
19770625c883SEric W. Biederman 		if (!gid_valid(group)) {
19780625c883SEric W. Biederman 			ret = -EINVAL;
19790625c883SEric W. Biederman 			break;
19800625c883SEric W. Biederman 		}
19810625c883SEric W. Biederman 		tun->group = group;
19821e588338SJason Wang 		tun_debug(KERN_INFO, tun, "group set to %u\n",
19830625c883SEric W. Biederman 			  from_kgid(&init_user_ns, tun->group));
19848c644623SGuido Guenther 		break;
19858c644623SGuido Guenther 
1986ff4cc3acSMike Kershaw 	case TUNSETLINK:
1987ff4cc3acSMike Kershaw 		/* Only allow setting the type when the interface is down */
1988ff4cc3acSMike Kershaw 		if (tun->dev->flags & IFF_UP) {
19896b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun,
19906b8a66eeSJoe Perches 				  "Linktype set failed because interface is up\n");
199148abfe05SDavid S. Miller 			ret = -EBUSY;
1992ff4cc3acSMike Kershaw 		} else {
1993ff4cc3acSMike Kershaw 			tun->dev->type = (int) arg;
19946b8a66eeSJoe Perches 			tun_debug(KERN_INFO, tun, "linktype set to %d\n",
19956b8a66eeSJoe Perches 				  tun->dev->type);
199648abfe05SDavid S. Miller 			ret = 0;
1997ff4cc3acSMike Kershaw 		}
1998631ab46bSEric W. Biederman 		break;
1999ff4cc3acSMike Kershaw 
20001da177e4SLinus Torvalds #ifdef TUN_DEBUG
20011da177e4SLinus Torvalds 	case TUNSETDEBUG:
20021da177e4SLinus Torvalds 		tun->debug = arg;
20031da177e4SLinus Torvalds 		break;
20041da177e4SLinus Torvalds #endif
20055228ddc9SRusty Russell 	case TUNSETOFFLOAD:
200688255375SMichał Mirosław 		ret = set_offload(tun, arg);
2007631ab46bSEric W. Biederman 		break;
20085228ddc9SRusty Russell 
2009f271b2ccSMax Krasnyansky 	case TUNSETTXFILTER:
2010f271b2ccSMax Krasnyansky 		/* Can be set only for TAPs */
2011631ab46bSEric W. Biederman 		ret = -EINVAL;
2012f271b2ccSMax Krasnyansky 		if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2013631ab46bSEric W. Biederman 			break;
2014c0e5a8c2SHarvey Harrison 		ret = update_filter(&tun->txflt, (void __user *)arg);
2015631ab46bSEric W. Biederman 		break;
20161da177e4SLinus Torvalds 
20171da177e4SLinus Torvalds 	case SIOCGIFHWADDR:
2018b595076aSUwe Kleine-König 		/* Get hw address */
2019f271b2ccSMax Krasnyansky 		memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2020f271b2ccSMax Krasnyansky 		ifr.ifr_hwaddr.sa_family = tun->dev->type;
202150857e2aSArnd Bergmann 		if (copy_to_user(argp, &ifr, ifreq_len))
2022631ab46bSEric W. Biederman 			ret = -EFAULT;
2023631ab46bSEric W. Biederman 		break;
20241da177e4SLinus Torvalds 
20251da177e4SLinus Torvalds 	case SIOCSIFHWADDR:
2026f271b2ccSMax Krasnyansky 		/* Set hw address */
20276b8a66eeSJoe Perches 		tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
20286b8a66eeSJoe Perches 			  ifr.ifr_hwaddr.sa_data);
202940102371SKim B. Heino 
203040102371SKim B. Heino 		ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2031631ab46bSEric W. Biederman 		break;
203233dccbb0SHerbert Xu 
203333dccbb0SHerbert Xu 	case TUNGETSNDBUF:
203454f968d6SJason Wang 		sndbuf = tfile->socket.sk->sk_sndbuf;
203533dccbb0SHerbert Xu 		if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
203633dccbb0SHerbert Xu 			ret = -EFAULT;
203733dccbb0SHerbert Xu 		break;
203833dccbb0SHerbert Xu 
203933dccbb0SHerbert Xu 	case TUNSETSNDBUF:
204033dccbb0SHerbert Xu 		if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
204133dccbb0SHerbert Xu 			ret = -EFAULT;
204233dccbb0SHerbert Xu 			break;
204333dccbb0SHerbert Xu 		}
204433dccbb0SHerbert Xu 
2045c8d68e6bSJason Wang 		tun->sndbuf = sndbuf;
2046c8d68e6bSJason Wang 		tun_set_sndbuf(tun);
204733dccbb0SHerbert Xu 		break;
204833dccbb0SHerbert Xu 
2049d9d52b51SMichael S. Tsirkin 	case TUNGETVNETHDRSZ:
2050d9d52b51SMichael S. Tsirkin 		vnet_hdr_sz = tun->vnet_hdr_sz;
2051d9d52b51SMichael S. Tsirkin 		if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2052d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
2053d9d52b51SMichael S. Tsirkin 		break;
2054d9d52b51SMichael S. Tsirkin 
2055d9d52b51SMichael S. Tsirkin 	case TUNSETVNETHDRSZ:
2056d9d52b51SMichael S. Tsirkin 		if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2057d9d52b51SMichael S. Tsirkin 			ret = -EFAULT;
2058d9d52b51SMichael S. Tsirkin 			break;
2059d9d52b51SMichael S. Tsirkin 		}
2060d9d52b51SMichael S. Tsirkin 		if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2061d9d52b51SMichael S. Tsirkin 			ret = -EINVAL;
2062d9d52b51SMichael S. Tsirkin 			break;
2063d9d52b51SMichael S. Tsirkin 		}
2064d9d52b51SMichael S. Tsirkin 
2065d9d52b51SMichael S. Tsirkin 		tun->vnet_hdr_sz = vnet_hdr_sz;
2066d9d52b51SMichael S. Tsirkin 		break;
2067d9d52b51SMichael S. Tsirkin 
206899405162SMichael S. Tsirkin 	case TUNATTACHFILTER:
206999405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
207099405162SMichael S. Tsirkin 		ret = -EINVAL;
207199405162SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
207299405162SMichael S. Tsirkin 			break;
207399405162SMichael S. Tsirkin 		ret = -EFAULT;
207454f968d6SJason Wang 		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
207599405162SMichael S. Tsirkin 			break;
207699405162SMichael S. Tsirkin 
2077c8d68e6bSJason Wang 		ret = tun_attach_filter(tun);
207899405162SMichael S. Tsirkin 		break;
207999405162SMichael S. Tsirkin 
208099405162SMichael S. Tsirkin 	case TUNDETACHFILTER:
208199405162SMichael S. Tsirkin 		/* Can be set only for TAPs */
208299405162SMichael S. Tsirkin 		ret = -EINVAL;
208399405162SMichael S. Tsirkin 		if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
208499405162SMichael S. Tsirkin 			break;
2085c8d68e6bSJason Wang 		ret = 0;
2086c8d68e6bSJason Wang 		tun_detach_filter(tun, tun->numqueues);
208799405162SMichael S. Tsirkin 		break;
208899405162SMichael S. Tsirkin 
208976975e9cSPavel Emelyanov 	case TUNGETFILTER:
209076975e9cSPavel Emelyanov 		ret = -EINVAL;
209176975e9cSPavel Emelyanov 		if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
209276975e9cSPavel Emelyanov 			break;
209376975e9cSPavel Emelyanov 		ret = -EFAULT;
209476975e9cSPavel Emelyanov 		if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
209576975e9cSPavel Emelyanov 			break;
209676975e9cSPavel Emelyanov 		ret = 0;
209776975e9cSPavel Emelyanov 		break;
209876975e9cSPavel Emelyanov 
20991da177e4SLinus Torvalds 	default:
2100631ab46bSEric W. Biederman 		ret = -EINVAL;
2101631ab46bSEric W. Biederman 		break;
2102ee289b64SJoe Perches 	}
21031da177e4SLinus Torvalds 
2104876bfd4dSHerbert Xu unlock:
2105876bfd4dSHerbert Xu 	rtnl_unlock();
2106876bfd4dSHerbert Xu 	if (tun)
2107631ab46bSEric W. Biederman 		tun_put(tun);
2108631ab46bSEric W. Biederman 	return ret;
21091da177e4SLinus Torvalds }
21101da177e4SLinus Torvalds 
211150857e2aSArnd Bergmann static long tun_chr_ioctl(struct file *file,
211250857e2aSArnd Bergmann 			  unsigned int cmd, unsigned long arg)
211350857e2aSArnd Bergmann {
211450857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
211550857e2aSArnd Bergmann }
211650857e2aSArnd Bergmann 
211750857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
211850857e2aSArnd Bergmann static long tun_chr_compat_ioctl(struct file *file,
211950857e2aSArnd Bergmann 			 unsigned int cmd, unsigned long arg)
212050857e2aSArnd Bergmann {
212150857e2aSArnd Bergmann 	switch (cmd) {
212250857e2aSArnd Bergmann 	case TUNSETIFF:
212350857e2aSArnd Bergmann 	case TUNGETIFF:
212450857e2aSArnd Bergmann 	case TUNSETTXFILTER:
212550857e2aSArnd Bergmann 	case TUNGETSNDBUF:
212650857e2aSArnd Bergmann 	case TUNSETSNDBUF:
212750857e2aSArnd Bergmann 	case SIOCGIFHWADDR:
212850857e2aSArnd Bergmann 	case SIOCSIFHWADDR:
212950857e2aSArnd Bergmann 		arg = (unsigned long)compat_ptr(arg);
213050857e2aSArnd Bergmann 		break;
213150857e2aSArnd Bergmann 	default:
213250857e2aSArnd Bergmann 		arg = (compat_ulong_t)arg;
213350857e2aSArnd Bergmann 		break;
213450857e2aSArnd Bergmann 	}
213550857e2aSArnd Bergmann 
213650857e2aSArnd Bergmann 	/*
213750857e2aSArnd Bergmann 	 * compat_ifreq is shorter than ifreq, so we must not access beyond
213850857e2aSArnd Bergmann 	 * the end of that structure. All fields that are used in this
213950857e2aSArnd Bergmann 	 * driver are compatible though, we don't need to convert the
214050857e2aSArnd Bergmann 	 * contents.
214150857e2aSArnd Bergmann 	 */
214250857e2aSArnd Bergmann 	return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
214350857e2aSArnd Bergmann }
214450857e2aSArnd Bergmann #endif /* CONFIG_COMPAT */
214550857e2aSArnd Bergmann 
21461da177e4SLinus Torvalds static int tun_chr_fasync(int fd, struct file *file, int on)
21471da177e4SLinus Torvalds {
214854f968d6SJason Wang 	struct tun_file *tfile = file->private_data;
21491da177e4SLinus Torvalds 	int ret;
21501da177e4SLinus Torvalds 
215154f968d6SJason Wang 	if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
21529d319522SJonathan Corbet 		goto out;
21531da177e4SLinus Torvalds 
21541da177e4SLinus Torvalds 	if (on) {
2155*e0b93eddSJeff Layton 		__f_setown(file, task_pid(current), PIDTYPE_PID, 0);
215654f968d6SJason Wang 		tfile->flags |= TUN_FASYNC;
21571da177e4SLinus Torvalds 	} else
215854f968d6SJason Wang 		tfile->flags &= ~TUN_FASYNC;
21599d319522SJonathan Corbet 	ret = 0;
21609d319522SJonathan Corbet out:
21619d319522SJonathan Corbet 	return ret;
21621da177e4SLinus Torvalds }
21631da177e4SLinus Torvalds 
21641da177e4SLinus Torvalds static int tun_chr_open(struct inode *inode, struct file * file)
21651da177e4SLinus Torvalds {
2166631ab46bSEric W. Biederman 	struct tun_file *tfile;
2167deed49fbSThomas Gleixner 
21686b8a66eeSJoe Perches 	DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2169631ab46bSEric W. Biederman 
217054f968d6SJason Wang 	tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
217154f968d6SJason Wang 					    &tun_proto);
2172631ab46bSEric W. Biederman 	if (!tfile)
2173631ab46bSEric W. Biederman 		return -ENOMEM;
2174c956674bSMonam Agarwal 	RCU_INIT_POINTER(tfile->tun, NULL);
217536b50babSEric W. Biederman 	tfile->net = get_net(current->nsproxy->net_ns);
217654f968d6SJason Wang 	tfile->flags = 0;
2177fb7589a1SPavel Emelyanov 	tfile->ifindex = 0;
217854f968d6SJason Wang 
217954f968d6SJason Wang 	init_waitqueue_head(&tfile->wq.wait);
21809e641bdcSXi Wang 	RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
218154f968d6SJason Wang 
218254f968d6SJason Wang 	tfile->socket.file = file;
218354f968d6SJason Wang 	tfile->socket.ops = &tun_socket_ops;
218454f968d6SJason Wang 
218554f968d6SJason Wang 	sock_init_data(&tfile->socket, &tfile->sk);
218654f968d6SJason Wang 	sk_change_net(&tfile->sk, tfile->net);
218754f968d6SJason Wang 
218854f968d6SJason Wang 	tfile->sk.sk_write_space = tun_sock_write_space;
218954f968d6SJason Wang 	tfile->sk.sk_sndbuf = INT_MAX;
219054f968d6SJason Wang 
2191631ab46bSEric W. Biederman 	file->private_data = tfile;
219254f968d6SJason Wang 	set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
21934008e97fSJason Wang 	INIT_LIST_HEAD(&tfile->next);
219454f968d6SJason Wang 
219519a6afb2SJason Wang 	sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
219619a6afb2SJason Wang 
21971da177e4SLinus Torvalds 	return 0;
21981da177e4SLinus Torvalds }
21991da177e4SLinus Torvalds 
22001da177e4SLinus Torvalds static int tun_chr_close(struct inode *inode, struct file *file)
22011da177e4SLinus Torvalds {
2202631ab46bSEric W. Biederman 	struct tun_file *tfile = file->private_data;
220354f968d6SJason Wang 	struct net *net = tfile->net;
22041da177e4SLinus Torvalds 
2205c8d68e6bSJason Wang 	tun_detach(tfile, true);
220654f968d6SJason Wang 	put_net(net);
22071da177e4SLinus Torvalds 
22081da177e4SLinus Torvalds 	return 0;
22091da177e4SLinus Torvalds }
22101da177e4SLinus Torvalds 
221193e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
221293e14b6dSMasatake YAMATO static int tun_chr_show_fdinfo(struct seq_file *m, struct file *f)
221393e14b6dSMasatake YAMATO {
221493e14b6dSMasatake YAMATO 	struct tun_struct *tun;
221593e14b6dSMasatake YAMATO 	struct ifreq ifr;
221693e14b6dSMasatake YAMATO 
221793e14b6dSMasatake YAMATO 	memset(&ifr, 0, sizeof(ifr));
221893e14b6dSMasatake YAMATO 
221993e14b6dSMasatake YAMATO 	rtnl_lock();
222093e14b6dSMasatake YAMATO 	tun = tun_get(f);
222193e14b6dSMasatake YAMATO 	if (tun)
222293e14b6dSMasatake YAMATO 		tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
222393e14b6dSMasatake YAMATO 	rtnl_unlock();
222493e14b6dSMasatake YAMATO 
222593e14b6dSMasatake YAMATO 	if (tun)
222693e14b6dSMasatake YAMATO 		tun_put(tun);
222793e14b6dSMasatake YAMATO 
222893e14b6dSMasatake YAMATO 	return seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
222993e14b6dSMasatake YAMATO }
223093e14b6dSMasatake YAMATO #endif
223193e14b6dSMasatake YAMATO 
2232d54b1fdbSArjan van de Ven static const struct file_operations tun_fops = {
22331da177e4SLinus Torvalds 	.owner	= THIS_MODULE,
22341da177e4SLinus Torvalds 	.llseek = no_llseek,
2235ee0b3e67SBadari Pulavarty 	.read  = do_sync_read,
2236ee0b3e67SBadari Pulavarty 	.aio_read  = tun_chr_aio_read,
2237ee0b3e67SBadari Pulavarty 	.write = do_sync_write,
2238ee0b3e67SBadari Pulavarty 	.aio_write = tun_chr_aio_write,
22391da177e4SLinus Torvalds 	.poll	= tun_chr_poll,
2240876bfd4dSHerbert Xu 	.unlocked_ioctl	= tun_chr_ioctl,
224150857e2aSArnd Bergmann #ifdef CONFIG_COMPAT
224250857e2aSArnd Bergmann 	.compat_ioctl = tun_chr_compat_ioctl,
224350857e2aSArnd Bergmann #endif
22441da177e4SLinus Torvalds 	.open	= tun_chr_open,
22451da177e4SLinus Torvalds 	.release = tun_chr_close,
224693e14b6dSMasatake YAMATO 	.fasync = tun_chr_fasync,
224793e14b6dSMasatake YAMATO #ifdef CONFIG_PROC_FS
224893e14b6dSMasatake YAMATO 	.show_fdinfo = tun_chr_show_fdinfo,
224993e14b6dSMasatake YAMATO #endif
22501da177e4SLinus Torvalds };
22511da177e4SLinus Torvalds 
22521da177e4SLinus Torvalds static struct miscdevice tun_miscdev = {
22531da177e4SLinus Torvalds 	.minor = TUN_MINOR,
22541da177e4SLinus Torvalds 	.name = "tun",
2255e454cea2SKay Sievers 	.nodename = "net/tun",
22561da177e4SLinus Torvalds 	.fops = &tun_fops,
22571da177e4SLinus Torvalds };
22581da177e4SLinus Torvalds 
22591da177e4SLinus Torvalds /* ethtool interface */
22601da177e4SLinus Torvalds 
22611da177e4SLinus Torvalds static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
22621da177e4SLinus Torvalds {
22631da177e4SLinus Torvalds 	cmd->supported		= 0;
22641da177e4SLinus Torvalds 	cmd->advertising	= 0;
226570739497SDavid Decotigny 	ethtool_cmd_speed_set(cmd, SPEED_10);
22661da177e4SLinus Torvalds 	cmd->duplex		= DUPLEX_FULL;
22671da177e4SLinus Torvalds 	cmd->port		= PORT_TP;
22681da177e4SLinus Torvalds 	cmd->phy_address	= 0;
22691da177e4SLinus Torvalds 	cmd->transceiver	= XCVR_INTERNAL;
22701da177e4SLinus Torvalds 	cmd->autoneg		= AUTONEG_DISABLE;
22711da177e4SLinus Torvalds 	cmd->maxtxpkt		= 0;
22721da177e4SLinus Torvalds 	cmd->maxrxpkt		= 0;
22731da177e4SLinus Torvalds 	return 0;
22741da177e4SLinus Torvalds }
22751da177e4SLinus Torvalds 
22761da177e4SLinus Torvalds static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
22771da177e4SLinus Torvalds {
22781da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
22791da177e4SLinus Torvalds 
228033a5ba14SRick Jones 	strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
228133a5ba14SRick Jones 	strlcpy(info->version, DRV_VERSION, sizeof(info->version));
22821da177e4SLinus Torvalds 
22831da177e4SLinus Torvalds 	switch (tun->flags & TUN_TYPE_MASK) {
22841da177e4SLinus Torvalds 	case TUN_TUN_DEV:
228533a5ba14SRick Jones 		strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
22861da177e4SLinus Torvalds 		break;
22871da177e4SLinus Torvalds 	case TUN_TAP_DEV:
228833a5ba14SRick Jones 		strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
22891da177e4SLinus Torvalds 		break;
22901da177e4SLinus Torvalds 	}
22911da177e4SLinus Torvalds }
22921da177e4SLinus Torvalds 
22931da177e4SLinus Torvalds static u32 tun_get_msglevel(struct net_device *dev)
22941da177e4SLinus Torvalds {
22951da177e4SLinus Torvalds #ifdef TUN_DEBUG
22961da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
22971da177e4SLinus Torvalds 	return tun->debug;
22981da177e4SLinus Torvalds #else
22991da177e4SLinus Torvalds 	return -EOPNOTSUPP;
23001da177e4SLinus Torvalds #endif
23011da177e4SLinus Torvalds }
23021da177e4SLinus Torvalds 
23031da177e4SLinus Torvalds static void tun_set_msglevel(struct net_device *dev, u32 value)
23041da177e4SLinus Torvalds {
23051da177e4SLinus Torvalds #ifdef TUN_DEBUG
23061da177e4SLinus Torvalds 	struct tun_struct *tun = netdev_priv(dev);
23071da177e4SLinus Torvalds 	tun->debug = value;
23081da177e4SLinus Torvalds #endif
23091da177e4SLinus Torvalds }
23101da177e4SLinus Torvalds 
23117282d491SJeff Garzik static const struct ethtool_ops tun_ethtool_ops = {
23121da177e4SLinus Torvalds 	.get_settings	= tun_get_settings,
23131da177e4SLinus Torvalds 	.get_drvinfo	= tun_get_drvinfo,
23141da177e4SLinus Torvalds 	.get_msglevel	= tun_get_msglevel,
23151da177e4SLinus Torvalds 	.set_msglevel	= tun_set_msglevel,
2316bee31369SNolan Leake 	.get_link	= ethtool_op_get_link,
2317eda29772SRichard Cochran 	.get_ts_info	= ethtool_op_get_ts_info,
23181da177e4SLinus Torvalds };
23191da177e4SLinus Torvalds 
232079d17604SPavel Emelyanov 
23211da177e4SLinus Torvalds static int __init tun_init(void)
23221da177e4SLinus Torvalds {
23231da177e4SLinus Torvalds 	int ret = 0;
23241da177e4SLinus Torvalds 
23256b8a66eeSJoe Perches 	pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
23266b8a66eeSJoe Perches 	pr_info("%s\n", DRV_COPYRIGHT);
23271da177e4SLinus Torvalds 
2328f019a7a5SEric W. Biederman 	ret = rtnl_link_register(&tun_link_ops);
232979d17604SPavel Emelyanov 	if (ret) {
23306b8a66eeSJoe Perches 		pr_err("Can't register link_ops\n");
2331f019a7a5SEric W. Biederman 		goto err_linkops;
233279d17604SPavel Emelyanov 	}
233379d17604SPavel Emelyanov 
23341da177e4SLinus Torvalds 	ret = misc_register(&tun_miscdev);
233579d17604SPavel Emelyanov 	if (ret) {
23366b8a66eeSJoe Perches 		pr_err("Can't register misc device %d\n", TUN_MINOR);
233779d17604SPavel Emelyanov 		goto err_misc;
233879d17604SPavel Emelyanov 	}
233979d17604SPavel Emelyanov 	return  0;
234079d17604SPavel Emelyanov err_misc:
2341f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
2342f019a7a5SEric W. Biederman err_linkops:
23431da177e4SLinus Torvalds 	return ret;
23441da177e4SLinus Torvalds }
23451da177e4SLinus Torvalds 
23461da177e4SLinus Torvalds static void tun_cleanup(void)
23471da177e4SLinus Torvalds {
23481da177e4SLinus Torvalds 	misc_deregister(&tun_miscdev);
2349f019a7a5SEric W. Biederman 	rtnl_link_unregister(&tun_link_ops);
23501da177e4SLinus Torvalds }
23511da177e4SLinus Torvalds 
235205c2828cSMichael S. Tsirkin /* Get an underlying socket object from tun file.  Returns error unless file is
235305c2828cSMichael S. Tsirkin  * attached to a device.  The returned object works like a packet socket, it
235405c2828cSMichael S. Tsirkin  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
235505c2828cSMichael S. Tsirkin  * holding a reference to the file for as long as the socket is in use. */
235605c2828cSMichael S. Tsirkin struct socket *tun_get_socket(struct file *file)
235705c2828cSMichael S. Tsirkin {
23586e914fc7SJason Wang 	struct tun_file *tfile;
235905c2828cSMichael S. Tsirkin 	if (file->f_op != &tun_fops)
236005c2828cSMichael S. Tsirkin 		return ERR_PTR(-EINVAL);
23616e914fc7SJason Wang 	tfile = file->private_data;
23626e914fc7SJason Wang 	if (!tfile)
236305c2828cSMichael S. Tsirkin 		return ERR_PTR(-EBADFD);
236454f968d6SJason Wang 	return &tfile->socket;
236505c2828cSMichael S. Tsirkin }
236605c2828cSMichael S. Tsirkin EXPORT_SYMBOL_GPL(tun_get_socket);
236705c2828cSMichael S. Tsirkin 
23681da177e4SLinus Torvalds module_init(tun_init);
23691da177e4SLinus Torvalds module_exit(tun_cleanup);
23701da177e4SLinus Torvalds MODULE_DESCRIPTION(DRV_DESCRIPTION);
23711da177e4SLinus Torvalds MODULE_AUTHOR(DRV_COPYRIGHT);
23721da177e4SLinus Torvalds MODULE_LICENSE("GPL");
23731da177e4SLinus Torvalds MODULE_ALIAS_MISCDEV(TUN_MINOR);
2374578454ffSKay Sievers MODULE_ALIAS("devname:net/tun");
2375