2 * TUN - Universal TUN/TAP device driver.
3 * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
21 * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
22 * Add TUNSETLINK ioctl to set the link encapsulation
24 * Mark Smith <markzzzsmith@yahoo.com.au>
25 * Use eth_random_addr() for tap MAC address.
27 * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20
28 * Fixes in packet dropping, queue length setting and queue wakeup.
29 * Increased default tx queue length.
33 * Daniel Podlejski <underley@underley.eu.org>
34 * Modifications for 2.3.99-pre5 kernel.
37 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
39 #define DRV_NAME "tun"
40 #define DRV_VERSION "1.6"
41 #define DRV_DESCRIPTION "Universal TUN/TAP device driver"
42 #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
44 #include <linux/module.h>
45 #include <linux/errno.h>
46 #include <linux/kernel.h>
47 #include <linux/major.h>
48 #include <linux/slab.h>
49 #include <linux/poll.h>
50 #include <linux/fcntl.h>
51 #include <linux/init.h>
52 #include <linux/skbuff.h>
53 #include <linux/netdevice.h>
54 #include <linux/etherdevice.h>
55 #include <linux/miscdevice.h>
56 #include <linux/ethtool.h>
57 #include <linux/rtnetlink.h>
58 #include <linux/compat.h>
60 #include <linux/if_arp.h>
61 #include <linux/if_ether.h>
62 #include <linux/if_tun.h>
63 #include <linux/if_vlan.h>
64 #include <linux/crc32.h>
65 #include <linux/nsproxy.h>
66 #include <linux/virtio_net.h>
67 #include <linux/rcupdate.h>
69 #include <net/net_namespace.h>
70 #include <net/netns/generic.h>
71 #include <net/rtnetlink.h>
73 #include <linux/seq_file.h>
75 #include <asm/uaccess.h>
77 /* Uncomment to enable debugging */
78 /* #define TUN_DEBUG 1 */
83 #define tun_debug(level, tun, fmt, args...) \
86 netdev_printk(level, tun->dev, fmt, ##args); \
88 #define DBG1(level, fmt, args...) \
91 printk(level fmt, ##args); \
94 #define tun_debug(level, tun, fmt, args...) \
97 netdev_printk(level, tun->dev, fmt, ##args); \
99 #define DBG1(level, fmt, args...) \
102 printk(level fmt, ##args); \
106 /* TUN device flags */
108 /* IFF_ATTACH_QUEUE is never stored in device flags,
109 * overload it to mean fasync when stored there.
111 #define TUN_FASYNC IFF_ATTACH_QUEUE
113 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
114 IFF_VNET_LE | IFF_MULTI_QUEUE)
115 #define GOODCOPY_LEN 128
117 #define FLT_EXACT_COUNT 8
119 unsigned int count; /* Number of addrs. Zero means disabled */
120 u32 mask[2]; /* Mask of the hashed addrs */
121 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
124 /* DEFAULT_MAX_NUM_RSS_QUEUES were chosen to let the rx/tx queues allocated for
125 * the netdevice to be fit in one page. So we can make sure the success of
126 * memory allocation. TODO: increase the limit. */
127 #define MAX_TAP_QUEUES DEFAULT_MAX_NUM_RSS_QUEUES
128 #define MAX_TAP_FLOWS 4096
130 #define TUN_FLOW_EXPIRE (3 * HZ)
132 /* A tun_file connects an open character device to a tuntap netdevice. It
133 * also contains all socket related structures (except sock_fprog and tap_filter)
134 * to serve as one transmit queue for tuntap device. The sock_fprog and
135 * tap_filter were kept in tun_struct since they were used for filtering for the
136 * netdevice not for a specific queue (at least I didn't see the requirement for
140 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
141 * other can only be read while rcu_read_lock or rtnl_lock is held.
145 struct socket socket;
147 struct tun_struct __rcu *tun;
149 struct fasync_struct *fasync;
150 /* only used for fasnyc */
154 unsigned int ifindex;
156 struct list_head next;
157 struct tun_struct *detached;
160 struct tun_flow_entry {
161 struct hlist_node hash_link;
163 struct tun_struct *tun;
168 unsigned long updated;
171 #define TUN_NUM_FLOW_ENTRIES 1024
173 /* Since the socket were moved to tun_file, to preserve the behavior of persist
174 * device, socket filter, sndbuf and vnet header size were restore when the
175 * file were attached to a persist device.
178 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
179 unsigned int numqueues;
184 struct net_device *dev;
185 netdev_features_t set_features;
186 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
191 struct tap_filter txflt;
192 struct sock_fprog fprog;
193 /* protected by rtnl lock */
194 bool filter_attached;
199 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
200 struct timer_list flow_gc_timer;
201 unsigned long ageing_time;
202 unsigned int numdisabled;
203 struct list_head disabled;
208 static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
210 return __virtio16_to_cpu(tun->flags & IFF_VNET_LE, val);
213 static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
215 return __cpu_to_virtio16(tun->flags & IFF_VNET_LE, val);
218 static inline u32 tun_hashfn(u32 rxhash)
220 return rxhash & 0x3ff;
223 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
225 struct tun_flow_entry *e;
227 hlist_for_each_entry_rcu(e, head, hash_link) {
228 if (e->rxhash == rxhash)
234 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
235 struct hlist_head *head,
236 u32 rxhash, u16 queue_index)
238 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
241 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
242 rxhash, queue_index);
243 e->updated = jiffies;
246 e->queue_index = queue_index;
248 hlist_add_head_rcu(&e->hash_link, head);
254 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
256 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
257 e->rxhash, e->queue_index);
258 sock_rps_reset_flow_hash(e->rps_rxhash);
259 hlist_del_rcu(&e->hash_link);
264 static void tun_flow_flush(struct tun_struct *tun)
268 spin_lock_bh(&tun->lock);
269 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
270 struct tun_flow_entry *e;
271 struct hlist_node *n;
273 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
274 tun_flow_delete(tun, e);
276 spin_unlock_bh(&tun->lock);
279 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
283 spin_lock_bh(&tun->lock);
284 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
285 struct tun_flow_entry *e;
286 struct hlist_node *n;
288 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
289 if (e->queue_index == queue_index)
290 tun_flow_delete(tun, e);
293 spin_unlock_bh(&tun->lock);
296 static void tun_flow_cleanup(unsigned long data)
298 struct tun_struct *tun = (struct tun_struct *)data;
299 unsigned long delay = tun->ageing_time;
300 unsigned long next_timer = jiffies + delay;
301 unsigned long count = 0;
304 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
306 spin_lock_bh(&tun->lock);
307 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
308 struct tun_flow_entry *e;
309 struct hlist_node *n;
311 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
312 unsigned long this_timer;
314 this_timer = e->updated + delay;
315 if (time_before_eq(this_timer, jiffies))
316 tun_flow_delete(tun, e);
317 else if (time_before(this_timer, next_timer))
318 next_timer = this_timer;
323 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
324 spin_unlock_bh(&tun->lock);
327 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
328 struct tun_file *tfile)
330 struct hlist_head *head;
331 struct tun_flow_entry *e;
332 unsigned long delay = tun->ageing_time;
333 u16 queue_index = tfile->queue_index;
338 head = &tun->flows[tun_hashfn(rxhash)];
342 /* We may get a very small possibility of OOO during switching, not
343 * worth to optimize.*/
344 if (tun->numqueues == 1 || tfile->detached)
347 e = tun_flow_find(head, rxhash);
349 /* TODO: keep queueing to old queue until it's empty? */
350 e->queue_index = queue_index;
351 e->updated = jiffies;
352 sock_rps_record_flow_hash(e->rps_rxhash);
354 spin_lock_bh(&tun->lock);
355 if (!tun_flow_find(head, rxhash) &&
356 tun->flow_count < MAX_TAP_FLOWS)
357 tun_flow_create(tun, head, rxhash, queue_index);
359 if (!timer_pending(&tun->flow_gc_timer))
360 mod_timer(&tun->flow_gc_timer,
361 round_jiffies_up(jiffies + delay));
362 spin_unlock_bh(&tun->lock);
370 * Save the hash received in the stack receive path and update the
371 * flow_hash table accordingly.
373 static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
375 if (unlikely(e->rps_rxhash != hash)) {
376 sock_rps_reset_flow_hash(e->rps_rxhash);
377 e->rps_rxhash = hash;
381 /* We try to identify a flow through its rxhash first. The reason that
382 * we do not check rxq no. is because some cards(e.g 82599), chooses
383 * the rxq based on the txq where the last packet of the flow comes. As
384 * the userspace application move between processors, we may get a
385 * different rxq no. here. If we could not get rxhash, then we would
386 * hope the rxq no. may help here.
388 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
389 void *accel_priv, select_queue_fallback_t fallback)
391 struct tun_struct *tun = netdev_priv(dev);
392 struct tun_flow_entry *e;
397 numqueues = ACCESS_ONCE(tun->numqueues);
399 txq = skb_get_hash(skb);
401 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
403 tun_flow_save_rps_rxhash(e, txq);
404 txq = e->queue_index;
406 /* use multiply and shift instead of expensive divide */
407 txq = ((u64)txq * numqueues) >> 32;
408 } else if (likely(skb_rx_queue_recorded(skb))) {
409 txq = skb_get_rx_queue(skb);
410 while (unlikely(txq >= numqueues))
418 static inline bool tun_not_capable(struct tun_struct *tun)
420 const struct cred *cred = current_cred();
421 struct net *net = dev_net(tun->dev);
423 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
424 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
425 !ns_capable(net->user_ns, CAP_NET_ADMIN);
428 static void tun_set_real_num_queues(struct tun_struct *tun)
430 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
431 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
434 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
436 tfile->detached = tun;
437 list_add_tail(&tfile->next, &tun->disabled);
441 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
443 struct tun_struct *tun = tfile->detached;
445 tfile->detached = NULL;
446 list_del_init(&tfile->next);
451 static void tun_queue_purge(struct tun_file *tfile)
453 skb_queue_purge(&tfile->sk.sk_receive_queue);
454 skb_queue_purge(&tfile->sk.sk_error_queue);
457 static void __tun_detach(struct tun_file *tfile, bool clean)
459 struct tun_file *ntfile;
460 struct tun_struct *tun;
462 tun = rtnl_dereference(tfile->tun);
464 if (tun && !tfile->detached) {
465 u16 index = tfile->queue_index;
466 BUG_ON(index >= tun->numqueues);
468 rcu_assign_pointer(tun->tfiles[index],
469 tun->tfiles[tun->numqueues - 1]);
470 ntfile = rtnl_dereference(tun->tfiles[index]);
471 ntfile->queue_index = index;
475 RCU_INIT_POINTER(tfile->tun, NULL);
476 sock_put(&tfile->sk);
478 tun_disable_queue(tun, tfile);
481 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
482 /* Drop read queue */
483 tun_queue_purge(tfile);
484 tun_set_real_num_queues(tun);
485 } else if (tfile->detached && clean) {
486 tun = tun_enable_queue(tfile);
487 sock_put(&tfile->sk);
491 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
492 netif_carrier_off(tun->dev);
494 if (!(tun->flags & IFF_PERSIST) &&
495 tun->dev->reg_state == NETREG_REGISTERED)
496 unregister_netdevice(tun->dev);
499 BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
500 &tfile->socket.flags));
501 sk_release_kernel(&tfile->sk);
505 static void tun_detach(struct tun_file *tfile, bool clean)
508 __tun_detach(tfile, clean);
512 static void tun_detach_all(struct net_device *dev)
514 struct tun_struct *tun = netdev_priv(dev);
515 struct tun_file *tfile, *tmp;
516 int i, n = tun->numqueues;
518 for (i = 0; i < n; i++) {
519 tfile = rtnl_dereference(tun->tfiles[i]);
521 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
522 RCU_INIT_POINTER(tfile->tun, NULL);
525 list_for_each_entry(tfile, &tun->disabled, next) {
526 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
527 RCU_INIT_POINTER(tfile->tun, NULL);
529 BUG_ON(tun->numqueues != 0);
532 for (i = 0; i < n; i++) {
533 tfile = rtnl_dereference(tun->tfiles[i]);
534 /* Drop read queue */
535 tun_queue_purge(tfile);
536 sock_put(&tfile->sk);
538 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
539 tun_enable_queue(tfile);
540 tun_queue_purge(tfile);
541 sock_put(&tfile->sk);
543 BUG_ON(tun->numdisabled != 0);
545 if (tun->flags & IFF_PERSIST)
546 module_put(THIS_MODULE);
549 static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter)
551 struct tun_file *tfile = file->private_data;
554 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
559 if (rtnl_dereference(tfile->tun) && !tfile->detached)
563 if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
567 if (!tfile->detached &&
568 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
573 /* Re-attach the filter to persist device */
574 if (!skip_filter && (tun->filter_attached == true)) {
575 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
579 tfile->queue_index = tun->numqueues;
580 rcu_assign_pointer(tfile->tun, tun);
581 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
585 tun_enable_queue(tfile);
587 sock_hold(&tfile->sk);
589 tun_set_real_num_queues(tun);
591 /* device is allowed to go away first, so no need to hold extra
599 static struct tun_struct *__tun_get(struct tun_file *tfile)
601 struct tun_struct *tun;
604 tun = rcu_dereference(tfile->tun);
612 static struct tun_struct *tun_get(struct file *file)
614 return __tun_get(file->private_data);
617 static void tun_put(struct tun_struct *tun)
623 static void addr_hash_set(u32 *mask, const u8 *addr)
625 int n = ether_crc(ETH_ALEN, addr) >> 26;
626 mask[n >> 5] |= (1 << (n & 31));
629 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
631 int n = ether_crc(ETH_ALEN, addr) >> 26;
632 return mask[n >> 5] & (1 << (n & 31));
635 static int update_filter(struct tap_filter *filter, void __user *arg)
637 struct { u8 u[ETH_ALEN]; } *addr;
638 struct tun_filter uf;
639 int err, alen, n, nexact;
641 if (copy_from_user(&uf, arg, sizeof(uf)))
650 alen = ETH_ALEN * uf.count;
651 addr = kmalloc(alen, GFP_KERNEL);
655 if (copy_from_user(addr, arg + sizeof(uf), alen)) {
660 /* The filter is updated without holding any locks. Which is
661 * perfectly safe. We disable it first and in the worst
662 * case we'll accept a few undesired packets. */
666 /* Use first set of addresses as an exact filter */
667 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
668 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
672 /* Remaining multicast addresses are hashed,
673 * unicast will leave the filter disabled. */
674 memset(filter->mask, 0, sizeof(filter->mask));
675 for (; n < uf.count; n++) {
676 if (!is_multicast_ether_addr(addr[n].u)) {
677 err = 0; /* no filter */
680 addr_hash_set(filter->mask, addr[n].u);
683 /* For ALLMULTI just set the mask to all ones.
684 * This overrides the mask populated above. */
685 if ((uf.flags & TUN_FLT_ALLMULTI))
686 memset(filter->mask, ~0, sizeof(filter->mask));
688 /* Now enable the filter */
690 filter->count = nexact;
692 /* Return the number of exact filters */
700 /* Returns: 0 - drop, !=0 - accept */
701 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
703 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
705 struct ethhdr *eh = (struct ethhdr *) skb->data;
709 for (i = 0; i < filter->count; i++)
710 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
713 /* Inexact match (multicast only) */
714 if (is_multicast_ether_addr(eh->h_dest))
715 return addr_hash_test(filter->mask, eh->h_dest);
721 * Checks whether the packet is accepted or not.
722 * Returns: 0 - drop, !=0 - accept
724 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
729 return run_filter(filter, skb);
732 /* Network device part of the driver */
734 static const struct ethtool_ops tun_ethtool_ops;
736 /* Net device detach from fd. */
737 static void tun_net_uninit(struct net_device *dev)
742 /* Net device open. */
743 static int tun_net_open(struct net_device *dev)
745 netif_tx_start_all_queues(dev);
749 /* Net device close. */
750 static int tun_net_close(struct net_device *dev)
752 netif_tx_stop_all_queues(dev);
756 /* Net device start xmit */
757 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
759 struct tun_struct *tun = netdev_priv(dev);
760 int txq = skb->queue_mapping;
761 struct tun_file *tfile;
765 tfile = rcu_dereference(tun->tfiles[txq]);
766 numqueues = ACCESS_ONCE(tun->numqueues);
768 /* Drop packet if interface is not attached */
769 if (txq >= numqueues)
772 if (numqueues == 1) {
773 /* Select queue was not called for the skbuff, so we extract the
774 * RPS hash and save it into the flow_table here.
778 rxhash = skb_get_hash(skb);
780 struct tun_flow_entry *e;
781 e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
784 tun_flow_save_rps_rxhash(e, rxhash);
788 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
792 /* Drop if the filter does not like it.
793 * This is a noop if the filter is disabled.
794 * Filter can be enabled only for the TAP devices. */
795 if (!check_filter(&tun->txflt, skb))
798 if (tfile->socket.sk->sk_filter &&
799 sk_filter(tfile->socket.sk, skb))
802 /* Limit the number of packets queued by dividing txq length with the
805 if (skb_queue_len(&tfile->socket.sk->sk_receive_queue) * numqueues
806 >= dev->tx_queue_len)
809 if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
813 sock_tx_timestamp(skb->sk, &skb_shinfo(skb)->tx_flags);
814 sw_tx_timestamp(skb);
817 /* Orphan the skb - required as we might hang on to it
818 * for indefinite time.
825 skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
827 /* Notify and wake up reader process */
828 if (tfile->flags & TUN_FASYNC)
829 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
830 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
836 dev->stats.tx_dropped++;
843 static void tun_net_mclist(struct net_device *dev)
846 * This callback is supposed to deal with mc filter in
847 * _rx_ path and has nothing to do with the _tx_ path.
848 * In rx path we always accept everything userspace gives us.
853 #define MAX_MTU 65535
856 tun_net_change_mtu(struct net_device *dev, int new_mtu)
858 if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
864 static netdev_features_t tun_net_fix_features(struct net_device *dev,
865 netdev_features_t features)
867 struct tun_struct *tun = netdev_priv(dev);
869 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
871 #ifdef CONFIG_NET_POLL_CONTROLLER
872 static void tun_poll_controller(struct net_device *dev)
875 * Tun only receives frames when:
876 * 1) the char device endpoint gets data from user space
877 * 2) the tun socket gets a sendmsg call from user space
878 * Since both of those are synchronous operations, we are guaranteed
879 * never to have pending data when we poll for it
880 * so there is nothing to do here but return.
881 * We need this though so netpoll recognizes us as an interface that
882 * supports polling, which enables bridge devices in virt setups to
883 * still use netconsole
888 static const struct net_device_ops tun_netdev_ops = {
889 .ndo_uninit = tun_net_uninit,
890 .ndo_open = tun_net_open,
891 .ndo_stop = tun_net_close,
892 .ndo_start_xmit = tun_net_xmit,
893 .ndo_change_mtu = tun_net_change_mtu,
894 .ndo_fix_features = tun_net_fix_features,
895 .ndo_select_queue = tun_select_queue,
896 #ifdef CONFIG_NET_POLL_CONTROLLER
897 .ndo_poll_controller = tun_poll_controller,
901 static const struct net_device_ops tap_netdev_ops = {
902 .ndo_uninit = tun_net_uninit,
903 .ndo_open = tun_net_open,
904 .ndo_stop = tun_net_close,
905 .ndo_start_xmit = tun_net_xmit,
906 .ndo_change_mtu = tun_net_change_mtu,
907 .ndo_fix_features = tun_net_fix_features,
908 .ndo_set_rx_mode = tun_net_mclist,
909 .ndo_set_mac_address = eth_mac_addr,
910 .ndo_validate_addr = eth_validate_addr,
911 .ndo_select_queue = tun_select_queue,
912 #ifdef CONFIG_NET_POLL_CONTROLLER
913 .ndo_poll_controller = tun_poll_controller,
917 static void tun_flow_init(struct tun_struct *tun)
921 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
922 INIT_HLIST_HEAD(&tun->flows[i]);
924 tun->ageing_time = TUN_FLOW_EXPIRE;
925 setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
926 mod_timer(&tun->flow_gc_timer,
927 round_jiffies_up(jiffies + tun->ageing_time));
930 static void tun_flow_uninit(struct tun_struct *tun)
932 del_timer_sync(&tun->flow_gc_timer);
936 /* Initialize net device. */
937 static void tun_net_init(struct net_device *dev)
939 struct tun_struct *tun = netdev_priv(dev);
941 switch (tun->flags & TUN_TYPE_MASK) {
943 dev->netdev_ops = &tun_netdev_ops;
945 /* Point-to-Point TUN Device */
946 dev->hard_header_len = 0;
950 /* Zero header length */
951 dev->type = ARPHRD_NONE;
952 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
953 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
957 dev->netdev_ops = &tap_netdev_ops;
958 /* Ethernet TAP Device */
960 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
961 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
963 eth_hw_addr_random(dev);
965 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
970 /* Character device part */
973 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
975 struct tun_file *tfile = file->private_data;
976 struct tun_struct *tun = __tun_get(tfile);
978 unsigned int mask = 0;
983 sk = tfile->socket.sk;
985 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
987 poll_wait(file, sk_sleep(sk), wait);
989 if (!skb_queue_empty(&sk->sk_receive_queue))
990 mask |= POLLIN | POLLRDNORM;
992 if (sock_writeable(sk) ||
993 (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
995 mask |= POLLOUT | POLLWRNORM;
997 if (tun->dev->reg_state != NETREG_REGISTERED)
1004 /* prepad is the amount to reserve at front. len is length after that.
1005 * linear is a hint as to how much to copy (usually headers). */
1006 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
1007 size_t prepad, size_t len,
1008 size_t linear, int noblock)
1010 struct sock *sk = tfile->socket.sk;
1011 struct sk_buff *skb;
1014 /* Under a page? Don't bother with paged skb. */
1015 if (prepad + len < PAGE_SIZE || !linear)
1018 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
1021 return ERR_PTR(err);
1023 skb_reserve(skb, prepad);
1024 skb_put(skb, linear);
1025 skb->data_len = len - linear;
1026 skb->len += len - linear;
1031 /* Get packet from user space buffer */
1032 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1033 void *msg_control, const struct iovec *iv,
1034 size_t total_len, size_t count, int noblock)
1036 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1037 struct sk_buff *skb;
1038 size_t len = total_len, align = NET_SKB_PAD, linear;
1039 struct virtio_net_hdr gso = { 0 };
1043 bool zerocopy = false;
1047 if (!(tun->flags & IFF_NO_PI)) {
1048 if (len < sizeof(pi))
1052 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
1054 offset += sizeof(pi);
1057 if (tun->flags & IFF_VNET_HDR) {
1058 if (len < tun->vnet_hdr_sz)
1060 len -= tun->vnet_hdr_sz;
1062 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
1065 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1066 tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
1067 gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
1069 if (tun16_to_cpu(tun, gso.hdr_len) > len)
1071 offset += tun->vnet_hdr_sz;
1074 if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1075 align += NET_IP_ALIGN;
1076 if (unlikely(len < ETH_HLEN ||
1077 (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1081 good_linear = SKB_MAX_HEAD(align);
1084 /* There are 256 bytes to be copied in skb, so there is
1085 * enough room for skb expand head in case it is used.
1086 * The rest of the buffer is mapped from userspace.
1088 copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
1089 if (copylen > good_linear)
1090 copylen = good_linear;
1092 if (iov_pages(iv, offset + copylen, count) <= MAX_SKB_FRAGS)
1098 if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
1099 linear = good_linear;
1101 linear = tun16_to_cpu(tun, gso.hdr_len);
1104 skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
1106 if (PTR_ERR(skb) != -EAGAIN)
1107 tun->dev->stats.rx_dropped++;
1108 return PTR_ERR(skb);
1112 err = zerocopy_sg_from_iovec(skb, iv, offset, count);
1114 err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
1115 if (!err && msg_control) {
1116 struct ubuf_info *uarg = msg_control;
1117 uarg->callback(uarg, false);
1122 tun->dev->stats.rx_dropped++;
1127 if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1128 if (!skb_partial_csum_set(skb, tun16_to_cpu(tun, gso.csum_start),
1129 tun16_to_cpu(tun, gso.csum_offset))) {
1130 tun->dev->stats.rx_frame_errors++;
1136 switch (tun->flags & TUN_TYPE_MASK) {
1138 if (tun->flags & IFF_NO_PI) {
1139 switch (skb->data[0] & 0xf0) {
1141 pi.proto = htons(ETH_P_IP);
1144 pi.proto = htons(ETH_P_IPV6);
1147 tun->dev->stats.rx_dropped++;
1153 skb_reset_mac_header(skb);
1154 skb->protocol = pi.proto;
1155 skb->dev = tun->dev;
1158 skb->protocol = eth_type_trans(skb, tun->dev);
1162 skb_reset_network_header(skb);
1164 if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1166 switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1167 case VIRTIO_NET_HDR_GSO_TCPV4:
1168 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1170 case VIRTIO_NET_HDR_GSO_TCPV6:
1171 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1173 case VIRTIO_NET_HDR_GSO_UDP:
1179 netdev_warn(tun->dev,
1180 "%s: using disabled UFO feature; please fix this program\n",
1183 skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
1184 if (skb->protocol == htons(ETH_P_IPV6))
1185 ipv6_proxy_select_ident(skb);
1189 tun->dev->stats.rx_frame_errors++;
1194 if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1195 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
1197 skb_shinfo(skb)->gso_size = tun16_to_cpu(tun, gso.gso_size);
1198 if (skb_shinfo(skb)->gso_size == 0) {
1199 tun->dev->stats.rx_frame_errors++;
1204 /* Header must be checked, and gso_segs computed. */
1205 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1206 skb_shinfo(skb)->gso_segs = 0;
1209 /* copy skb_ubuf_info for callback when skb has no error */
1211 skb_shinfo(skb)->destructor_arg = msg_control;
1212 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1213 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1216 skb_probe_transport_header(skb, 0);
1218 rxhash = skb_get_hash(skb);
1221 tun->dev->stats.rx_packets++;
1222 tun->dev->stats.rx_bytes += len;
1224 tun_flow_update(tun, rxhash, tfile);
1228 static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
1229 unsigned long count, loff_t pos)
1231 struct file *file = iocb->ki_filp;
1232 struct tun_struct *tun = tun_get(file);
1233 struct tun_file *tfile = file->private_data;
1239 tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
1241 result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
1242 count, file->f_flags & O_NONBLOCK);
1248 /* Put packet to the user space buffer */
1249 static ssize_t tun_put_user(struct tun_struct *tun,
1250 struct tun_file *tfile,
1251 struct sk_buff *skb,
1252 const struct iovec *iv, int len)
1254 struct tun_pi pi = { 0, skb->protocol };
1256 int vlan_offset = 0, copied;
1258 int vnet_hdr_sz = 0;
1260 if (vlan_tx_tag_present(skb))
1261 vlan_hlen = VLAN_HLEN;
1263 if (tun->flags & IFF_VNET_HDR)
1264 vnet_hdr_sz = tun->vnet_hdr_sz;
1266 if (!(tun->flags & IFF_NO_PI)) {
1267 if ((len -= sizeof(pi)) < 0)
1270 if (len < skb->len + vlan_hlen + vnet_hdr_sz) {
1271 /* Packet will be striped */
1272 pi.flags |= TUN_PKT_STRIP;
1275 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
1277 total += sizeof(pi);
1281 struct virtio_net_hdr gso = { 0 }; /* no info leak */
1282 if ((len -= vnet_hdr_sz) < 0)
1285 if (skb_is_gso(skb)) {
1286 struct skb_shared_info *sinfo = skb_shinfo(skb);
1288 /* This is a hint as to how much should be linear. */
1289 gso.hdr_len = cpu_to_tun16(tun, skb_headlen(skb));
1290 gso.gso_size = cpu_to_tun16(tun, sinfo->gso_size);
1291 if (sinfo->gso_type & SKB_GSO_TCPV4)
1292 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1293 else if (sinfo->gso_type & SKB_GSO_TCPV6)
1294 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1296 pr_err("unexpected GSO type: "
1297 "0x%x, gso_size %d, hdr_len %d\n",
1298 sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
1299 tun16_to_cpu(tun, gso.hdr_len));
1300 print_hex_dump(KERN_ERR, "tun: ",
1303 min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
1307 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1308 gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1310 gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1312 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1313 gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
1314 gso.csum_start = cpu_to_tun16(tun, skb_checksum_start_offset(skb) +
1316 gso.csum_offset = cpu_to_tun16(tun, skb->csum_offset);
1317 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
1318 gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1319 } /* else everything is zero */
1321 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
1324 total += vnet_hdr_sz;
1328 len = min_t(int, skb->len + vlan_hlen, len);
1329 total += skb->len + vlan_hlen;
1333 __be16 h_vlan_proto;
1337 veth.h_vlan_proto = skb->vlan_proto;
1338 veth.h_vlan_TCI = htons(vlan_tx_tag_get(skb));
1340 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
1342 copy = min_t(int, vlan_offset, len);
1343 ret = skb_copy_datagram_const_iovec(skb, 0, iv, copied, copy);
1349 copy = min_t(int, sizeof(veth), len);
1350 ret = memcpy_toiovecend(iv, (void *)&veth, copied, copy);
1357 skb_copy_datagram_const_iovec(skb, vlan_offset, iv, copied, len);
1360 tun->dev->stats.tx_packets++;
1361 tun->dev->stats.tx_bytes += len;
1366 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1367 const struct iovec *iv, ssize_t len, int noblock)
1369 struct sk_buff *skb;
1371 int peeked, err, off = 0;
1373 tun_debug(KERN_INFO, tun, "tun_do_read\n");
1378 if (tun->dev->reg_state != NETREG_REGISTERED)
1381 /* Read frames from queue */
1382 skb = __skb_recv_datagram(tfile->socket.sk, noblock ? MSG_DONTWAIT : 0,
1383 &peeked, &off, &err);
1385 ret = tun_put_user(tun, tfile, skb, iv, len);
1393 static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
1394 unsigned long count, loff_t pos)
1396 struct file *file = iocb->ki_filp;
1397 struct tun_file *tfile = file->private_data;
1398 struct tun_struct *tun = __tun_get(tfile);
1403 len = iov_length(iv, count);
1409 ret = tun_do_read(tun, tfile, iv, len,
1410 file->f_flags & O_NONBLOCK);
1411 ret = min_t(ssize_t, ret, len);
1419 static void tun_free_netdev(struct net_device *dev)
1421 struct tun_struct *tun = netdev_priv(dev);
1423 BUG_ON(!(list_empty(&tun->disabled)));
1424 tun_flow_uninit(tun);
1425 security_tun_dev_free_security(tun->security);
1429 static void tun_setup(struct net_device *dev)
1431 struct tun_struct *tun = netdev_priv(dev);
1433 tun->owner = INVALID_UID;
1434 tun->group = INVALID_GID;
1436 dev->ethtool_ops = &tun_ethtool_ops;
1437 dev->destructor = tun_free_netdev;
1440 /* Trivial set of netlink ops to allow deleting tun or tap
1441 * device with netlink.
1443 static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1448 static struct rtnl_link_ops tun_link_ops __read_mostly = {
1450 .priv_size = sizeof(struct tun_struct),
1452 .validate = tun_validate,
1455 static void tun_sock_write_space(struct sock *sk)
1457 struct tun_file *tfile;
1458 wait_queue_head_t *wqueue;
1460 if (!sock_writeable(sk))
1463 if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1466 wqueue = sk_sleep(sk);
1467 if (wqueue && waitqueue_active(wqueue))
1468 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1469 POLLWRNORM | POLLWRBAND);
1471 tfile = container_of(sk, struct tun_file, sk);
1472 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1475 static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1476 struct msghdr *m, size_t total_len)
1479 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1480 struct tun_struct *tun = __tun_get(tfile);
1484 ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
1485 m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
1490 static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1491 struct msghdr *m, size_t total_len,
1494 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1495 struct tun_struct *tun = __tun_get(tfile);
1501 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
1505 if (flags & MSG_ERRQUEUE) {
1506 ret = sock_recv_errqueue(sock->sk, m, total_len,
1507 SOL_PACKET, TUN_TX_TIMESTAMP);
1510 ret = tun_do_read(tun, tfile, m->msg_iov, total_len,
1511 flags & MSG_DONTWAIT);
1512 if (ret > total_len) {
1513 m->msg_flags |= MSG_TRUNC;
1514 ret = flags & MSG_TRUNC ? ret : total_len;
1521 static int tun_release(struct socket *sock)
1528 /* Ops structure to mimic raw sockets with tun */
1529 static const struct proto_ops tun_socket_ops = {
1530 .sendmsg = tun_sendmsg,
1531 .recvmsg = tun_recvmsg,
1532 .release = tun_release,
1535 static struct proto tun_proto = {
1537 .owner = THIS_MODULE,
1538 .obj_size = sizeof(struct tun_file),
1541 static int tun_flags(struct tun_struct *tun)
1543 return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
1546 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1549 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1550 return sprintf(buf, "0x%x\n", tun_flags(tun));
1553 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1556 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1557 return uid_valid(tun->owner)?
1558 sprintf(buf, "%u\n",
1559 from_kuid_munged(current_user_ns(), tun->owner)):
1560 sprintf(buf, "-1\n");
1563 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1566 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1567 return gid_valid(tun->group) ?
1568 sprintf(buf, "%u\n",
1569 from_kgid_munged(current_user_ns(), tun->group)):
1570 sprintf(buf, "-1\n");
1573 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1574 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1575 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1577 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1579 struct tun_struct *tun;
1580 struct tun_file *tfile = file->private_data;
1581 struct net_device *dev;
1584 if (tfile->detached)
1587 dev = __dev_get_by_name(net, ifr->ifr_name);
1589 if (ifr->ifr_flags & IFF_TUN_EXCL)
1591 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
1592 tun = netdev_priv(dev);
1593 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
1594 tun = netdev_priv(dev);
1598 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
1599 !!(tun->flags & IFF_MULTI_QUEUE))
1602 if (tun_not_capable(tun))
1604 err = security_tun_dev_open(tun->security);
1608 err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
1612 if (tun->flags & IFF_MULTI_QUEUE &&
1613 (tun->numqueues + tun->numdisabled > 1)) {
1614 /* One or more queue has already been attached, no need
1615 * to initialize the device again.
1622 unsigned long flags = 0;
1623 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1626 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1628 err = security_tun_dev_create();
1633 if (ifr->ifr_flags & IFF_TUN) {
1637 } else if (ifr->ifr_flags & IFF_TAP) {
1645 name = ifr->ifr_name;
1647 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1648 NET_NAME_UNKNOWN, tun_setup, queues,
1654 dev_net_set(dev, net);
1655 dev->rtnl_link_ops = &tun_link_ops;
1656 dev->ifindex = tfile->ifindex;
1658 tun = netdev_priv(dev);
1661 tun->txflt.count = 0;
1662 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
1664 tun->filter_attached = false;
1665 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
1667 spin_lock_init(&tun->lock);
1669 err = security_tun_dev_alloc_security(&tun->security);
1676 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1677 TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
1678 NETIF_F_HW_VLAN_STAG_TX;
1679 dev->features = dev->hw_features;
1680 dev->vlan_features = dev->features &
1681 ~(NETIF_F_HW_VLAN_CTAG_TX |
1682 NETIF_F_HW_VLAN_STAG_TX);
1684 INIT_LIST_HEAD(&tun->disabled);
1685 err = tun_attach(tun, file, false);
1689 err = register_netdevice(tun->dev);
1693 if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1694 device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1695 device_create_file(&tun->dev->dev, &dev_attr_group))
1696 pr_err("Failed to create tun sysfs files\n");
1699 netif_carrier_on(tun->dev);
1701 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1703 tun->flags = (tun->flags & ~TUN_FEATURES) |
1704 (ifr->ifr_flags & TUN_FEATURES);
1706 /* Make sure persistent devices do not get stuck in
1709 if (netif_running(tun->dev))
1710 netif_tx_wake_all_queues(tun->dev);
1712 strcpy(ifr->ifr_name, tun->dev->name);
1716 tun_detach_all(dev);
1718 tun_flow_uninit(tun);
1719 security_tun_dev_free_security(tun->security);
1725 static void tun_get_iff(struct net *net, struct tun_struct *tun,
1728 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1730 strcpy(ifr->ifr_name, tun->dev->name);
1732 ifr->ifr_flags = tun_flags(tun);
1736 /* This is like a cut-down ethtool ops, except done via tun fd so no
1737 * privs required. */
1738 static int set_offload(struct tun_struct *tun, unsigned long arg)
1740 netdev_features_t features = 0;
1742 if (arg & TUN_F_CSUM) {
1743 features |= NETIF_F_HW_CSUM;
1746 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
1747 if (arg & TUN_F_TSO_ECN) {
1748 features |= NETIF_F_TSO_ECN;
1749 arg &= ~TUN_F_TSO_ECN;
1751 if (arg & TUN_F_TSO4)
1752 features |= NETIF_F_TSO;
1753 if (arg & TUN_F_TSO6)
1754 features |= NETIF_F_TSO6;
1755 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
1759 /* This gives the user a way to test for new features in future by
1760 * trying to set them. */
1764 tun->set_features = features;
1765 netdev_update_features(tun->dev);
1770 static void tun_detach_filter(struct tun_struct *tun, int n)
1773 struct tun_file *tfile;
1775 for (i = 0; i < n; i++) {
1776 tfile = rtnl_dereference(tun->tfiles[i]);
1777 sk_detach_filter(tfile->socket.sk);
1780 tun->filter_attached = false;
1783 static int tun_attach_filter(struct tun_struct *tun)
1786 struct tun_file *tfile;
1788 for (i = 0; i < tun->numqueues; i++) {
1789 tfile = rtnl_dereference(tun->tfiles[i]);
1790 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1792 tun_detach_filter(tun, i);
1797 tun->filter_attached = true;
1801 static void tun_set_sndbuf(struct tun_struct *tun)
1803 struct tun_file *tfile;
1806 for (i = 0; i < tun->numqueues; i++) {
1807 tfile = rtnl_dereference(tun->tfiles[i]);
1808 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1812 static int tun_set_queue(struct file *file, struct ifreq *ifr)
1814 struct tun_file *tfile = file->private_data;
1815 struct tun_struct *tun;
1820 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
1821 tun = tfile->detached;
1826 ret = security_tun_dev_attach_queue(tun->security);
1829 ret = tun_attach(tun, file, false);
1830 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
1831 tun = rtnl_dereference(tfile->tun);
1832 if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
1835 __tun_detach(tfile, false);
1844 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
1845 unsigned long arg, int ifreq_len)
1847 struct tun_file *tfile = file->private_data;
1848 struct tun_struct *tun;
1849 void __user* argp = (void __user*)arg;
1855 unsigned int ifindex;
1858 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
1859 if (copy_from_user(&ifr, argp, ifreq_len))
1862 memset(&ifr, 0, sizeof(ifr));
1864 if (cmd == TUNGETFEATURES) {
1865 /* Currently this just means: "what IFF flags are valid?".
1866 * This is needed because we never checked for invalid flags on
1869 return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
1870 (unsigned int __user*)argp);
1871 } else if (cmd == TUNSETQUEUE)
1872 return tun_set_queue(file, &ifr);
1877 tun = __tun_get(tfile);
1878 if (cmd == TUNSETIFF && !tun) {
1879 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1881 ret = tun_set_iff(tfile->net, file, &ifr);
1886 if (copy_to_user(argp, &ifr, ifreq_len))
1890 if (cmd == TUNSETIFINDEX) {
1896 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
1900 tfile->ifindex = ifindex;
1908 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1913 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1915 if (tfile->detached)
1916 ifr.ifr_flags |= IFF_DETACH_QUEUE;
1917 if (!tfile->socket.sk->sk_filter)
1918 ifr.ifr_flags |= IFF_NOFILTER;
1920 if (copy_to_user(argp, &ifr, ifreq_len))
1925 /* Disable/Enable checksum */
1927 /* [unimplemented] */
1928 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
1929 arg ? "disabled" : "enabled");
1933 /* Disable/Enable persist mode. Keep an extra reference to the
1934 * module to prevent the module being unprobed.
1936 if (arg && !(tun->flags & IFF_PERSIST)) {
1937 tun->flags |= IFF_PERSIST;
1938 __module_get(THIS_MODULE);
1940 if (!arg && (tun->flags & IFF_PERSIST)) {
1941 tun->flags &= ~IFF_PERSIST;
1942 module_put(THIS_MODULE);
1945 tun_debug(KERN_INFO, tun, "persist %s\n",
1946 arg ? "enabled" : "disabled");
1950 /* Set owner of the device */
1951 owner = make_kuid(current_user_ns(), arg);
1952 if (!uid_valid(owner)) {
1957 tun_debug(KERN_INFO, tun, "owner set to %u\n",
1958 from_kuid(&init_user_ns, tun->owner));
1962 /* Set group of the device */
1963 group = make_kgid(current_user_ns(), arg);
1964 if (!gid_valid(group)) {
1969 tun_debug(KERN_INFO, tun, "group set to %u\n",
1970 from_kgid(&init_user_ns, tun->group));
1974 /* Only allow setting the type when the interface is down */
1975 if (tun->dev->flags & IFF_UP) {
1976 tun_debug(KERN_INFO, tun,
1977 "Linktype set failed because interface is up\n");
1980 tun->dev->type = (int) arg;
1981 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
1993 ret = set_offload(tun, arg);
1996 case TUNSETTXFILTER:
1997 /* Can be set only for TAPs */
1999 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2001 ret = update_filter(&tun->txflt, (void __user *)arg);
2005 /* Get hw address */
2006 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2007 ifr.ifr_hwaddr.sa_family = tun->dev->type;
2008 if (copy_to_user(argp, &ifr, ifreq_len))
2013 /* Set hw address */
2014 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
2015 ifr.ifr_hwaddr.sa_data);
2017 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2021 sndbuf = tfile->socket.sk->sk_sndbuf;
2022 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
2027 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
2032 tun->sndbuf = sndbuf;
2033 tun_set_sndbuf(tun);
2036 case TUNGETVNETHDRSZ:
2037 vnet_hdr_sz = tun->vnet_hdr_sz;
2038 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2042 case TUNSETVNETHDRSZ:
2043 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2047 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2052 tun->vnet_hdr_sz = vnet_hdr_sz;
2055 case TUNATTACHFILTER:
2056 /* Can be set only for TAPs */
2058 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2061 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
2064 ret = tun_attach_filter(tun);
2067 case TUNDETACHFILTER:
2068 /* Can be set only for TAPs */
2070 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2073 tun_detach_filter(tun, tun->numqueues);
2078 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
2081 if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
2098 static long tun_chr_ioctl(struct file *file,
2099 unsigned int cmd, unsigned long arg)
2101 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2104 #ifdef CONFIG_COMPAT
2105 static long tun_chr_compat_ioctl(struct file *file,
2106 unsigned int cmd, unsigned long arg)
2111 case TUNSETTXFILTER:
2116 arg = (unsigned long)compat_ptr(arg);
2119 arg = (compat_ulong_t)arg;
2124 * compat_ifreq is shorter than ifreq, so we must not access beyond
2125 * the end of that structure. All fields that are used in this
2126 * driver are compatible though, we don't need to convert the
2129 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2131 #endif /* CONFIG_COMPAT */
2133 static int tun_chr_fasync(int fd, struct file *file, int on)
2135 struct tun_file *tfile = file->private_data;
2138 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
2142 __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
2143 tfile->flags |= TUN_FASYNC;
2145 tfile->flags &= ~TUN_FASYNC;
2151 static int tun_chr_open(struct inode *inode, struct file * file)
2153 struct tun_file *tfile;
2155 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2157 tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
2161 RCU_INIT_POINTER(tfile->tun, NULL);
2162 tfile->net = get_net(current->nsproxy->net_ns);
2166 init_waitqueue_head(&tfile->wq.wait);
2167 RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
2169 tfile->socket.file = file;
2170 tfile->socket.ops = &tun_socket_ops;
2172 sock_init_data(&tfile->socket, &tfile->sk);
2173 sk_change_net(&tfile->sk, tfile->net);
2175 tfile->sk.sk_write_space = tun_sock_write_space;
2176 tfile->sk.sk_sndbuf = INT_MAX;
2178 file->private_data = tfile;
2179 set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
2180 INIT_LIST_HEAD(&tfile->next);
2182 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
2187 static int tun_chr_close(struct inode *inode, struct file *file)
2189 struct tun_file *tfile = file->private_data;
2190 struct net *net = tfile->net;
2192 tun_detach(tfile, true);
2198 #ifdef CONFIG_PROC_FS
2199 static void tun_chr_show_fdinfo(struct seq_file *m, struct file *f)
2201 struct tun_struct *tun;
2204 memset(&ifr, 0, sizeof(ifr));
2209 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2215 seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
2219 static const struct file_operations tun_fops = {
2220 .owner = THIS_MODULE,
2221 .llseek = no_llseek,
2222 .read = do_sync_read,
2223 .aio_read = tun_chr_aio_read,
2224 .write = do_sync_write,
2225 .aio_write = tun_chr_aio_write,
2226 .poll = tun_chr_poll,
2227 .unlocked_ioctl = tun_chr_ioctl,
2228 #ifdef CONFIG_COMPAT
2229 .compat_ioctl = tun_chr_compat_ioctl,
2231 .open = tun_chr_open,
2232 .release = tun_chr_close,
2233 .fasync = tun_chr_fasync,
2234 #ifdef CONFIG_PROC_FS
2235 .show_fdinfo = tun_chr_show_fdinfo,
2239 static struct miscdevice tun_miscdev = {
2242 .nodename = "net/tun",
2246 /* ethtool interface */
2248 static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2251 cmd->advertising = 0;
2252 ethtool_cmd_speed_set(cmd, SPEED_10);
2253 cmd->duplex = DUPLEX_FULL;
2254 cmd->port = PORT_TP;
2255 cmd->phy_address = 0;
2256 cmd->transceiver = XCVR_INTERNAL;
2257 cmd->autoneg = AUTONEG_DISABLE;
2263 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2265 struct tun_struct *tun = netdev_priv(dev);
2267 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
2268 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
2270 switch (tun->flags & TUN_TYPE_MASK) {
2272 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
2275 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
2280 static u32 tun_get_msglevel(struct net_device *dev)
2283 struct tun_struct *tun = netdev_priv(dev);
2290 static void tun_set_msglevel(struct net_device *dev, u32 value)
2293 struct tun_struct *tun = netdev_priv(dev);
2298 static const struct ethtool_ops tun_ethtool_ops = {
2299 .get_settings = tun_get_settings,
2300 .get_drvinfo = tun_get_drvinfo,
2301 .get_msglevel = tun_get_msglevel,
2302 .set_msglevel = tun_set_msglevel,
2303 .get_link = ethtool_op_get_link,
2304 .get_ts_info = ethtool_op_get_ts_info,
2308 static int __init tun_init(void)
2312 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
2313 pr_info("%s\n", DRV_COPYRIGHT);
2315 ret = rtnl_link_register(&tun_link_ops);
2317 pr_err("Can't register link_ops\n");
2321 ret = misc_register(&tun_miscdev);
2323 pr_err("Can't register misc device %d\n", TUN_MINOR);
2328 rtnl_link_unregister(&tun_link_ops);
2333 static void tun_cleanup(void)
2335 misc_deregister(&tun_miscdev);
2336 rtnl_link_unregister(&tun_link_ops);
2339 /* Get an underlying socket object from tun file. Returns error unless file is
2340 * attached to a device. The returned object works like a packet socket, it
2341 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
2342 * holding a reference to the file for as long as the socket is in use. */
2343 struct socket *tun_get_socket(struct file *file)
2345 struct tun_file *tfile;
2346 if (file->f_op != &tun_fops)
2347 return ERR_PTR(-EINVAL);
2348 tfile = file->private_data;
2350 return ERR_PTR(-EBADFD);
2351 return &tfile->socket;
2353 EXPORT_SYMBOL_GPL(tun_get_socket);
2355 module_init(tun_init);
2356 module_exit(tun_cleanup);
2357 MODULE_DESCRIPTION(DRV_DESCRIPTION);
2358 MODULE_AUTHOR(DRV_COPYRIGHT);
2359 MODULE_LICENSE("GPL");
2360 MODULE_ALIAS_MISCDEV(TUN_MINOR);
2361 MODULE_ALIAS("devname:net/tun");