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>
68 #include <net/net_namespace.h>
69 #include <net/netns/generic.h>
70 #include <net/rtnetlink.h>
73 #include <asm/uaccess.h>
75 /* Uncomment to enable debugging */
76 /* #define TUN_DEBUG 1 */
81 #define tun_debug(level, tun, fmt, args...) \
84 netdev_printk(level, tun->dev, fmt, ##args); \
86 #define DBG1(level, fmt, args...) \
89 printk(level fmt, ##args); \
92 #define tun_debug(level, tun, fmt, args...) \
95 netdev_printk(level, tun->dev, fmt, ##args); \
97 #define DBG1(level, fmt, args...) \
100 printk(level fmt, ##args); \
104 #define GOODCOPY_LEN 128
106 #define FLT_EXACT_COUNT 8
108 unsigned int count; /* Number of addrs. Zero means disabled */
109 u32 mask[2]; /* Mask of the hashed addrs */
110 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
113 /* DEFAULT_MAX_NUM_RSS_QUEUES were choosed to let the rx/tx queues allocated for
114 * the netdevice to be fit in one page. So we can make sure the success of
115 * memory allocation. TODO: increase the limit. */
116 #define MAX_TAP_QUEUES DEFAULT_MAX_NUM_RSS_QUEUES
117 #define MAX_TAP_FLOWS 4096
119 #define TUN_FLOW_EXPIRE (3 * HZ)
121 /* A tun_file connects an open character device to a tuntap netdevice. It
122 * also contains all socket related strctures (except sock_fprog and tap_filter)
123 * to serve as one transmit queue for tuntap device. The sock_fprog and
124 * tap_filter were kept in tun_struct since they were used for filtering for the
125 * netdevice not for a specific queue (at least I didn't see the requirement for
129 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
130 * other can only be read while rcu_read_lock or rtnl_lock is held.
134 struct socket socket;
136 struct tun_struct __rcu *tun;
138 struct fasync_struct *fasync;
139 /* only used for fasnyc */
143 unsigned int ifindex;
145 struct list_head next;
146 struct tun_struct *detached;
149 struct tun_flow_entry {
150 struct hlist_node hash_link;
152 struct tun_struct *tun;
156 unsigned long updated;
159 #define TUN_NUM_FLOW_ENTRIES 1024
161 /* Since the socket were moved to tun_file, to preserve the behavior of persist
162 * device, socket filter, sndbuf and vnet header size were restore when the
163 * file were attached to a persist device.
166 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
167 unsigned int numqueues;
172 struct net_device *dev;
173 netdev_features_t set_features;
174 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
175 NETIF_F_TSO6|NETIF_F_UFO)
179 struct tap_filter txflt;
180 struct sock_fprog fprog;
181 /* protected by rtnl lock */
182 bool filter_attached;
187 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
188 struct timer_list flow_gc_timer;
189 unsigned long ageing_time;
190 unsigned int numdisabled;
191 struct list_head disabled;
196 static inline u32 tun_hashfn(u32 rxhash)
198 return rxhash & 0x3ff;
201 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
203 struct tun_flow_entry *e;
205 hlist_for_each_entry_rcu(e, head, hash_link) {
206 if (e->rxhash == rxhash)
212 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
213 struct hlist_head *head,
214 u32 rxhash, u16 queue_index)
216 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
219 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
220 rxhash, queue_index);
221 e->updated = jiffies;
223 e->queue_index = queue_index;
225 hlist_add_head_rcu(&e->hash_link, head);
231 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
233 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
234 e->rxhash, e->queue_index);
235 hlist_del_rcu(&e->hash_link);
240 static void tun_flow_flush(struct tun_struct *tun)
244 spin_lock_bh(&tun->lock);
245 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
246 struct tun_flow_entry *e;
247 struct hlist_node *n;
249 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
250 tun_flow_delete(tun, e);
252 spin_unlock_bh(&tun->lock);
255 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
259 spin_lock_bh(&tun->lock);
260 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
261 struct tun_flow_entry *e;
262 struct hlist_node *n;
264 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
265 if (e->queue_index == queue_index)
266 tun_flow_delete(tun, e);
269 spin_unlock_bh(&tun->lock);
272 static void tun_flow_cleanup(unsigned long data)
274 struct tun_struct *tun = (struct tun_struct *)data;
275 unsigned long delay = tun->ageing_time;
276 unsigned long next_timer = jiffies + delay;
277 unsigned long count = 0;
280 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
282 spin_lock_bh(&tun->lock);
283 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
284 struct tun_flow_entry *e;
285 struct hlist_node *n;
287 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
288 unsigned long this_timer;
290 this_timer = e->updated + delay;
291 if (time_before_eq(this_timer, jiffies))
292 tun_flow_delete(tun, e);
293 else if (time_before(this_timer, next_timer))
294 next_timer = this_timer;
299 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
300 spin_unlock_bh(&tun->lock);
303 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
304 struct tun_file *tfile)
306 struct hlist_head *head;
307 struct tun_flow_entry *e;
308 unsigned long delay = tun->ageing_time;
309 u16 queue_index = tfile->queue_index;
314 head = &tun->flows[tun_hashfn(rxhash)];
318 /* We may get a very small possibility of OOO during switching, not
319 * worth to optimize.*/
320 if (tun->numqueues == 1 || tfile->detached)
323 e = tun_flow_find(head, rxhash);
325 /* TODO: keep queueing to old queue until it's empty? */
326 e->queue_index = queue_index;
327 e->updated = jiffies;
329 spin_lock_bh(&tun->lock);
330 if (!tun_flow_find(head, rxhash) &&
331 tun->flow_count < MAX_TAP_FLOWS)
332 tun_flow_create(tun, head, rxhash, queue_index);
334 if (!timer_pending(&tun->flow_gc_timer))
335 mod_timer(&tun->flow_gc_timer,
336 round_jiffies_up(jiffies + delay));
337 spin_unlock_bh(&tun->lock);
344 /* We try to identify a flow through its rxhash first. The reason that
345 * we do not check rxq no. is becuase some cards(e.g 82599), chooses
346 * the rxq based on the txq where the last packet of the flow comes. As
347 * the userspace application move between processors, we may get a
348 * different rxq no. here. If we could not get rxhash, then we would
349 * hope the rxq no. may help here.
351 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb)
353 struct tun_struct *tun = netdev_priv(dev);
354 struct tun_flow_entry *e;
359 numqueues = ACCESS_ONCE(tun->numqueues);
361 txq = skb_get_rxhash(skb);
363 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
365 txq = e->queue_index;
367 /* use multiply and shift instead of expensive divide */
368 txq = ((u64)txq * numqueues) >> 32;
369 } else if (likely(skb_rx_queue_recorded(skb))) {
370 txq = skb_get_rx_queue(skb);
371 while (unlikely(txq >= numqueues))
379 static inline bool tun_not_capable(struct tun_struct *tun)
381 const struct cred *cred = current_cred();
382 struct net *net = dev_net(tun->dev);
384 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
385 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
386 !ns_capable(net->user_ns, CAP_NET_ADMIN);
389 static void tun_set_real_num_queues(struct tun_struct *tun)
391 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
392 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
395 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
397 tfile->detached = tun;
398 list_add_tail(&tfile->next, &tun->disabled);
402 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
404 struct tun_struct *tun = tfile->detached;
406 tfile->detached = NULL;
407 list_del_init(&tfile->next);
412 static void __tun_detach(struct tun_file *tfile, bool clean)
414 struct tun_file *ntfile;
415 struct tun_struct *tun;
417 tun = rtnl_dereference(tfile->tun);
419 if (tun && !tfile->detached) {
420 u16 index = tfile->queue_index;
421 BUG_ON(index >= tun->numqueues);
423 rcu_assign_pointer(tun->tfiles[index],
424 tun->tfiles[tun->numqueues - 1]);
425 ntfile = rtnl_dereference(tun->tfiles[index]);
426 ntfile->queue_index = index;
430 rcu_assign_pointer(tfile->tun, NULL);
431 sock_put(&tfile->sk);
433 tun_disable_queue(tun, tfile);
436 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
437 /* Drop read queue */
438 skb_queue_purge(&tfile->sk.sk_receive_queue);
439 tun_set_real_num_queues(tun);
440 } else if (tfile->detached && clean) {
441 tun = tun_enable_queue(tfile);
442 sock_put(&tfile->sk);
446 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
447 netif_carrier_off(tun->dev);
449 if (!(tun->flags & TUN_PERSIST) &&
450 tun->dev->reg_state == NETREG_REGISTERED)
451 unregister_netdevice(tun->dev);
454 BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
455 &tfile->socket.flags));
456 sk_release_kernel(&tfile->sk);
460 static void tun_detach(struct tun_file *tfile, bool clean)
463 __tun_detach(tfile, clean);
467 static void tun_detach_all(struct net_device *dev)
469 struct tun_struct *tun = netdev_priv(dev);
470 struct tun_file *tfile, *tmp;
471 int i, n = tun->numqueues;
473 for (i = 0; i < n; i++) {
474 tfile = rtnl_dereference(tun->tfiles[i]);
476 wake_up_all(&tfile->wq.wait);
477 rcu_assign_pointer(tfile->tun, NULL);
480 list_for_each_entry(tfile, &tun->disabled, next) {
481 wake_up_all(&tfile->wq.wait);
482 rcu_assign_pointer(tfile->tun, NULL);
484 BUG_ON(tun->numqueues != 0);
487 for (i = 0; i < n; i++) {
488 tfile = rtnl_dereference(tun->tfiles[i]);
489 /* Drop read queue */
490 skb_queue_purge(&tfile->sk.sk_receive_queue);
491 sock_put(&tfile->sk);
493 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
494 tun_enable_queue(tfile);
495 skb_queue_purge(&tfile->sk.sk_receive_queue);
496 sock_put(&tfile->sk);
498 BUG_ON(tun->numdisabled != 0);
500 if (tun->flags & TUN_PERSIST)
501 module_put(THIS_MODULE);
504 static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter)
506 struct tun_file *tfile = file->private_data;
509 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
514 if (rtnl_dereference(tfile->tun) && !tfile->detached)
518 if (!(tun->flags & TUN_TAP_MQ) && tun->numqueues == 1)
522 if (!tfile->detached &&
523 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
528 /* Re-attach the filter to presist device */
529 if (!skip_filter && (tun->filter_attached == true)) {
530 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
534 tfile->queue_index = tun->numqueues;
535 rcu_assign_pointer(tfile->tun, tun);
536 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
540 tun_enable_queue(tfile);
542 sock_hold(&tfile->sk);
544 tun_set_real_num_queues(tun);
546 /* device is allowed to go away first, so no need to hold extra
554 static struct tun_struct *__tun_get(struct tun_file *tfile)
556 struct tun_struct *tun;
559 tun = rcu_dereference(tfile->tun);
567 static struct tun_struct *tun_get(struct file *file)
569 return __tun_get(file->private_data);
572 static void tun_put(struct tun_struct *tun)
578 static void addr_hash_set(u32 *mask, const u8 *addr)
580 int n = ether_crc(ETH_ALEN, addr) >> 26;
581 mask[n >> 5] |= (1 << (n & 31));
584 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
586 int n = ether_crc(ETH_ALEN, addr) >> 26;
587 return mask[n >> 5] & (1 << (n & 31));
590 static int update_filter(struct tap_filter *filter, void __user *arg)
592 struct { u8 u[ETH_ALEN]; } *addr;
593 struct tun_filter uf;
594 int err, alen, n, nexact;
596 if (copy_from_user(&uf, arg, sizeof(uf)))
605 alen = ETH_ALEN * uf.count;
606 addr = kmalloc(alen, GFP_KERNEL);
610 if (copy_from_user(addr, arg + sizeof(uf), alen)) {
615 /* The filter is updated without holding any locks. Which is
616 * perfectly safe. We disable it first and in the worst
617 * case we'll accept a few undesired packets. */
621 /* Use first set of addresses as an exact filter */
622 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
623 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
627 /* Remaining multicast addresses are hashed,
628 * unicast will leave the filter disabled. */
629 memset(filter->mask, 0, sizeof(filter->mask));
630 for (; n < uf.count; n++) {
631 if (!is_multicast_ether_addr(addr[n].u)) {
632 err = 0; /* no filter */
635 addr_hash_set(filter->mask, addr[n].u);
638 /* For ALLMULTI just set the mask to all ones.
639 * This overrides the mask populated above. */
640 if ((uf.flags & TUN_FLT_ALLMULTI))
641 memset(filter->mask, ~0, sizeof(filter->mask));
643 /* Now enable the filter */
645 filter->count = nexact;
647 /* Return the number of exact filters */
655 /* Returns: 0 - drop, !=0 - accept */
656 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
658 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
660 struct ethhdr *eh = (struct ethhdr *) skb->data;
664 for (i = 0; i < filter->count; i++)
665 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
668 /* Inexact match (multicast only) */
669 if (is_multicast_ether_addr(eh->h_dest))
670 return addr_hash_test(filter->mask, eh->h_dest);
676 * Checks whether the packet is accepted or not.
677 * Returns: 0 - drop, !=0 - accept
679 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
684 return run_filter(filter, skb);
687 /* Network device part of the driver */
689 static const struct ethtool_ops tun_ethtool_ops;
691 /* Net device detach from fd. */
692 static void tun_net_uninit(struct net_device *dev)
697 /* Net device open. */
698 static int tun_net_open(struct net_device *dev)
700 netif_tx_start_all_queues(dev);
704 /* Net device close. */
705 static int tun_net_close(struct net_device *dev)
707 netif_tx_stop_all_queues(dev);
711 /* Net device start xmit */
712 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
714 struct tun_struct *tun = netdev_priv(dev);
715 int txq = skb->queue_mapping;
716 struct tun_file *tfile;
719 tfile = rcu_dereference(tun->tfiles[txq]);
721 /* Drop packet if interface is not attached */
722 if (txq >= tun->numqueues)
725 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
729 /* Drop if the filter does not like it.
730 * This is a noop if the filter is disabled.
731 * Filter can be enabled only for the TAP devices. */
732 if (!check_filter(&tun->txflt, skb))
735 if (tfile->socket.sk->sk_filter &&
736 sk_filter(tfile->socket.sk, skb))
739 /* Limit the number of packets queued by dividing txq length with the
742 if (skb_queue_len(&tfile->socket.sk->sk_receive_queue)
743 >= dev->tx_queue_len / tun->numqueues)
747 sock_tx_timestamp(skb->sk, &skb_shinfo(skb)->tx_flags);
748 sw_tx_timestamp(skb);
751 /* Orphan the skb - required as we might hang on to it
752 * for indefinite time. */
753 if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
760 skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
762 /* Notify and wake up reader process */
763 if (tfile->flags & TUN_FASYNC)
764 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
765 wake_up_interruptible_poll(&tfile->wq.wait, POLLIN |
766 POLLRDNORM | POLLRDBAND);
772 dev->stats.tx_dropped++;
779 static void tun_net_mclist(struct net_device *dev)
782 * This callback is supposed to deal with mc filter in
783 * _rx_ path and has nothing to do with the _tx_ path.
784 * In rx path we always accept everything userspace gives us.
789 #define MAX_MTU 65535
792 tun_net_change_mtu(struct net_device *dev, int new_mtu)
794 if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
800 static netdev_features_t tun_net_fix_features(struct net_device *dev,
801 netdev_features_t features)
803 struct tun_struct *tun = netdev_priv(dev);
805 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
807 #ifdef CONFIG_NET_POLL_CONTROLLER
808 static void tun_poll_controller(struct net_device *dev)
811 * Tun only receives frames when:
812 * 1) the char device endpoint gets data from user space
813 * 2) the tun socket gets a sendmsg call from user space
814 * Since both of those are syncronous operations, we are guaranteed
815 * never to have pending data when we poll for it
816 * so theres nothing to do here but return.
817 * We need this though so netpoll recognizes us as an interface that
818 * supports polling, which enables bridge devices in virt setups to
819 * still use netconsole
824 static const struct net_device_ops tun_netdev_ops = {
825 .ndo_uninit = tun_net_uninit,
826 .ndo_open = tun_net_open,
827 .ndo_stop = tun_net_close,
828 .ndo_start_xmit = tun_net_xmit,
829 .ndo_change_mtu = tun_net_change_mtu,
830 .ndo_fix_features = tun_net_fix_features,
831 .ndo_select_queue = tun_select_queue,
832 #ifdef CONFIG_NET_POLL_CONTROLLER
833 .ndo_poll_controller = tun_poll_controller,
837 static const struct net_device_ops tap_netdev_ops = {
838 .ndo_uninit = tun_net_uninit,
839 .ndo_open = tun_net_open,
840 .ndo_stop = tun_net_close,
841 .ndo_start_xmit = tun_net_xmit,
842 .ndo_change_mtu = tun_net_change_mtu,
843 .ndo_fix_features = tun_net_fix_features,
844 .ndo_set_rx_mode = tun_net_mclist,
845 .ndo_set_mac_address = eth_mac_addr,
846 .ndo_validate_addr = eth_validate_addr,
847 .ndo_select_queue = tun_select_queue,
848 #ifdef CONFIG_NET_POLL_CONTROLLER
849 .ndo_poll_controller = tun_poll_controller,
853 static void tun_flow_init(struct tun_struct *tun)
857 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
858 INIT_HLIST_HEAD(&tun->flows[i]);
860 tun->ageing_time = TUN_FLOW_EXPIRE;
861 setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
862 mod_timer(&tun->flow_gc_timer,
863 round_jiffies_up(jiffies + tun->ageing_time));
866 static void tun_flow_uninit(struct tun_struct *tun)
868 del_timer_sync(&tun->flow_gc_timer);
872 /* Initialize net device. */
873 static void tun_net_init(struct net_device *dev)
875 struct tun_struct *tun = netdev_priv(dev);
877 switch (tun->flags & TUN_TYPE_MASK) {
879 dev->netdev_ops = &tun_netdev_ops;
881 /* Point-to-Point TUN Device */
882 dev->hard_header_len = 0;
886 /* Zero header length */
887 dev->type = ARPHRD_NONE;
888 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
889 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
893 dev->netdev_ops = &tap_netdev_ops;
894 /* Ethernet TAP Device */
896 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
897 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
899 eth_hw_addr_random(dev);
901 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
906 /* Character device part */
909 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
911 struct tun_file *tfile = file->private_data;
912 struct tun_struct *tun = __tun_get(tfile);
914 unsigned int mask = 0;
919 sk = tfile->socket.sk;
921 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
923 poll_wait(file, &tfile->wq.wait, wait);
925 if (!skb_queue_empty(&sk->sk_receive_queue))
926 mask |= POLLIN | POLLRDNORM;
928 if (sock_writeable(sk) ||
929 (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
931 mask |= POLLOUT | POLLWRNORM;
933 if (tun->dev->reg_state != NETREG_REGISTERED)
940 /* prepad is the amount to reserve at front. len is length after that.
941 * linear is a hint as to how much to copy (usually headers). */
942 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
943 size_t prepad, size_t len,
944 size_t linear, int noblock)
946 struct sock *sk = tfile->socket.sk;
950 /* Under a page? Don't bother with paged skb. */
951 if (prepad + len < PAGE_SIZE || !linear)
954 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
959 skb_reserve(skb, prepad);
960 skb_put(skb, linear);
961 skb->data_len = len - linear;
962 skb->len += len - linear;
967 /* Get packet from user space buffer */
968 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
969 void *msg_control, const struct iovec *iv,
970 size_t total_len, size_t count, int noblock)
972 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
974 size_t len = total_len, align = NET_SKB_PAD, linear;
975 struct virtio_net_hdr gso = { 0 };
978 bool zerocopy = false;
982 if (!(tun->flags & TUN_NO_PI)) {
983 if (len < sizeof(pi))
987 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
989 offset += sizeof(pi);
992 if (tun->flags & TUN_VNET_HDR) {
993 if (len < tun->vnet_hdr_sz)
995 len -= tun->vnet_hdr_sz;
997 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
1000 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1001 gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
1002 gso.hdr_len = gso.csum_start + gso.csum_offset + 2;
1004 if (gso.hdr_len > len)
1006 offset += tun->vnet_hdr_sz;
1009 if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
1010 align += NET_IP_ALIGN;
1011 if (unlikely(len < ETH_HLEN ||
1012 (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
1017 /* There are 256 bytes to be copied in skb, so there is
1018 * enough room for skb expand head in case it is used.
1019 * The rest of the buffer is mapped from userspace.
1021 copylen = gso.hdr_len ? gso.hdr_len : GOODCOPY_LEN;
1023 if (iov_pages(iv, offset + copylen, count) <= MAX_SKB_FRAGS)
1029 linear = gso.hdr_len;
1032 skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
1034 if (PTR_ERR(skb) != -EAGAIN)
1035 tun->dev->stats.rx_dropped++;
1036 return PTR_ERR(skb);
1040 err = zerocopy_sg_from_iovec(skb, iv, offset, count);
1042 err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
1043 if (!err && msg_control) {
1044 struct ubuf_info *uarg = msg_control;
1045 uarg->callback(uarg, false);
1050 tun->dev->stats.rx_dropped++;
1055 if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1056 if (!skb_partial_csum_set(skb, gso.csum_start,
1058 tun->dev->stats.rx_frame_errors++;
1064 switch (tun->flags & TUN_TYPE_MASK) {
1066 if (tun->flags & TUN_NO_PI) {
1067 switch (skb->data[0] & 0xf0) {
1069 pi.proto = htons(ETH_P_IP);
1072 pi.proto = htons(ETH_P_IPV6);
1075 tun->dev->stats.rx_dropped++;
1081 skb_reset_mac_header(skb);
1082 skb->protocol = pi.proto;
1083 skb->dev = tun->dev;
1086 skb->protocol = eth_type_trans(skb, tun->dev);
1090 if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1092 switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1093 case VIRTIO_NET_HDR_GSO_TCPV4:
1094 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1096 case VIRTIO_NET_HDR_GSO_TCPV6:
1097 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1099 case VIRTIO_NET_HDR_GSO_UDP:
1100 skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
1103 tun->dev->stats.rx_frame_errors++;
1108 if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1109 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
1111 skb_shinfo(skb)->gso_size = gso.gso_size;
1112 if (skb_shinfo(skb)->gso_size == 0) {
1113 tun->dev->stats.rx_frame_errors++;
1118 /* Header must be checked, and gso_segs computed. */
1119 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1120 skb_shinfo(skb)->gso_segs = 0;
1123 /* copy skb_ubuf_info for callback when skb has no error */
1125 skb_shinfo(skb)->destructor_arg = msg_control;
1126 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1127 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1130 skb_reset_network_header(skb);
1131 skb_probe_transport_header(skb, 0);
1133 rxhash = skb_get_rxhash(skb);
1136 tun->dev->stats.rx_packets++;
1137 tun->dev->stats.rx_bytes += len;
1139 tun_flow_update(tun, rxhash, tfile);
1143 static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
1144 unsigned long count, loff_t pos)
1146 struct file *file = iocb->ki_filp;
1147 struct tun_struct *tun = tun_get(file);
1148 struct tun_file *tfile = file->private_data;
1154 tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
1156 result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
1157 count, file->f_flags & O_NONBLOCK);
1163 /* Put packet to the user space buffer */
1164 static ssize_t tun_put_user(struct tun_struct *tun,
1165 struct tun_file *tfile,
1166 struct sk_buff *skb,
1167 const struct iovec *iv, int len)
1169 struct tun_pi pi = { 0, skb->protocol };
1171 int vlan_offset = 0;
1173 if (!(tun->flags & TUN_NO_PI)) {
1174 if ((len -= sizeof(pi)) < 0)
1177 if (len < skb->len) {
1178 /* Packet will be striped */
1179 pi.flags |= TUN_PKT_STRIP;
1182 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
1184 total += sizeof(pi);
1187 if (tun->flags & TUN_VNET_HDR) {
1188 struct virtio_net_hdr gso = { 0 }; /* no info leak */
1189 if ((len -= tun->vnet_hdr_sz) < 0)
1192 if (skb_is_gso(skb)) {
1193 struct skb_shared_info *sinfo = skb_shinfo(skb);
1195 /* This is a hint as to how much should be linear. */
1196 gso.hdr_len = skb_headlen(skb);
1197 gso.gso_size = sinfo->gso_size;
1198 if (sinfo->gso_type & SKB_GSO_TCPV4)
1199 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1200 else if (sinfo->gso_type & SKB_GSO_TCPV6)
1201 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1202 else if (sinfo->gso_type & SKB_GSO_UDP)
1203 gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1205 pr_err("unexpected GSO type: "
1206 "0x%x, gso_size %d, hdr_len %d\n",
1207 sinfo->gso_type, gso.gso_size,
1209 print_hex_dump(KERN_ERR, "tun: ",
1212 min((int)gso.hdr_len, 64), true);
1216 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1217 gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1219 gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1221 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1222 gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
1223 gso.csum_start = skb_checksum_start_offset(skb);
1224 gso.csum_offset = skb->csum_offset;
1225 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
1226 gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1227 } /* else everything is zero */
1229 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
1232 total += tun->vnet_hdr_sz;
1235 if (!vlan_tx_tag_present(skb)) {
1236 len = min_t(int, skb->len, len);
1240 __be16 h_vlan_proto;
1244 veth.h_vlan_proto = skb->vlan_proto;
1245 veth.h_vlan_TCI = htons(vlan_tx_tag_get(skb));
1247 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
1248 len = min_t(int, skb->len + VLAN_HLEN, len);
1250 copy = min_t(int, vlan_offset, len);
1251 ret = skb_copy_datagram_const_iovec(skb, 0, iv, total, copy);
1257 copy = min_t(int, sizeof(veth), len);
1258 ret = memcpy_toiovecend(iv, (void *)&veth, total, copy);
1265 skb_copy_datagram_const_iovec(skb, vlan_offset, iv, total, len);
1269 tun->dev->stats.tx_packets++;
1270 tun->dev->stats.tx_bytes += len;
1275 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1276 struct kiocb *iocb, const struct iovec *iv,
1277 ssize_t len, int noblock)
1279 DECLARE_WAITQUEUE(wait, current);
1280 struct sk_buff *skb;
1283 tun_debug(KERN_INFO, tun, "tun_do_read\n");
1285 if (unlikely(!noblock))
1286 add_wait_queue(&tfile->wq.wait, &wait);
1288 current->state = TASK_INTERRUPTIBLE;
1290 /* Read frames from the queue */
1291 if (!(skb = skb_dequeue(&tfile->socket.sk->sk_receive_queue))) {
1296 if (signal_pending(current)) {
1300 if (tun->dev->reg_state != NETREG_REGISTERED) {
1305 /* Nothing to read, let's sleep */
1310 ret = tun_put_user(tun, tfile, skb, iv, len);
1315 current->state = TASK_RUNNING;
1316 if (unlikely(!noblock))
1317 remove_wait_queue(&tfile->wq.wait, &wait);
1322 static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
1323 unsigned long count, loff_t pos)
1325 struct file *file = iocb->ki_filp;
1326 struct tun_file *tfile = file->private_data;
1327 struct tun_struct *tun = __tun_get(tfile);
1332 len = iov_length(iv, count);
1338 ret = tun_do_read(tun, tfile, iocb, iv, len,
1339 file->f_flags & O_NONBLOCK);
1340 ret = min_t(ssize_t, ret, len);
1346 static void tun_free_netdev(struct net_device *dev)
1348 struct tun_struct *tun = netdev_priv(dev);
1350 BUG_ON(!(list_empty(&tun->disabled)));
1351 tun_flow_uninit(tun);
1352 security_tun_dev_free_security(tun->security);
1356 static void tun_setup(struct net_device *dev)
1358 struct tun_struct *tun = netdev_priv(dev);
1360 tun->owner = INVALID_UID;
1361 tun->group = INVALID_GID;
1363 dev->ethtool_ops = &tun_ethtool_ops;
1364 dev->destructor = tun_free_netdev;
1367 /* Trivial set of netlink ops to allow deleting tun or tap
1368 * device with netlink.
1370 static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1375 static struct rtnl_link_ops tun_link_ops __read_mostly = {
1377 .priv_size = sizeof(struct tun_struct),
1379 .validate = tun_validate,
1382 static void tun_sock_write_space(struct sock *sk)
1384 struct tun_file *tfile;
1385 wait_queue_head_t *wqueue;
1387 if (!sock_writeable(sk))
1390 if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1393 wqueue = sk_sleep(sk);
1394 if (wqueue && waitqueue_active(wqueue))
1395 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1396 POLLWRNORM | POLLWRBAND);
1398 tfile = container_of(sk, struct tun_file, sk);
1399 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1402 static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1403 struct msghdr *m, size_t total_len)
1406 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1407 struct tun_struct *tun = __tun_get(tfile);
1411 ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
1412 m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
1417 static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1418 struct msghdr *m, size_t total_len,
1421 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1422 struct tun_struct *tun = __tun_get(tfile);
1428 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
1432 if (flags & MSG_ERRQUEUE) {
1433 ret = sock_recv_errqueue(sock->sk, m, total_len,
1434 SOL_PACKET, TUN_TX_TIMESTAMP);
1437 ret = tun_do_read(tun, tfile, iocb, m->msg_iov, total_len,
1438 flags & MSG_DONTWAIT);
1439 if (ret > total_len) {
1440 m->msg_flags |= MSG_TRUNC;
1441 ret = flags & MSG_TRUNC ? ret : total_len;
1448 static int tun_release(struct socket *sock)
1455 /* Ops structure to mimic raw sockets with tun */
1456 static const struct proto_ops tun_socket_ops = {
1457 .sendmsg = tun_sendmsg,
1458 .recvmsg = tun_recvmsg,
1459 .release = tun_release,
1462 static struct proto tun_proto = {
1464 .owner = THIS_MODULE,
1465 .obj_size = sizeof(struct tun_file),
1468 static int tun_flags(struct tun_struct *tun)
1472 if (tun->flags & TUN_TUN_DEV)
1477 if (tun->flags & TUN_NO_PI)
1480 /* This flag has no real effect. We track the value for backwards
1483 if (tun->flags & TUN_ONE_QUEUE)
1484 flags |= IFF_ONE_QUEUE;
1486 if (tun->flags & TUN_VNET_HDR)
1487 flags |= IFF_VNET_HDR;
1489 if (tun->flags & TUN_TAP_MQ)
1490 flags |= IFF_MULTI_QUEUE;
1492 if (tun->flags & TUN_PERSIST)
1493 flags |= IFF_PERSIST;
1498 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1501 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1502 return sprintf(buf, "0x%x\n", tun_flags(tun));
1505 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1508 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1509 return uid_valid(tun->owner)?
1510 sprintf(buf, "%u\n",
1511 from_kuid_munged(current_user_ns(), tun->owner)):
1512 sprintf(buf, "-1\n");
1515 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1518 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1519 return gid_valid(tun->group) ?
1520 sprintf(buf, "%u\n",
1521 from_kgid_munged(current_user_ns(), tun->group)):
1522 sprintf(buf, "-1\n");
1525 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1526 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1527 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1529 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1531 struct tun_struct *tun;
1532 struct tun_file *tfile = file->private_data;
1533 struct net_device *dev;
1536 if (tfile->detached)
1539 dev = __dev_get_by_name(net, ifr->ifr_name);
1541 if (ifr->ifr_flags & IFF_TUN_EXCL)
1543 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
1544 tun = netdev_priv(dev);
1545 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
1546 tun = netdev_priv(dev);
1550 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
1551 !!(tun->flags & TUN_TAP_MQ))
1554 if (tun_not_capable(tun))
1556 err = security_tun_dev_open(tun->security);
1560 err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
1564 if (tun->flags & TUN_TAP_MQ &&
1565 (tun->numqueues + tun->numdisabled > 1)) {
1566 /* One or more queue has already been attached, no need
1567 * to initialize the device again.
1574 unsigned long flags = 0;
1575 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1578 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1580 err = security_tun_dev_create();
1585 if (ifr->ifr_flags & IFF_TUN) {
1587 flags |= TUN_TUN_DEV;
1589 } else if (ifr->ifr_flags & IFF_TAP) {
1591 flags |= TUN_TAP_DEV;
1597 name = ifr->ifr_name;
1599 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1600 tun_setup, queues, queues);
1605 dev_net_set(dev, net);
1606 dev->rtnl_link_ops = &tun_link_ops;
1607 dev->ifindex = tfile->ifindex;
1609 tun = netdev_priv(dev);
1612 tun->txflt.count = 0;
1613 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
1615 tun->filter_attached = false;
1616 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
1618 spin_lock_init(&tun->lock);
1620 err = security_tun_dev_alloc_security(&tun->security);
1627 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1628 TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
1629 NETIF_F_HW_VLAN_STAG_TX;
1630 dev->features = dev->hw_features;
1631 dev->vlan_features = dev->features;
1633 INIT_LIST_HEAD(&tun->disabled);
1634 err = tun_attach(tun, file, false);
1638 err = register_netdevice(tun->dev);
1642 if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1643 device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1644 device_create_file(&tun->dev->dev, &dev_attr_group))
1645 pr_err("Failed to create tun sysfs files\n");
1648 netif_carrier_on(tun->dev);
1650 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1652 if (ifr->ifr_flags & IFF_NO_PI)
1653 tun->flags |= TUN_NO_PI;
1655 tun->flags &= ~TUN_NO_PI;
1657 /* This flag has no real effect. We track the value for backwards
1660 if (ifr->ifr_flags & IFF_ONE_QUEUE)
1661 tun->flags |= TUN_ONE_QUEUE;
1663 tun->flags &= ~TUN_ONE_QUEUE;
1665 if (ifr->ifr_flags & IFF_VNET_HDR)
1666 tun->flags |= TUN_VNET_HDR;
1668 tun->flags &= ~TUN_VNET_HDR;
1670 if (ifr->ifr_flags & IFF_MULTI_QUEUE)
1671 tun->flags |= TUN_TAP_MQ;
1673 tun->flags &= ~TUN_TAP_MQ;
1675 /* Make sure persistent devices do not get stuck in
1678 if (netif_running(tun->dev))
1679 netif_tx_wake_all_queues(tun->dev);
1681 strcpy(ifr->ifr_name, tun->dev->name);
1689 static void tun_get_iff(struct net *net, struct tun_struct *tun,
1692 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1694 strcpy(ifr->ifr_name, tun->dev->name);
1696 ifr->ifr_flags = tun_flags(tun);
1700 /* This is like a cut-down ethtool ops, except done via tun fd so no
1701 * privs required. */
1702 static int set_offload(struct tun_struct *tun, unsigned long arg)
1704 netdev_features_t features = 0;
1706 if (arg & TUN_F_CSUM) {
1707 features |= NETIF_F_HW_CSUM;
1710 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
1711 if (arg & TUN_F_TSO_ECN) {
1712 features |= NETIF_F_TSO_ECN;
1713 arg &= ~TUN_F_TSO_ECN;
1715 if (arg & TUN_F_TSO4)
1716 features |= NETIF_F_TSO;
1717 if (arg & TUN_F_TSO6)
1718 features |= NETIF_F_TSO6;
1719 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
1722 if (arg & TUN_F_UFO) {
1723 features |= NETIF_F_UFO;
1728 /* This gives the user a way to test for new features in future by
1729 * trying to set them. */
1733 tun->set_features = features;
1734 netdev_update_features(tun->dev);
1739 static void tun_detach_filter(struct tun_struct *tun, int n)
1742 struct tun_file *tfile;
1744 for (i = 0; i < n; i++) {
1745 tfile = rtnl_dereference(tun->tfiles[i]);
1746 sk_detach_filter(tfile->socket.sk);
1749 tun->filter_attached = false;
1752 static int tun_attach_filter(struct tun_struct *tun)
1755 struct tun_file *tfile;
1757 for (i = 0; i < tun->numqueues; i++) {
1758 tfile = rtnl_dereference(tun->tfiles[i]);
1759 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1761 tun_detach_filter(tun, i);
1766 tun->filter_attached = true;
1770 static void tun_set_sndbuf(struct tun_struct *tun)
1772 struct tun_file *tfile;
1775 for (i = 0; i < tun->numqueues; i++) {
1776 tfile = rtnl_dereference(tun->tfiles[i]);
1777 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1781 static int tun_set_queue(struct file *file, struct ifreq *ifr)
1783 struct tun_file *tfile = file->private_data;
1784 struct tun_struct *tun;
1789 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
1790 tun = tfile->detached;
1795 ret = security_tun_dev_attach_queue(tun->security);
1798 ret = tun_attach(tun, file, false);
1799 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
1800 tun = rtnl_dereference(tfile->tun);
1801 if (!tun || !(tun->flags & TUN_TAP_MQ) || tfile->detached)
1804 __tun_detach(tfile, false);
1813 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
1814 unsigned long arg, int ifreq_len)
1816 struct tun_file *tfile = file->private_data;
1817 struct tun_struct *tun;
1818 void __user* argp = (void __user*)arg;
1824 unsigned int ifindex;
1827 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
1828 if (copy_from_user(&ifr, argp, ifreq_len))
1831 memset(&ifr, 0, sizeof(ifr));
1833 if (cmd == TUNGETFEATURES) {
1834 /* Currently this just means: "what IFF flags are valid?".
1835 * This is needed because we never checked for invalid flags on
1837 return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
1838 IFF_VNET_HDR | IFF_MULTI_QUEUE,
1839 (unsigned int __user*)argp);
1840 } else if (cmd == TUNSETQUEUE)
1841 return tun_set_queue(file, &ifr);
1846 tun = __tun_get(tfile);
1847 if (cmd == TUNSETIFF && !tun) {
1848 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1850 ret = tun_set_iff(tfile->net, file, &ifr);
1855 if (copy_to_user(argp, &ifr, ifreq_len))
1859 if (cmd == TUNSETIFINDEX) {
1865 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
1869 tfile->ifindex = ifindex;
1877 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1882 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
1884 if (tfile->detached)
1885 ifr.ifr_flags |= IFF_DETACH_QUEUE;
1886 if (!tfile->socket.sk->sk_filter)
1887 ifr.ifr_flags |= IFF_NOFILTER;
1889 if (copy_to_user(argp, &ifr, ifreq_len))
1894 /* Disable/Enable checksum */
1896 /* [unimplemented] */
1897 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
1898 arg ? "disabled" : "enabled");
1902 /* Disable/Enable persist mode. Keep an extra reference to the
1903 * module to prevent the module being unprobed.
1905 if (arg && !(tun->flags & TUN_PERSIST)) {
1906 tun->flags |= TUN_PERSIST;
1907 __module_get(THIS_MODULE);
1909 if (!arg && (tun->flags & TUN_PERSIST)) {
1910 tun->flags &= ~TUN_PERSIST;
1911 module_put(THIS_MODULE);
1914 tun_debug(KERN_INFO, tun, "persist %s\n",
1915 arg ? "enabled" : "disabled");
1919 /* Set owner of the device */
1920 owner = make_kuid(current_user_ns(), arg);
1921 if (!uid_valid(owner)) {
1926 tun_debug(KERN_INFO, tun, "owner set to %u\n",
1927 from_kuid(&init_user_ns, tun->owner));
1931 /* Set group of the device */
1932 group = make_kgid(current_user_ns(), arg);
1933 if (!gid_valid(group)) {
1938 tun_debug(KERN_INFO, tun, "group set to %u\n",
1939 from_kgid(&init_user_ns, tun->group));
1943 /* Only allow setting the type when the interface is down */
1944 if (tun->dev->flags & IFF_UP) {
1945 tun_debug(KERN_INFO, tun,
1946 "Linktype set failed because interface is up\n");
1949 tun->dev->type = (int) arg;
1950 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
1962 ret = set_offload(tun, arg);
1965 case TUNSETTXFILTER:
1966 /* Can be set only for TAPs */
1968 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
1970 ret = update_filter(&tun->txflt, (void __user *)arg);
1974 /* Get hw address */
1975 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
1976 ifr.ifr_hwaddr.sa_family = tun->dev->type;
1977 if (copy_to_user(argp, &ifr, ifreq_len))
1982 /* Set hw address */
1983 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
1984 ifr.ifr_hwaddr.sa_data);
1986 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
1990 sndbuf = tfile->socket.sk->sk_sndbuf;
1991 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
1996 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
2001 tun->sndbuf = sndbuf;
2002 tun_set_sndbuf(tun);
2005 case TUNGETVNETHDRSZ:
2006 vnet_hdr_sz = tun->vnet_hdr_sz;
2007 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2011 case TUNSETVNETHDRSZ:
2012 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2016 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2021 tun->vnet_hdr_sz = vnet_hdr_sz;
2024 case TUNATTACHFILTER:
2025 /* Can be set only for TAPs */
2027 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2030 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
2033 ret = tun_attach_filter(tun);
2036 case TUNDETACHFILTER:
2037 /* Can be set only for TAPs */
2039 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2042 tun_detach_filter(tun, tun->numqueues);
2047 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2050 if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
2067 static long tun_chr_ioctl(struct file *file,
2068 unsigned int cmd, unsigned long arg)
2070 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2073 #ifdef CONFIG_COMPAT
2074 static long tun_chr_compat_ioctl(struct file *file,
2075 unsigned int cmd, unsigned long arg)
2080 case TUNSETTXFILTER:
2085 arg = (unsigned long)compat_ptr(arg);
2088 arg = (compat_ulong_t)arg;
2093 * compat_ifreq is shorter than ifreq, so we must not access beyond
2094 * the end of that structure. All fields that are used in this
2095 * driver are compatible though, we don't need to convert the
2098 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2100 #endif /* CONFIG_COMPAT */
2102 static int tun_chr_fasync(int fd, struct file *file, int on)
2104 struct tun_file *tfile = file->private_data;
2107 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
2111 ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
2114 tfile->flags |= TUN_FASYNC;
2116 tfile->flags &= ~TUN_FASYNC;
2122 static int tun_chr_open(struct inode *inode, struct file * file)
2124 struct tun_file *tfile;
2126 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2128 tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
2132 rcu_assign_pointer(tfile->tun, NULL);
2133 tfile->net = get_net(current->nsproxy->net_ns);
2137 rcu_assign_pointer(tfile->socket.wq, &tfile->wq);
2138 init_waitqueue_head(&tfile->wq.wait);
2140 tfile->socket.file = file;
2141 tfile->socket.ops = &tun_socket_ops;
2143 sock_init_data(&tfile->socket, &tfile->sk);
2144 sk_change_net(&tfile->sk, tfile->net);
2146 tfile->sk.sk_write_space = tun_sock_write_space;
2147 tfile->sk.sk_sndbuf = INT_MAX;
2149 file->private_data = tfile;
2150 set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
2151 INIT_LIST_HEAD(&tfile->next);
2153 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
2158 static int tun_chr_close(struct inode *inode, struct file *file)
2160 struct tun_file *tfile = file->private_data;
2161 struct net *net = tfile->net;
2163 tun_detach(tfile, true);
2169 static const struct file_operations tun_fops = {
2170 .owner = THIS_MODULE,
2171 .llseek = no_llseek,
2172 .read = do_sync_read,
2173 .aio_read = tun_chr_aio_read,
2174 .write = do_sync_write,
2175 .aio_write = tun_chr_aio_write,
2176 .poll = tun_chr_poll,
2177 .unlocked_ioctl = tun_chr_ioctl,
2178 #ifdef CONFIG_COMPAT
2179 .compat_ioctl = tun_chr_compat_ioctl,
2181 .open = tun_chr_open,
2182 .release = tun_chr_close,
2183 .fasync = tun_chr_fasync
2186 static struct miscdevice tun_miscdev = {
2189 .nodename = "net/tun",
2193 /* ethtool interface */
2195 static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2198 cmd->advertising = 0;
2199 ethtool_cmd_speed_set(cmd, SPEED_10);
2200 cmd->duplex = DUPLEX_FULL;
2201 cmd->port = PORT_TP;
2202 cmd->phy_address = 0;
2203 cmd->transceiver = XCVR_INTERNAL;
2204 cmd->autoneg = AUTONEG_DISABLE;
2210 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2212 struct tun_struct *tun = netdev_priv(dev);
2214 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
2215 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
2217 switch (tun->flags & TUN_TYPE_MASK) {
2219 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
2222 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
2227 static u32 tun_get_msglevel(struct net_device *dev)
2230 struct tun_struct *tun = netdev_priv(dev);
2237 static void tun_set_msglevel(struct net_device *dev, u32 value)
2240 struct tun_struct *tun = netdev_priv(dev);
2245 static const struct ethtool_ops tun_ethtool_ops = {
2246 .get_settings = tun_get_settings,
2247 .get_drvinfo = tun_get_drvinfo,
2248 .get_msglevel = tun_get_msglevel,
2249 .set_msglevel = tun_set_msglevel,
2250 .get_link = ethtool_op_get_link,
2251 .get_ts_info = ethtool_op_get_ts_info,
2255 static int __init tun_init(void)
2259 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
2260 pr_info("%s\n", DRV_COPYRIGHT);
2262 ret = rtnl_link_register(&tun_link_ops);
2264 pr_err("Can't register link_ops\n");
2268 ret = misc_register(&tun_miscdev);
2270 pr_err("Can't register misc device %d\n", TUN_MINOR);
2275 rtnl_link_unregister(&tun_link_ops);
2280 static void tun_cleanup(void)
2282 misc_deregister(&tun_miscdev);
2283 rtnl_link_unregister(&tun_link_ops);
2286 /* Get an underlying socket object from tun file. Returns error unless file is
2287 * attached to a device. The returned object works like a packet socket, it
2288 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
2289 * holding a reference to the file for as long as the socket is in use. */
2290 struct socket *tun_get_socket(struct file *file)
2292 struct tun_file *tfile;
2293 if (file->f_op != &tun_fops)
2294 return ERR_PTR(-EINVAL);
2295 tfile = file->private_data;
2297 return ERR_PTR(-EBADFD);
2298 return &tfile->socket;
2300 EXPORT_SYMBOL_GPL(tun_get_socket);
2302 module_init(tun_init);
2303 module_exit(tun_cleanup);
2304 MODULE_DESCRIPTION(DRV_DESCRIPTION);
2305 MODULE_AUTHOR(DRV_COPYRIGHT);
2306 MODULE_LICENSE("GPL");
2307 MODULE_ALIAS_MISCDEV(TUN_MINOR);
2308 MODULE_ALIAS("devname:net/tun");