2 * TUN - Universal TUN/TAP device driver.
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 $
22 * Add TUNSETLINK ioctl to set the link encapsulation
25 * Use eth_random_addr() for tap MAC address.
28 * Fixes in packet dropping, queue length setting and queue wakeup.
29 * Increased default tx queue length.
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"
44 #include <linux/module.h>
45 #include <linux/errno.h>
46 #include <linux/kernel.h>
47 #include <linux/sched/signal.h>
48 #include <linux/major.h>
49 #include <linux/slab.h>
50 #include <linux/poll.h>
51 #include <linux/fcntl.h>
52 #include <linux/init.h>
53 #include <linux/skbuff.h>
54 #include <linux/netdevice.h>
55 #include <linux/etherdevice.h>
56 #include <linux/miscdevice.h>
57 #include <linux/ethtool.h>
58 #include <linux/rtnetlink.h>
59 #include <linux/compat.h>
61 #include <linux/if_arp.h>
62 #include <linux/if_ether.h>
63 #include <linux/if_tun.h>
64 #include <linux/if_vlan.h>
65 #include <linux/crc32.h>
66 #include <linux/nsproxy.h>
67 #include <linux/virtio_net.h>
68 #include <linux/rcupdate.h>
69 #include <net/net_namespace.h>
70 #include <net/netns/generic.h>
71 #include <net/rtnetlink.h>
74 #include <linux/seq_file.h>
75 #include <linux/uio.h>
76 #include <linux/skb_array.h>
77 #include <linux/bpf.h>
78 #include <linux/bpf_trace.h>
79 #include <linux/mutex.h>
81 #include <linux/uaccess.h>
82 #include <linux/proc_fs.h>
84 static void tun_default_link_ksettings(struct net_device *dev,
85 struct ethtool_link_ksettings *cmd);
87 /* Uncomment to enable debugging */
88 /* #define TUN_DEBUG 1 */
93 #define tun_debug(level, tun, fmt, args...) \
96 netdev_printk(level, tun->dev, fmt, ##args); \
98 #define DBG1(level, fmt, args...) \
101 printk(level fmt, ##args); \
104 #define tun_debug(level, tun, fmt, args...) \
107 netdev_printk(level, tun->dev, fmt, ##args); \
109 #define DBG1(level, fmt, args...) \
112 printk(level fmt, ##args); \
116 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
118 /* TUN device flags */
120 /* IFF_ATTACH_QUEUE is never stored in device flags,
121 * overload it to mean fasync when stored there.
123 #define TUN_FASYNC IFF_ATTACH_QUEUE
124 /* High bits in flags field are unused. */
125 #define TUN_VNET_LE 0x80000000
126 #define TUN_VNET_BE 0x40000000
128 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
129 IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
131 #define GOODCOPY_LEN 128
133 #define FLT_EXACT_COUNT 8
135 unsigned int count; /* Number of addrs. Zero means disabled */
136 u32 mask[2]; /* Mask of the hashed addrs */
137 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
140 /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
141 * to max number of VCPUs in guest. */
142 #define MAX_TAP_QUEUES 256
143 #define MAX_TAP_FLOWS 4096
145 #define TUN_FLOW_EXPIRE (3 * HZ)
147 struct tun_pcpu_stats {
152 struct u64_stats_sync syncp;
158 /* A tun_file connects an open character device to a tuntap netdevice. It
159 * also contains all socket related structures (except sock_fprog and tap_filter)
160 * to serve as one transmit queue for tuntap device. The sock_fprog and
161 * tap_filter were kept in tun_struct since they were used for filtering for the
162 * netdevice not for a specific queue (at least I didn't see the requirement for
166 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
167 * other can only be read while rcu_read_lock or rtnl_lock is held.
171 struct socket socket;
173 struct tun_struct __rcu *tun;
174 struct fasync_struct *fasync;
175 /* only used for fasnyc */
179 unsigned int ifindex;
181 struct napi_struct napi;
183 bool napi_frags_enabled;
184 struct mutex napi_mutex; /* Protects access to the above napi */
185 struct list_head next;
186 struct tun_struct *detached;
187 struct ptr_ring tx_ring;
188 struct xdp_rxq_info xdp_rxq;
196 struct tun_flow_entry {
197 struct hlist_node hash_link;
199 struct tun_struct *tun;
204 unsigned long updated ____cacheline_aligned_in_smp;
207 #define TUN_NUM_FLOW_ENTRIES 1024
208 #define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
212 struct bpf_prog *prog;
215 /* Since the socket were moved to tun_file, to preserve the behavior of persist
216 * device, socket filter, sndbuf and vnet header size were restore when the
217 * file were attached to a persist device.
220 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
221 unsigned int numqueues;
226 struct net_device *dev;
227 netdev_features_t set_features;
228 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
234 struct tap_filter txflt;
235 struct sock_fprog fprog;
236 /* protected by rtnl lock */
237 bool filter_attached;
242 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
243 struct timer_list flow_gc_timer;
244 unsigned long ageing_time;
245 unsigned int numdisabled;
246 struct list_head disabled;
250 struct tun_pcpu_stats __percpu *pcpu_stats;
251 struct bpf_prog __rcu *xdp_prog;
252 struct tun_prog __rcu *steering_prog;
253 struct tun_prog __rcu *filter_prog;
254 struct ethtool_link_ksettings link_ksettings;
262 bool tun_is_xdp_frame(void *ptr)
264 return (unsigned long)ptr & TUN_XDP_FLAG;
266 EXPORT_SYMBOL(tun_is_xdp_frame);
268 void *tun_xdp_to_ptr(void *ptr)
270 return (void *)((unsigned long)ptr | TUN_XDP_FLAG);
272 EXPORT_SYMBOL(tun_xdp_to_ptr);
274 void *tun_ptr_to_xdp(void *ptr)
276 return (void *)((unsigned long)ptr & ~TUN_XDP_FLAG);
278 EXPORT_SYMBOL(tun_ptr_to_xdp);
280 static int tun_napi_receive(struct napi_struct *napi, int budget)
282 struct tun_file *tfile = container_of(napi, struct tun_file, napi);
283 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
284 struct sk_buff_head process_queue;
288 __skb_queue_head_init(&process_queue);
290 spin_lock(&queue->lock);
291 skb_queue_splice_tail_init(queue, &process_queue);
292 spin_unlock(&queue->lock);
294 while (received < budget && (skb = __skb_dequeue(&process_queue))) {
295 napi_gro_receive(napi, skb);
299 if (!skb_queue_empty(&process_queue)) {
300 spin_lock(&queue->lock);
301 skb_queue_splice(&process_queue, queue);
302 spin_unlock(&queue->lock);
308 static int tun_napi_poll(struct napi_struct *napi, int budget)
310 unsigned int received;
312 received = tun_napi_receive(napi, budget);
314 if (received < budget)
315 napi_complete_done(napi, received);
320 static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
321 bool napi_en, bool napi_frags)
323 tfile->napi_enabled = napi_en;
324 tfile->napi_frags_enabled = napi_en && napi_frags;
326 netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
328 napi_enable(&tfile->napi);
332 static void tun_napi_disable(struct tun_file *tfile)
334 if (tfile->napi_enabled)
335 napi_disable(&tfile->napi);
338 static void tun_napi_del(struct tun_file *tfile)
340 if (tfile->napi_enabled)
341 netif_napi_del(&tfile->napi);
344 static bool tun_napi_frags_enabled(const struct tun_file *tfile)
346 return tfile->napi_frags_enabled;
349 #ifdef CONFIG_TUN_VNET_CROSS_LE
350 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
352 return tun->flags & TUN_VNET_BE ? false :
353 virtio_legacy_is_little_endian();
356 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
358 int be = !!(tun->flags & TUN_VNET_BE);
360 if (put_user(be, argp))
366 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
370 if (get_user(be, argp))
374 tun->flags |= TUN_VNET_BE;
376 tun->flags &= ~TUN_VNET_BE;
381 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
383 return virtio_legacy_is_little_endian();
386 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
391 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
395 #endif /* CONFIG_TUN_VNET_CROSS_LE */
397 static inline bool tun_is_little_endian(struct tun_struct *tun)
399 return tun->flags & TUN_VNET_LE ||
400 tun_legacy_is_little_endian(tun);
403 static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
405 return __virtio16_to_cpu(tun_is_little_endian(tun), val);
408 static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
410 return __cpu_to_virtio16(tun_is_little_endian(tun), val);
413 static inline u32 tun_hashfn(u32 rxhash)
415 return rxhash & TUN_MASK_FLOW_ENTRIES;
418 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
420 struct tun_flow_entry *e;
422 hlist_for_each_entry_rcu(e, head, hash_link) {
423 if (e->rxhash == rxhash)
429 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
430 struct hlist_head *head,
431 u32 rxhash, u16 queue_index)
433 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
436 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
437 rxhash, queue_index);
438 e->updated = jiffies;
441 e->queue_index = queue_index;
443 hlist_add_head_rcu(&e->hash_link, head);
449 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
451 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
452 e->rxhash, e->queue_index);
453 hlist_del_rcu(&e->hash_link);
458 static void tun_flow_flush(struct tun_struct *tun)
462 spin_lock_bh(&tun->lock);
463 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
464 struct tun_flow_entry *e;
465 struct hlist_node *n;
467 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
468 tun_flow_delete(tun, e);
470 spin_unlock_bh(&tun->lock);
473 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
477 spin_lock_bh(&tun->lock);
478 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
479 struct tun_flow_entry *e;
480 struct hlist_node *n;
482 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
483 if (e->queue_index == queue_index)
484 tun_flow_delete(tun, e);
487 spin_unlock_bh(&tun->lock);
490 static void tun_flow_cleanup(struct timer_list *t)
492 struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
493 unsigned long delay = tun->ageing_time;
494 unsigned long next_timer = jiffies + delay;
495 unsigned long count = 0;
498 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
500 spin_lock(&tun->lock);
501 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
502 struct tun_flow_entry *e;
503 struct hlist_node *n;
505 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
506 unsigned long this_timer;
508 this_timer = e->updated + delay;
509 if (time_before_eq(this_timer, jiffies)) {
510 tun_flow_delete(tun, e);
514 if (time_before(this_timer, next_timer))
515 next_timer = this_timer;
520 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
521 spin_unlock(&tun->lock);
524 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
525 struct tun_file *tfile)
527 struct hlist_head *head;
528 struct tun_flow_entry *e;
529 unsigned long delay = tun->ageing_time;
530 u16 queue_index = tfile->queue_index;
532 head = &tun->flows[tun_hashfn(rxhash)];
536 e = tun_flow_find(head, rxhash);
538 /* TODO: keep queueing to old queue until it's empty? */
539 if (e->queue_index != queue_index)
540 e->queue_index = queue_index;
541 if (e->updated != jiffies)
542 e->updated = jiffies;
543 sock_rps_record_flow_hash(e->rps_rxhash);
545 spin_lock_bh(&tun->lock);
546 if (!tun_flow_find(head, rxhash) &&
547 tun->flow_count < MAX_TAP_FLOWS)
548 tun_flow_create(tun, head, rxhash, queue_index);
550 if (!timer_pending(&tun->flow_gc_timer))
551 mod_timer(&tun->flow_gc_timer,
552 round_jiffies_up(jiffies + delay));
553 spin_unlock_bh(&tun->lock);
560 * Save the hash received in the stack receive path and update the
561 * flow_hash table accordingly.
563 static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
565 if (unlikely(e->rps_rxhash != hash))
566 e->rps_rxhash = hash;
569 /* We try to identify a flow through its rxhash. The reason that
570 * we do not check rxq no. is because some cards(e.g 82599), chooses
571 * the rxq based on the txq where the last packet of the flow comes. As
572 * the userspace application move between processors, we may get a
573 * different rxq no. here.
575 static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
577 struct tun_flow_entry *e;
581 numqueues = READ_ONCE(tun->numqueues);
583 txq = __skb_get_hash_symmetric(skb);
584 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
586 tun_flow_save_rps_rxhash(e, txq);
587 txq = e->queue_index;
589 /* use multiply and shift instead of expensive divide */
590 txq = ((u64)txq * numqueues) >> 32;
596 static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
598 struct tun_prog *prog;
602 numqueues = READ_ONCE(tun->numqueues);
606 prog = rcu_dereference(tun->steering_prog);
608 ret = bpf_prog_run_clear_cb(prog->prog, skb);
610 return ret % numqueues;
613 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
614 struct net_device *sb_dev)
616 struct tun_struct *tun = netdev_priv(dev);
620 if (rcu_dereference(tun->steering_prog))
621 ret = tun_ebpf_select_queue(tun, skb);
623 ret = tun_automq_select_queue(tun, skb);
629 static inline bool tun_not_capable(struct tun_struct *tun)
631 const struct cred *cred = current_cred();
632 struct net *net = dev_net(tun->dev);
634 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
635 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
636 !ns_capable(net->user_ns, CAP_NET_ADMIN);
639 static void tun_set_real_num_queues(struct tun_struct *tun)
641 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
642 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
645 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
647 tfile->detached = tun;
648 list_add_tail(&tfile->next, &tun->disabled);
652 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
654 struct tun_struct *tun = tfile->detached;
656 tfile->detached = NULL;
657 list_del_init(&tfile->next);
662 void tun_ptr_free(void *ptr)
666 if (tun_is_xdp_frame(ptr)) {
667 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
669 xdp_return_frame(xdpf);
671 __skb_array_destroy_skb(ptr);
674 EXPORT_SYMBOL_GPL(tun_ptr_free);
676 static void tun_queue_purge(struct tun_file *tfile)
680 while ((ptr = ptr_ring_consume(&tfile->tx_ring)) != NULL)
683 skb_queue_purge(&tfile->sk.sk_write_queue);
684 skb_queue_purge(&tfile->sk.sk_error_queue);
687 static void __tun_detach(struct tun_file *tfile, bool clean)
689 struct tun_file *ntfile;
690 struct tun_struct *tun;
692 tun = rtnl_dereference(tfile->tun);
695 tun_napi_disable(tfile);
699 if (tun && !tfile->detached) {
700 u16 index = tfile->queue_index;
701 BUG_ON(index >= tun->numqueues);
703 rcu_assign_pointer(tun->tfiles[index],
704 tun->tfiles[tun->numqueues - 1]);
705 ntfile = rtnl_dereference(tun->tfiles[index]);
706 ntfile->queue_index = index;
707 rcu_assign_pointer(tun->tfiles[tun->numqueues - 1],
712 RCU_INIT_POINTER(tfile->tun, NULL);
713 sock_put(&tfile->sk);
715 tun_disable_queue(tun, tfile);
718 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
719 /* Drop read queue */
720 tun_queue_purge(tfile);
721 tun_set_real_num_queues(tun);
722 } else if (tfile->detached && clean) {
723 tun = tun_enable_queue(tfile);
724 sock_put(&tfile->sk);
728 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
729 netif_carrier_off(tun->dev);
731 if (!(tun->flags & IFF_PERSIST) &&
732 tun->dev->reg_state == NETREG_REGISTERED)
733 unregister_netdevice(tun->dev);
736 xdp_rxq_info_unreg(&tfile->xdp_rxq);
737 ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
738 sock_put(&tfile->sk);
742 static void tun_detach(struct tun_file *tfile, bool clean)
744 struct tun_struct *tun;
745 struct net_device *dev;
748 tun = rtnl_dereference(tfile->tun);
749 dev = tun ? tun->dev : NULL;
750 __tun_detach(tfile, clean);
752 netdev_state_change(dev);
756 static void tun_detach_all(struct net_device *dev)
758 struct tun_struct *tun = netdev_priv(dev);
759 struct tun_file *tfile, *tmp;
760 int i, n = tun->numqueues;
762 for (i = 0; i < n; i++) {
763 tfile = rtnl_dereference(tun->tfiles[i]);
765 tun_napi_disable(tfile);
766 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
767 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
768 RCU_INIT_POINTER(tfile->tun, NULL);
771 list_for_each_entry(tfile, &tun->disabled, next) {
772 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
773 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
774 RCU_INIT_POINTER(tfile->tun, NULL);
776 BUG_ON(tun->numqueues != 0);
779 for (i = 0; i < n; i++) {
780 tfile = rtnl_dereference(tun->tfiles[i]);
782 /* Drop read queue */
783 tun_queue_purge(tfile);
784 xdp_rxq_info_unreg(&tfile->xdp_rxq);
785 sock_put(&tfile->sk);
787 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
788 tun_enable_queue(tfile);
789 tun_queue_purge(tfile);
790 xdp_rxq_info_unreg(&tfile->xdp_rxq);
791 sock_put(&tfile->sk);
793 BUG_ON(tun->numdisabled != 0);
795 if (tun->flags & IFF_PERSIST)
796 module_put(THIS_MODULE);
799 static int tun_attach(struct tun_struct *tun, struct file *file,
800 bool skip_filter, bool napi, bool napi_frags)
802 struct tun_file *tfile = file->private_data;
803 struct net_device *dev = tun->dev;
806 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
811 if (rtnl_dereference(tfile->tun) && !tfile->detached)
815 if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
819 if (!tfile->detached &&
820 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
825 /* Re-attach the filter to persist device */
826 if (!skip_filter && (tun->filter_attached == true)) {
827 lock_sock(tfile->socket.sk);
828 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
829 release_sock(tfile->socket.sk);
834 if (!tfile->detached &&
835 ptr_ring_resize(&tfile->tx_ring, dev->tx_queue_len,
836 GFP_KERNEL, tun_ptr_free)) {
841 tfile->queue_index = tun->numqueues;
842 tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
844 if (tfile->detached) {
845 /* Re-attach detached tfile, updating XDP queue_index */
846 WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
848 if (tfile->xdp_rxq.queue_index != tfile->queue_index)
849 tfile->xdp_rxq.queue_index = tfile->queue_index;
851 /* Setup XDP RX-queue info, for new tfile getting attached */
852 err = xdp_rxq_info_reg(&tfile->xdp_rxq,
853 tun->dev, tfile->queue_index);
856 err = xdp_rxq_info_reg_mem_model(&tfile->xdp_rxq,
857 MEM_TYPE_PAGE_SHARED, NULL);
859 xdp_rxq_info_unreg(&tfile->xdp_rxq);
865 if (tfile->detached) {
866 tun_enable_queue(tfile);
868 sock_hold(&tfile->sk);
869 tun_napi_init(tun, tfile, napi, napi_frags);
872 if (rtnl_dereference(tun->xdp_prog))
873 sock_set_flag(&tfile->sk, SOCK_XDP);
875 /* device is allowed to go away first, so no need to hold extra
879 /* Publish tfile->tun and tun->tfiles only after we've fully
880 * initialized tfile; otherwise we risk using half-initialized
883 rcu_assign_pointer(tfile->tun, tun);
884 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
886 tun_set_real_num_queues(tun);
891 static struct tun_struct *tun_get(struct tun_file *tfile)
893 struct tun_struct *tun;
896 tun = rcu_dereference(tfile->tun);
904 static void tun_put(struct tun_struct *tun)
910 static void addr_hash_set(u32 *mask, const u8 *addr)
912 int n = ether_crc(ETH_ALEN, addr) >> 26;
913 mask[n >> 5] |= (1 << (n & 31));
916 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
918 int n = ether_crc(ETH_ALEN, addr) >> 26;
919 return mask[n >> 5] & (1 << (n & 31));
922 static int update_filter(struct tap_filter *filter, void __user *arg)
924 struct { u8 u[ETH_ALEN]; } *addr;
925 struct tun_filter uf;
926 int err, alen, n, nexact;
928 if (copy_from_user(&uf, arg, sizeof(uf)))
937 alen = ETH_ALEN * uf.count;
938 addr = memdup_user(arg + sizeof(uf), alen);
940 return PTR_ERR(addr);
942 /* The filter is updated without holding any locks. Which is
943 * perfectly safe. We disable it first and in the worst
944 * case we'll accept a few undesired packets. */
948 /* Use first set of addresses as an exact filter */
949 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
950 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
954 /* Remaining multicast addresses are hashed,
955 * unicast will leave the filter disabled. */
956 memset(filter->mask, 0, sizeof(filter->mask));
957 for (; n < uf.count; n++) {
958 if (!is_multicast_ether_addr(addr[n].u)) {
959 err = 0; /* no filter */
962 addr_hash_set(filter->mask, addr[n].u);
965 /* For ALLMULTI just set the mask to all ones.
966 * This overrides the mask populated above. */
967 if ((uf.flags & TUN_FLT_ALLMULTI))
968 memset(filter->mask, ~0, sizeof(filter->mask));
970 /* Now enable the filter */
972 filter->count = nexact;
974 /* Return the number of exact filters */
981 /* Returns: 0 - drop, !=0 - accept */
982 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
984 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
986 struct ethhdr *eh = (struct ethhdr *) skb->data;
990 for (i = 0; i < filter->count; i++)
991 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
994 /* Inexact match (multicast only) */
995 if (is_multicast_ether_addr(eh->h_dest))
996 return addr_hash_test(filter->mask, eh->h_dest);
1002 * Checks whether the packet is accepted or not.
1003 * Returns: 0 - drop, !=0 - accept
1005 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
1010 return run_filter(filter, skb);
1013 /* Network device part of the driver */
1015 static const struct ethtool_ops tun_ethtool_ops;
1017 /* Net device detach from fd. */
1018 static void tun_net_uninit(struct net_device *dev)
1020 tun_detach_all(dev);
1023 /* Net device open. */
1024 static int tun_net_open(struct net_device *dev)
1026 struct tun_struct *tun = netdev_priv(dev);
1029 netif_tx_start_all_queues(dev);
1031 for (i = 0; i < tun->numqueues; i++) {
1032 struct tun_file *tfile;
1034 tfile = rtnl_dereference(tun->tfiles[i]);
1035 tfile->socket.sk->sk_write_space(tfile->socket.sk);
1041 /* Net device close. */
1042 static int tun_net_close(struct net_device *dev)
1044 netif_tx_stop_all_queues(dev);
1048 /* Net device start xmit */
1049 static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
1052 if (tun->numqueues == 1 && static_branch_unlikely(&rps_needed)) {
1053 /* Select queue was not called for the skbuff, so we extract the
1054 * RPS hash and save it into the flow_table here.
1056 struct tun_flow_entry *e;
1059 rxhash = __skb_get_hash_symmetric(skb);
1060 e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash);
1062 tun_flow_save_rps_rxhash(e, rxhash);
1067 static unsigned int run_ebpf_filter(struct tun_struct *tun,
1068 struct sk_buff *skb,
1071 struct tun_prog *prog = rcu_dereference(tun->filter_prog);
1074 len = bpf_prog_run_clear_cb(prog->prog, skb);
1079 /* Net device start xmit */
1080 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
1082 struct tun_struct *tun = netdev_priv(dev);
1083 int txq = skb->queue_mapping;
1084 struct tun_file *tfile;
1088 tfile = rcu_dereference(tun->tfiles[txq]);
1090 /* Drop packet if interface is not attached */
1094 if (!rcu_dereference(tun->steering_prog))
1095 tun_automq_xmit(tun, skb);
1097 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
1101 /* Drop if the filter does not like it.
1102 * This is a noop if the filter is disabled.
1103 * Filter can be enabled only for the TAP devices. */
1104 if (!check_filter(&tun->txflt, skb))
1107 if (tfile->socket.sk->sk_filter &&
1108 sk_filter(tfile->socket.sk, skb))
1111 len = run_ebpf_filter(tun, skb, len);
1112 if (len == 0 || pskb_trim(skb, len))
1115 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
1118 skb_tx_timestamp(skb);
1120 /* Orphan the skb - required as we might hang on to it
1121 * for indefinite time.
1127 if (ptr_ring_produce(&tfile->tx_ring, skb))
1130 /* Notify and wake up reader process */
1131 if (tfile->flags & TUN_FASYNC)
1132 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1133 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1136 return NETDEV_TX_OK;
1139 this_cpu_inc(tun->pcpu_stats->tx_dropped);
1143 return NET_XMIT_DROP;
1146 static void tun_net_mclist(struct net_device *dev)
1149 * This callback is supposed to deal with mc filter in
1150 * _rx_ path and has nothing to do with the _tx_ path.
1151 * In rx path we always accept everything userspace gives us.
1155 static netdev_features_t tun_net_fix_features(struct net_device *dev,
1156 netdev_features_t features)
1158 struct tun_struct *tun = netdev_priv(dev);
1160 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
1163 static void tun_set_headroom(struct net_device *dev, int new_hr)
1165 struct tun_struct *tun = netdev_priv(dev);
1167 if (new_hr < NET_SKB_PAD)
1168 new_hr = NET_SKB_PAD;
1170 tun->align = new_hr;
1174 tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1176 u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1177 struct tun_struct *tun = netdev_priv(dev);
1178 struct tun_pcpu_stats *p;
1181 for_each_possible_cpu(i) {
1182 u64 rxpackets, rxbytes, txpackets, txbytes;
1185 p = per_cpu_ptr(tun->pcpu_stats, i);
1187 start = u64_stats_fetch_begin(&p->syncp);
1188 rxpackets = p->rx_packets;
1189 rxbytes = p->rx_bytes;
1190 txpackets = p->tx_packets;
1191 txbytes = p->tx_bytes;
1192 } while (u64_stats_fetch_retry(&p->syncp, start));
1194 stats->rx_packets += rxpackets;
1195 stats->rx_bytes += rxbytes;
1196 stats->tx_packets += txpackets;
1197 stats->tx_bytes += txbytes;
1200 rx_dropped += p->rx_dropped;
1201 rx_frame_errors += p->rx_frame_errors;
1202 tx_dropped += p->tx_dropped;
1204 stats->rx_dropped = rx_dropped;
1205 stats->rx_frame_errors = rx_frame_errors;
1206 stats->tx_dropped = tx_dropped;
1209 static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1210 struct netlink_ext_ack *extack)
1212 struct tun_struct *tun = netdev_priv(dev);
1213 struct tun_file *tfile;
1214 struct bpf_prog *old_prog;
1217 old_prog = rtnl_dereference(tun->xdp_prog);
1218 rcu_assign_pointer(tun->xdp_prog, prog);
1220 bpf_prog_put(old_prog);
1222 for (i = 0; i < tun->numqueues; i++) {
1223 tfile = rtnl_dereference(tun->tfiles[i]);
1225 sock_set_flag(&tfile->sk, SOCK_XDP);
1227 sock_reset_flag(&tfile->sk, SOCK_XDP);
1229 list_for_each_entry(tfile, &tun->disabled, next) {
1231 sock_set_flag(&tfile->sk, SOCK_XDP);
1233 sock_reset_flag(&tfile->sk, SOCK_XDP);
1239 static u32 tun_xdp_query(struct net_device *dev)
1241 struct tun_struct *tun = netdev_priv(dev);
1242 const struct bpf_prog *xdp_prog;
1244 xdp_prog = rtnl_dereference(tun->xdp_prog);
1246 return xdp_prog->aux->id;
1251 static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1253 switch (xdp->command) {
1254 case XDP_SETUP_PROG:
1255 return tun_xdp_set(dev, xdp->prog, xdp->extack);
1256 case XDP_QUERY_PROG:
1257 xdp->prog_id = tun_xdp_query(dev);
1264 static int tun_net_change_carrier(struct net_device *dev, bool new_carrier)
1267 struct tun_struct *tun = netdev_priv(dev);
1269 if (!tun->numqueues)
1272 netif_carrier_on(dev);
1274 netif_carrier_off(dev);
1279 static const struct net_device_ops tun_netdev_ops = {
1280 .ndo_uninit = tun_net_uninit,
1281 .ndo_open = tun_net_open,
1282 .ndo_stop = tun_net_close,
1283 .ndo_start_xmit = tun_net_xmit,
1284 .ndo_fix_features = tun_net_fix_features,
1285 .ndo_select_queue = tun_select_queue,
1286 .ndo_set_rx_headroom = tun_set_headroom,
1287 .ndo_get_stats64 = tun_net_get_stats64,
1288 .ndo_change_carrier = tun_net_change_carrier,
1291 static void __tun_xdp_flush_tfile(struct tun_file *tfile)
1293 /* Notify and wake up reader process */
1294 if (tfile->flags & TUN_FASYNC)
1295 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1296 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1299 static int tun_xdp_xmit(struct net_device *dev, int n,
1300 struct xdp_frame **frames, u32 flags)
1302 struct tun_struct *tun = netdev_priv(dev);
1303 struct tun_file *tfile;
1309 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
1315 numqueues = READ_ONCE(tun->numqueues);
1318 return -ENXIO; /* Caller will free/return all frames */
1321 tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1323 if (unlikely(!tfile))
1326 spin_lock(&tfile->tx_ring.producer_lock);
1327 for (i = 0; i < n; i++) {
1328 struct xdp_frame *xdp = frames[i];
1329 /* Encode the XDP flag into lowest bit for consumer to differ
1330 * XDP buffer from sk_buff.
1332 void *frame = tun_xdp_to_ptr(xdp);
1334 if (__ptr_ring_produce(&tfile->tx_ring, frame)) {
1335 this_cpu_inc(tun->pcpu_stats->tx_dropped);
1336 xdp_return_frame_rx_napi(xdp);
1340 spin_unlock(&tfile->tx_ring.producer_lock);
1342 if (flags & XDP_XMIT_FLUSH)
1343 __tun_xdp_flush_tfile(tfile);
1349 static int tun_xdp_tx(struct net_device *dev, struct xdp_buff *xdp)
1351 struct xdp_frame *frame = convert_to_xdp_frame(xdp);
1353 if (unlikely(!frame))
1356 return tun_xdp_xmit(dev, 1, &frame, XDP_XMIT_FLUSH);
1359 static const struct net_device_ops tap_netdev_ops = {
1360 .ndo_uninit = tun_net_uninit,
1361 .ndo_open = tun_net_open,
1362 .ndo_stop = tun_net_close,
1363 .ndo_start_xmit = tun_net_xmit,
1364 .ndo_fix_features = tun_net_fix_features,
1365 .ndo_set_rx_mode = tun_net_mclist,
1366 .ndo_set_mac_address = eth_mac_addr,
1367 .ndo_validate_addr = eth_validate_addr,
1368 .ndo_select_queue = tun_select_queue,
1369 .ndo_features_check = passthru_features_check,
1370 .ndo_set_rx_headroom = tun_set_headroom,
1371 .ndo_get_stats64 = tun_net_get_stats64,
1373 .ndo_xdp_xmit = tun_xdp_xmit,
1374 .ndo_change_carrier = tun_net_change_carrier,
1377 static void tun_flow_init(struct tun_struct *tun)
1381 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
1382 INIT_HLIST_HEAD(&tun->flows[i]);
1384 tun->ageing_time = TUN_FLOW_EXPIRE;
1385 timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1386 mod_timer(&tun->flow_gc_timer,
1387 round_jiffies_up(jiffies + tun->ageing_time));
1390 static void tun_flow_uninit(struct tun_struct *tun)
1392 del_timer_sync(&tun->flow_gc_timer);
1393 tun_flow_flush(tun);
1397 #define MAX_MTU 65535
1399 /* Initialize net device. */
1400 static void tun_net_init(struct net_device *dev)
1402 struct tun_struct *tun = netdev_priv(dev);
1404 switch (tun->flags & TUN_TYPE_MASK) {
1406 dev->netdev_ops = &tun_netdev_ops;
1408 /* Point-to-Point TUN Device */
1409 dev->hard_header_len = 0;
1413 /* Zero header length */
1414 dev->type = ARPHRD_NONE;
1415 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
1419 dev->netdev_ops = &tap_netdev_ops;
1420 /* Ethernet TAP Device */
1422 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1423 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
1425 eth_hw_addr_random(dev);
1430 dev->min_mtu = MIN_MTU;
1431 dev->max_mtu = MAX_MTU - dev->hard_header_len;
1434 static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
1436 struct sock *sk = tfile->socket.sk;
1438 return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
1441 /* Character device part */
1444 static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
1446 struct tun_file *tfile = file->private_data;
1447 struct tun_struct *tun = tun_get(tfile);
1454 sk = tfile->socket.sk;
1456 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
1458 poll_wait(file, sk_sleep(sk), wait);
1460 if (!ptr_ring_empty(&tfile->tx_ring))
1461 mask |= EPOLLIN | EPOLLRDNORM;
1463 /* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
1464 * guarantee EPOLLOUT to be raised by either here or
1465 * tun_sock_write_space(). Then process could get notification
1466 * after it writes to a down device and meets -EIO.
1468 if (tun_sock_writeable(tun, tfile) ||
1469 (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1470 tun_sock_writeable(tun, tfile)))
1471 mask |= EPOLLOUT | EPOLLWRNORM;
1473 if (tun->dev->reg_state != NETREG_REGISTERED)
1480 static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
1482 const struct iov_iter *it)
1484 struct sk_buff *skb;
1489 if (it->nr_segs > MAX_SKB_FRAGS + 1)
1490 return ERR_PTR(-ENOMEM);
1493 skb = napi_get_frags(&tfile->napi);
1496 return ERR_PTR(-ENOMEM);
1498 linear = iov_iter_single_seg_count(it);
1499 err = __skb_grow(skb, linear);
1504 skb->data_len = len - linear;
1505 skb->truesize += skb->data_len;
1507 for (i = 1; i < it->nr_segs; i++) {
1508 size_t fragsz = it->iov[i].iov_len;
1512 if (fragsz == 0 || fragsz > PAGE_SIZE) {
1516 frag = netdev_alloc_frag(fragsz);
1521 page = virt_to_head_page(frag);
1522 skb_fill_page_desc(skb, i - 1, page,
1523 frag - page_address(page), fragsz);
1528 /* frees skb and all frags allocated with napi_alloc_frag() */
1529 napi_free_frags(&tfile->napi);
1530 return ERR_PTR(err);
1533 /* prepad is the amount to reserve at front. len is length after that.
1534 * linear is a hint as to how much to copy (usually headers). */
1535 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
1536 size_t prepad, size_t len,
1537 size_t linear, int noblock)
1539 struct sock *sk = tfile->socket.sk;
1540 struct sk_buff *skb;
1543 /* Under a page? Don't bother with paged skb. */
1544 if (prepad + len < PAGE_SIZE || !linear)
1547 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
1550 return ERR_PTR(err);
1552 skb_reserve(skb, prepad);
1553 skb_put(skb, linear);
1554 skb->data_len = len - linear;
1555 skb->len += len - linear;
1560 static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
1561 struct sk_buff *skb, int more)
1563 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1564 struct sk_buff_head process_queue;
1565 u32 rx_batched = tun->rx_batched;
1568 if (!rx_batched || (!more && skb_queue_empty(queue))) {
1570 skb_record_rx_queue(skb, tfile->queue_index);
1571 netif_receive_skb(skb);
1576 spin_lock(&queue->lock);
1577 if (!more || skb_queue_len(queue) == rx_batched) {
1578 __skb_queue_head_init(&process_queue);
1579 skb_queue_splice_tail_init(queue, &process_queue);
1582 __skb_queue_tail(queue, skb);
1584 spin_unlock(&queue->lock);
1587 struct sk_buff *nskb;
1590 while ((nskb = __skb_dequeue(&process_queue))) {
1591 skb_record_rx_queue(nskb, tfile->queue_index);
1592 netif_receive_skb(nskb);
1594 skb_record_rx_queue(skb, tfile->queue_index);
1595 netif_receive_skb(skb);
1600 static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
1601 int len, int noblock, bool zerocopy)
1603 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
1606 if (tfile->socket.sk->sk_sndbuf != INT_MAX)
1615 if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
1616 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
1622 static struct sk_buff *__tun_build_skb(struct page_frag *alloc_frag, char *buf,
1623 int buflen, int len, int pad)
1625 struct sk_buff *skb = build_skb(buf, buflen);
1628 return ERR_PTR(-ENOMEM);
1630 skb_reserve(skb, pad);
1633 get_page(alloc_frag->page);
1634 alloc_frag->offset += buflen;
1639 static int tun_xdp_act(struct tun_struct *tun, struct bpf_prog *xdp_prog,
1640 struct xdp_buff *xdp, u32 act)
1646 err = xdp_do_redirect(tun->dev, xdp, xdp_prog);
1651 err = tun_xdp_tx(tun->dev, xdp);
1658 bpf_warn_invalid_xdp_action(act);
1661 trace_xdp_exception(tun->dev, xdp_prog, act);
1664 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1671 static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1672 struct tun_file *tfile,
1673 struct iov_iter *from,
1674 struct virtio_net_hdr *hdr,
1675 int len, int *skb_xdp)
1677 struct page_frag *alloc_frag = ¤t->task_frag;
1678 struct bpf_prog *xdp_prog;
1679 int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1682 int pad = TUN_RX_PAD;
1686 xdp_prog = rcu_dereference(tun->xdp_prog);
1688 pad += XDP_PACKET_HEADROOM;
1689 buflen += SKB_DATA_ALIGN(len + pad);
1692 alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
1693 if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
1694 return ERR_PTR(-ENOMEM);
1696 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1697 copied = copy_page_from_iter(alloc_frag->page,
1698 alloc_frag->offset + pad,
1701 return ERR_PTR(-EFAULT);
1703 /* There's a small window that XDP may be set after the check
1704 * of xdp_prog above, this should be rare and for simplicity
1705 * we do XDP on skb in case the headroom is not enough.
1707 if (hdr->gso_type || !xdp_prog) {
1709 return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
1716 xdp_prog = rcu_dereference(tun->xdp_prog);
1718 struct xdp_buff xdp;
1721 xdp.data_hard_start = buf;
1722 xdp.data = buf + pad;
1723 xdp_set_data_meta_invalid(&xdp);
1724 xdp.data_end = xdp.data + len;
1725 xdp.rxq = &tfile->xdp_rxq;
1727 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1728 if (act == XDP_REDIRECT || act == XDP_TX) {
1729 get_page(alloc_frag->page);
1730 alloc_frag->offset += buflen;
1732 err = tun_xdp_act(tun, xdp_prog, &xdp, act);
1735 if (err == XDP_REDIRECT)
1737 if (err != XDP_PASS)
1740 pad = xdp.data - xdp.data_hard_start;
1741 len = xdp.data_end - xdp.data;
1746 return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
1749 put_page(alloc_frag->page);
1756 /* Get packet from user space buffer */
1757 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1758 void *msg_control, struct iov_iter *from,
1759 int noblock, bool more)
1761 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1762 struct sk_buff *skb;
1763 size_t total_len = iov_iter_count(from);
1764 size_t len = total_len, align = tun->align, linear;
1765 struct virtio_net_hdr gso = { 0 };
1766 struct tun_pcpu_stats *stats;
1769 bool zerocopy = false;
1773 bool frags = tun_napi_frags_enabled(tfile);
1775 if (!(tun->flags & IFF_NO_PI)) {
1776 if (len < sizeof(pi))
1780 if (!copy_from_iter_full(&pi, sizeof(pi), from))
1784 if (tun->flags & IFF_VNET_HDR) {
1785 int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1787 if (len < vnet_hdr_sz)
1791 if (!copy_from_iter_full(&gso, sizeof(gso), from))
1794 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1795 tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
1796 gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
1798 if (tun16_to_cpu(tun, gso.hdr_len) > len)
1800 iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1803 if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1804 align += NET_IP_ALIGN;
1805 if (unlikely(len < ETH_HLEN ||
1806 (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1810 good_linear = SKB_MAX_HEAD(align);
1813 struct iov_iter i = *from;
1815 /* There are 256 bytes to be copied in skb, so there is
1816 * enough room for skb expand head in case it is used.
1817 * The rest of the buffer is mapped from userspace.
1819 copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
1820 if (copylen > good_linear)
1821 copylen = good_linear;
1823 iov_iter_advance(&i, copylen);
1824 if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
1828 if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
1829 /* For the packet that is not easy to be processed
1830 * (e.g gso or jumbo packet), we will do it at after
1831 * skb was created with generic XDP routine.
1833 skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
1835 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1836 return PTR_ERR(skb);
1843 if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
1844 linear = good_linear;
1846 linear = tun16_to_cpu(tun, gso.hdr_len);
1850 mutex_lock(&tfile->napi_mutex);
1851 skb = tun_napi_alloc_frags(tfile, copylen, from);
1852 /* tun_napi_alloc_frags() enforces a layout for the skb.
1853 * If zerocopy is enabled, then this layout will be
1854 * overwritten by zerocopy_sg_from_iter().
1858 skb = tun_alloc_skb(tfile, align, copylen, linear,
1863 if (PTR_ERR(skb) != -EAGAIN)
1864 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1866 mutex_unlock(&tfile->napi_mutex);
1867 return PTR_ERR(skb);
1871 err = zerocopy_sg_from_iter(skb, from);
1873 err = skb_copy_datagram_from_iter(skb, 0, from, len);
1878 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1881 tfile->napi.skb = NULL;
1882 mutex_unlock(&tfile->napi_mutex);
1889 if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1890 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1893 tfile->napi.skb = NULL;
1894 mutex_unlock(&tfile->napi_mutex);
1900 switch (tun->flags & TUN_TYPE_MASK) {
1902 if (tun->flags & IFF_NO_PI) {
1903 u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
1905 switch (ip_version) {
1907 pi.proto = htons(ETH_P_IP);
1910 pi.proto = htons(ETH_P_IPV6);
1913 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1919 skb_reset_mac_header(skb);
1920 skb->protocol = pi.proto;
1921 skb->dev = tun->dev;
1925 skb->protocol = eth_type_trans(skb, tun->dev);
1929 /* copy skb_ubuf_info for callback when skb has no error */
1931 skb_shinfo(skb)->destructor_arg = msg_control;
1932 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1933 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1934 } else if (msg_control) {
1935 struct ubuf_info *uarg = msg_control;
1936 uarg->callback(uarg, false);
1939 skb_reset_network_header(skb);
1940 skb_probe_transport_header(skb);
1943 struct bpf_prog *xdp_prog;
1948 xdp_prog = rcu_dereference(tun->xdp_prog);
1950 ret = do_xdp_generic(xdp_prog, skb);
1951 if (ret != XDP_PASS) {
1961 /* Compute the costly rx hash only if needed for flow updates.
1962 * We may get a very small possibility of OOO during switching, not
1963 * worth to optimize.
1965 if (!rcu_access_pointer(tun->steering_prog) && tun->numqueues > 1 &&
1967 rxhash = __skb_get_hash_symmetric(skb);
1970 if (unlikely(!(tun->dev->flags & IFF_UP))) {
1977 /* Exercise flow dissector code path. */
1978 u32 headlen = eth_get_headlen(tun->dev, skb->data,
1981 if (unlikely(headlen > skb_headlen(skb))) {
1982 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1983 napi_free_frags(&tfile->napi);
1985 mutex_unlock(&tfile->napi_mutex);
1991 napi_gro_frags(&tfile->napi);
1993 mutex_unlock(&tfile->napi_mutex);
1994 } else if (tfile->napi_enabled) {
1995 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1998 spin_lock_bh(&queue->lock);
1999 __skb_queue_tail(queue, skb);
2000 queue_len = skb_queue_len(queue);
2001 spin_unlock(&queue->lock);
2003 if (!more || queue_len > NAPI_POLL_WEIGHT)
2004 napi_schedule(&tfile->napi);
2007 } else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
2008 tun_rx_batched(tun, tfile, skb, more);
2014 stats = get_cpu_ptr(tun->pcpu_stats);
2015 u64_stats_update_begin(&stats->syncp);
2016 stats->rx_packets++;
2017 stats->rx_bytes += len;
2018 u64_stats_update_end(&stats->syncp);
2022 tun_flow_update(tun, rxhash, tfile);
2027 static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
2029 struct file *file = iocb->ki_filp;
2030 struct tun_file *tfile = file->private_data;
2031 struct tun_struct *tun = tun_get(tfile);
2037 result = tun_get_user(tun, tfile, NULL, from,
2038 file->f_flags & O_NONBLOCK, false);
2044 static ssize_t tun_put_user_xdp(struct tun_struct *tun,
2045 struct tun_file *tfile,
2046 struct xdp_frame *xdp_frame,
2047 struct iov_iter *iter)
2049 int vnet_hdr_sz = 0;
2050 size_t size = xdp_frame->len;
2051 struct tun_pcpu_stats *stats;
2054 if (tun->flags & IFF_VNET_HDR) {
2055 struct virtio_net_hdr gso = { 0 };
2057 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2058 if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
2060 if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
2063 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2066 ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
2068 stats = get_cpu_ptr(tun->pcpu_stats);
2069 u64_stats_update_begin(&stats->syncp);
2070 stats->tx_packets++;
2071 stats->tx_bytes += ret;
2072 u64_stats_update_end(&stats->syncp);
2073 put_cpu_ptr(tun->pcpu_stats);
2078 /* Put packet to the user space buffer */
2079 static ssize_t tun_put_user(struct tun_struct *tun,
2080 struct tun_file *tfile,
2081 struct sk_buff *skb,
2082 struct iov_iter *iter)
2084 struct tun_pi pi = { 0, skb->protocol };
2085 struct tun_pcpu_stats *stats;
2087 int vlan_offset = 0;
2089 int vnet_hdr_sz = 0;
2091 if (skb_vlan_tag_present(skb))
2092 vlan_hlen = VLAN_HLEN;
2094 if (tun->flags & IFF_VNET_HDR)
2095 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2097 total = skb->len + vlan_hlen + vnet_hdr_sz;
2099 if (!(tun->flags & IFF_NO_PI)) {
2100 if (iov_iter_count(iter) < sizeof(pi))
2103 total += sizeof(pi);
2104 if (iov_iter_count(iter) < total) {
2105 /* Packet will be striped */
2106 pi.flags |= TUN_PKT_STRIP;
2109 if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
2114 struct virtio_net_hdr gso;
2116 if (iov_iter_count(iter) < vnet_hdr_sz)
2119 if (virtio_net_hdr_from_skb(skb, &gso,
2120 tun_is_little_endian(tun), true,
2122 struct skb_shared_info *sinfo = skb_shinfo(skb);
2123 pr_err("unexpected GSO type: "
2124 "0x%x, gso_size %d, hdr_len %d\n",
2125 sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
2126 tun16_to_cpu(tun, gso.hdr_len));
2127 print_hex_dump(KERN_ERR, "tun: ",
2130 min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
2135 if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
2138 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2145 veth.h_vlan_proto = skb->vlan_proto;
2146 veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
2148 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
2150 ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
2151 if (ret || !iov_iter_count(iter))
2154 ret = copy_to_iter(&veth, sizeof(veth), iter);
2155 if (ret != sizeof(veth) || !iov_iter_count(iter))
2159 skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
2162 /* caller is in process context, */
2163 stats = get_cpu_ptr(tun->pcpu_stats);
2164 u64_stats_update_begin(&stats->syncp);
2165 stats->tx_packets++;
2166 stats->tx_bytes += skb->len + vlan_hlen;
2167 u64_stats_update_end(&stats->syncp);
2168 put_cpu_ptr(tun->pcpu_stats);
2173 static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
2175 DECLARE_WAITQUEUE(wait, current);
2179 ptr = ptr_ring_consume(&tfile->tx_ring);
2187 add_wait_queue(&tfile->wq.wait, &wait);
2190 set_current_state(TASK_INTERRUPTIBLE);
2191 ptr = ptr_ring_consume(&tfile->tx_ring);
2194 if (signal_pending(current)) {
2195 error = -ERESTARTSYS;
2198 if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
2206 __set_current_state(TASK_RUNNING);
2207 remove_wait_queue(&tfile->wq.wait, &wait);
2214 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
2215 struct iov_iter *to,
2216 int noblock, void *ptr)
2221 tun_debug(KERN_INFO, tun, "tun_do_read\n");
2223 if (!iov_iter_count(to)) {
2229 /* Read frames from ring */
2230 ptr = tun_ring_recv(tfile, noblock, &err);
2235 if (tun_is_xdp_frame(ptr)) {
2236 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2238 ret = tun_put_user_xdp(tun, tfile, xdpf, to);
2239 xdp_return_frame(xdpf);
2241 struct sk_buff *skb = ptr;
2243 ret = tun_put_user(tun, tfile, skb, to);
2244 if (unlikely(ret < 0))
2253 static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
2255 struct file *file = iocb->ki_filp;
2256 struct tun_file *tfile = file->private_data;
2257 struct tun_struct *tun = tun_get(tfile);
2258 ssize_t len = iov_iter_count(to), ret;
2262 ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
2263 ret = min_t(ssize_t, ret, len);
2270 static void tun_prog_free(struct rcu_head *rcu)
2272 struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
2274 bpf_prog_destroy(prog->prog);
2278 static int __tun_set_ebpf(struct tun_struct *tun,
2279 struct tun_prog __rcu **prog_p,
2280 struct bpf_prog *prog)
2282 struct tun_prog *old, *new = NULL;
2285 new = kmalloc(sizeof(*new), GFP_KERNEL);
2291 spin_lock_bh(&tun->lock);
2292 old = rcu_dereference_protected(*prog_p,
2293 lockdep_is_held(&tun->lock));
2294 rcu_assign_pointer(*prog_p, new);
2295 spin_unlock_bh(&tun->lock);
2298 call_rcu(&old->rcu, tun_prog_free);
2303 static void tun_free_netdev(struct net_device *dev)
2305 struct tun_struct *tun = netdev_priv(dev);
2307 BUG_ON(!(list_empty(&tun->disabled)));
2308 free_percpu(tun->pcpu_stats);
2309 tun_flow_uninit(tun);
2310 security_tun_dev_free_security(tun->security);
2311 __tun_set_ebpf(tun, &tun->steering_prog, NULL);
2312 __tun_set_ebpf(tun, &tun->filter_prog, NULL);
2315 static void tun_setup(struct net_device *dev)
2317 struct tun_struct *tun = netdev_priv(dev);
2319 tun->owner = INVALID_UID;
2320 tun->group = INVALID_GID;
2321 tun_default_link_ksettings(dev, &tun->link_ksettings);
2323 dev->ethtool_ops = &tun_ethtool_ops;
2324 dev->needs_free_netdev = true;
2325 dev->priv_destructor = tun_free_netdev;
2326 /* We prefer our own queue length */
2327 dev->tx_queue_len = TUN_READQ_SIZE;
2330 /* Trivial set of netlink ops to allow deleting tun or tap
2331 * device with netlink.
2333 static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2334 struct netlink_ext_ack *extack)
2336 NL_SET_ERR_MSG(extack,
2337 "tun/tap creation via rtnetlink is not supported.");
2341 static size_t tun_get_size(const struct net_device *dev)
2343 BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
2344 BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
2346 return nla_total_size(sizeof(uid_t)) + /* OWNER */
2347 nla_total_size(sizeof(gid_t)) + /* GROUP */
2348 nla_total_size(sizeof(u8)) + /* TYPE */
2349 nla_total_size(sizeof(u8)) + /* PI */
2350 nla_total_size(sizeof(u8)) + /* VNET_HDR */
2351 nla_total_size(sizeof(u8)) + /* PERSIST */
2352 nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
2353 nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
2354 nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
2358 static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
2360 struct tun_struct *tun = netdev_priv(dev);
2362 if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
2363 goto nla_put_failure;
2364 if (uid_valid(tun->owner) &&
2365 nla_put_u32(skb, IFLA_TUN_OWNER,
2366 from_kuid_munged(current_user_ns(), tun->owner)))
2367 goto nla_put_failure;
2368 if (gid_valid(tun->group) &&
2369 nla_put_u32(skb, IFLA_TUN_GROUP,
2370 from_kgid_munged(current_user_ns(), tun->group)))
2371 goto nla_put_failure;
2372 if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
2373 goto nla_put_failure;
2374 if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
2375 goto nla_put_failure;
2376 if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
2377 goto nla_put_failure;
2378 if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
2379 !!(tun->flags & IFF_MULTI_QUEUE)))
2380 goto nla_put_failure;
2381 if (tun->flags & IFF_MULTI_QUEUE) {
2382 if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
2383 goto nla_put_failure;
2384 if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
2386 goto nla_put_failure;
2395 static struct rtnl_link_ops tun_link_ops __read_mostly = {
2397 .priv_size = sizeof(struct tun_struct),
2399 .validate = tun_validate,
2400 .get_size = tun_get_size,
2401 .fill_info = tun_fill_info,
2404 static void tun_sock_write_space(struct sock *sk)
2406 struct tun_file *tfile;
2407 wait_queue_head_t *wqueue;
2409 if (!sock_writeable(sk))
2412 if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
2415 wqueue = sk_sleep(sk);
2416 if (wqueue && waitqueue_active(wqueue))
2417 wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
2418 EPOLLWRNORM | EPOLLWRBAND);
2420 tfile = container_of(sk, struct tun_file, sk);
2421 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
2424 static void tun_put_page(struct tun_page *tpage)
2427 __page_frag_cache_drain(tpage->page, tpage->count);
2430 static int tun_xdp_one(struct tun_struct *tun,
2431 struct tun_file *tfile,
2432 struct xdp_buff *xdp, int *flush,
2433 struct tun_page *tpage)
2435 unsigned int datasize = xdp->data_end - xdp->data;
2436 struct tun_xdp_hdr *hdr = xdp->data_hard_start;
2437 struct virtio_net_hdr *gso = &hdr->gso;
2438 struct tun_pcpu_stats *stats;
2439 struct bpf_prog *xdp_prog;
2440 struct sk_buff *skb = NULL;
2441 u32 rxhash = 0, act;
2442 int buflen = hdr->buflen;
2444 bool skb_xdp = false;
2447 xdp_prog = rcu_dereference(tun->xdp_prog);
2449 if (gso->gso_type) {
2453 xdp_set_data_meta_invalid(xdp);
2454 xdp->rxq = &tfile->xdp_rxq;
2456 act = bpf_prog_run_xdp(xdp_prog, xdp);
2457 err = tun_xdp_act(tun, xdp_prog, xdp, act);
2459 put_page(virt_to_head_page(xdp->data));
2472 page = virt_to_head_page(xdp->data);
2473 if (tpage->page == page) {
2476 tun_put_page(tpage);
2485 skb = build_skb(xdp->data_hard_start, buflen);
2491 skb_reserve(skb, xdp->data - xdp->data_hard_start);
2492 skb_put(skb, xdp->data_end - xdp->data);
2494 if (virtio_net_hdr_to_skb(skb, gso, tun_is_little_endian(tun))) {
2495 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
2501 skb->protocol = eth_type_trans(skb, tun->dev);
2502 skb_reset_network_header(skb);
2503 skb_probe_transport_header(skb);
2506 err = do_xdp_generic(xdp_prog, skb);
2507 if (err != XDP_PASS)
2511 if (!rcu_dereference(tun->steering_prog) && tun->numqueues > 1 &&
2513 rxhash = __skb_get_hash_symmetric(skb);
2515 skb_record_rx_queue(skb, tfile->queue_index);
2516 netif_receive_skb(skb);
2518 /* No need for get_cpu_ptr() here since this function is
2519 * always called with bh disabled
2521 stats = this_cpu_ptr(tun->pcpu_stats);
2522 u64_stats_update_begin(&stats->syncp);
2523 stats->rx_packets++;
2524 stats->rx_bytes += datasize;
2525 u64_stats_update_end(&stats->syncp);
2528 tun_flow_update(tun, rxhash, tfile);
2534 static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
2537 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2538 struct tun_struct *tun = tun_get(tfile);
2539 struct tun_msg_ctl *ctl = m->msg_control;
2540 struct xdp_buff *xdp;
2545 if (ctl && (ctl->type == TUN_MSG_PTR)) {
2546 struct tun_page tpage;
2550 memset(&tpage, 0, sizeof(tpage));
2555 for (i = 0; i < n; i++) {
2556 xdp = &((struct xdp_buff *)ctl->ptr)[i];
2557 tun_xdp_one(tun, tfile, xdp, &flush, &tpage);
2566 tun_put_page(&tpage);
2572 ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
2573 m->msg_flags & MSG_DONTWAIT,
2574 m->msg_flags & MSG_MORE);
2580 static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
2583 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2584 struct tun_struct *tun = tun_get(tfile);
2585 void *ptr = m->msg_control;
2593 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
2597 if (flags & MSG_ERRQUEUE) {
2598 ret = sock_recv_errqueue(sock->sk, m, total_len,
2599 SOL_PACKET, TUN_TX_TIMESTAMP);
2602 ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
2603 if (ret > (ssize_t)total_len) {
2604 m->msg_flags |= MSG_TRUNC;
2605 ret = flags & MSG_TRUNC ? ret : total_len;
2618 static int tun_ptr_peek_len(void *ptr)
2621 if (tun_is_xdp_frame(ptr)) {
2622 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2626 return __skb_array_len_with_tag(ptr);
2632 static int tun_peek_len(struct socket *sock)
2634 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2635 struct tun_struct *tun;
2638 tun = tun_get(tfile);
2642 ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
2648 /* Ops structure to mimic raw sockets with tun */
2649 static const struct proto_ops tun_socket_ops = {
2650 .peek_len = tun_peek_len,
2651 .sendmsg = tun_sendmsg,
2652 .recvmsg = tun_recvmsg,
2655 static struct proto tun_proto = {
2657 .owner = THIS_MODULE,
2658 .obj_size = sizeof(struct tun_file),
2661 static int tun_flags(struct tun_struct *tun)
2663 return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2666 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2669 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2670 return sprintf(buf, "0x%x\n", tun_flags(tun));
2673 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2676 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2677 return uid_valid(tun->owner)?
2678 sprintf(buf, "%u\n",
2679 from_kuid_munged(current_user_ns(), tun->owner)):
2680 sprintf(buf, "-1\n");
2683 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2686 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2687 return gid_valid(tun->group) ?
2688 sprintf(buf, "%u\n",
2689 from_kgid_munged(current_user_ns(), tun->group)):
2690 sprintf(buf, "-1\n");
2693 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2694 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2695 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2697 static struct attribute *tun_dev_attrs[] = {
2698 &dev_attr_tun_flags.attr,
2699 &dev_attr_owner.attr,
2700 &dev_attr_group.attr,
2704 static const struct attribute_group tun_attr_group = {
2705 .attrs = tun_dev_attrs
2708 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
2710 struct tun_struct *tun;
2711 struct tun_file *tfile = file->private_data;
2712 struct net_device *dev;
2715 if (tfile->detached)
2718 if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
2719 if (!capable(CAP_NET_ADMIN))
2722 if (!(ifr->ifr_flags & IFF_NAPI) ||
2723 (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
2727 dev = __dev_get_by_name(net, ifr->ifr_name);
2729 if (ifr->ifr_flags & IFF_TUN_EXCL)
2731 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
2732 tun = netdev_priv(dev);
2733 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
2734 tun = netdev_priv(dev);
2738 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
2739 !!(tun->flags & IFF_MULTI_QUEUE))
2742 if (tun_not_capable(tun))
2744 err = security_tun_dev_open(tun->security);
2748 err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
2749 ifr->ifr_flags & IFF_NAPI,
2750 ifr->ifr_flags & IFF_NAPI_FRAGS);
2754 if (tun->flags & IFF_MULTI_QUEUE &&
2755 (tun->numqueues + tun->numdisabled > 1)) {
2756 /* One or more queue has already been attached, no need
2757 * to initialize the device again.
2759 netdev_state_change(dev);
2763 tun->flags = (tun->flags & ~TUN_FEATURES) |
2764 (ifr->ifr_flags & TUN_FEATURES);
2766 netdev_state_change(dev);
2769 unsigned long flags = 0;
2770 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2773 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2775 err = security_tun_dev_create();
2780 if (ifr->ifr_flags & IFF_TUN) {
2784 } else if (ifr->ifr_flags & IFF_TAP) {
2792 name = ifr->ifr_name;
2794 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2795 NET_NAME_UNKNOWN, tun_setup, queues,
2800 err = dev_get_valid_name(net, dev, name);
2804 dev_net_set(dev, net);
2805 dev->rtnl_link_ops = &tun_link_ops;
2806 dev->ifindex = tfile->ifindex;
2807 dev->sysfs_groups[0] = &tun_attr_group;
2809 tun = netdev_priv(dev);
2812 tun->txflt.count = 0;
2813 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
2815 tun->align = NET_SKB_PAD;
2816 tun->filter_attached = false;
2817 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
2818 tun->rx_batched = 0;
2819 RCU_INIT_POINTER(tun->steering_prog, NULL);
2821 tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2822 if (!tun->pcpu_stats) {
2827 spin_lock_init(&tun->lock);
2829 err = security_tun_dev_alloc_security(&tun->security);
2836 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
2837 TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
2838 NETIF_F_HW_VLAN_STAG_TX;
2839 dev->features = dev->hw_features | NETIF_F_LLTX;
2840 dev->vlan_features = dev->features &
2841 ~(NETIF_F_HW_VLAN_CTAG_TX |
2842 NETIF_F_HW_VLAN_STAG_TX);
2844 tun->flags = (tun->flags & ~TUN_FEATURES) |
2845 (ifr->ifr_flags & TUN_FEATURES);
2847 INIT_LIST_HEAD(&tun->disabled);
2848 err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI,
2849 ifr->ifr_flags & IFF_NAPI_FRAGS);
2853 err = register_netdevice(tun->dev);
2858 netif_carrier_on(tun->dev);
2860 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
2862 /* Make sure persistent devices do not get stuck in
2865 if (netif_running(tun->dev))
2866 netif_tx_wake_all_queues(tun->dev);
2868 strcpy(ifr->ifr_name, tun->dev->name);
2872 tun_detach_all(dev);
2873 /* register_netdevice() already called tun_free_netdev() */
2877 tun_flow_uninit(tun);
2878 security_tun_dev_free_security(tun->security);
2880 free_percpu(tun->pcpu_stats);
2886 static void tun_get_iff(struct tun_struct *tun, struct ifreq *ifr)
2888 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2890 strcpy(ifr->ifr_name, tun->dev->name);
2892 ifr->ifr_flags = tun_flags(tun);
2896 /* This is like a cut-down ethtool ops, except done via tun fd so no
2897 * privs required. */
2898 static int set_offload(struct tun_struct *tun, unsigned long arg)
2900 netdev_features_t features = 0;
2902 if (arg & TUN_F_CSUM) {
2903 features |= NETIF_F_HW_CSUM;
2906 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
2907 if (arg & TUN_F_TSO_ECN) {
2908 features |= NETIF_F_TSO_ECN;
2909 arg &= ~TUN_F_TSO_ECN;
2911 if (arg & TUN_F_TSO4)
2912 features |= NETIF_F_TSO;
2913 if (arg & TUN_F_TSO6)
2914 features |= NETIF_F_TSO6;
2915 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
2921 /* This gives the user a way to test for new features in future by
2922 * trying to set them. */
2926 tun->set_features = features;
2927 tun->dev->wanted_features &= ~TUN_USER_FEATURES;
2928 tun->dev->wanted_features |= features;
2929 netdev_update_features(tun->dev);
2934 static void tun_detach_filter(struct tun_struct *tun, int n)
2937 struct tun_file *tfile;
2939 for (i = 0; i < n; i++) {
2940 tfile = rtnl_dereference(tun->tfiles[i]);
2941 lock_sock(tfile->socket.sk);
2942 sk_detach_filter(tfile->socket.sk);
2943 release_sock(tfile->socket.sk);
2946 tun->filter_attached = false;
2949 static int tun_attach_filter(struct tun_struct *tun)
2952 struct tun_file *tfile;
2954 for (i = 0; i < tun->numqueues; i++) {
2955 tfile = rtnl_dereference(tun->tfiles[i]);
2956 lock_sock(tfile->socket.sk);
2957 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
2958 release_sock(tfile->socket.sk);
2960 tun_detach_filter(tun, i);
2965 tun->filter_attached = true;
2969 static void tun_set_sndbuf(struct tun_struct *tun)
2971 struct tun_file *tfile;
2974 for (i = 0; i < tun->numqueues; i++) {
2975 tfile = rtnl_dereference(tun->tfiles[i]);
2976 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2980 static int tun_set_queue(struct file *file, struct ifreq *ifr)
2982 struct tun_file *tfile = file->private_data;
2983 struct tun_struct *tun;
2988 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
2989 tun = tfile->detached;
2994 ret = security_tun_dev_attach_queue(tun->security);
2997 ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
2998 tun->flags & IFF_NAPI_FRAGS);
2999 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
3000 tun = rtnl_dereference(tfile->tun);
3001 if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
3004 __tun_detach(tfile, false);
3009 netdev_state_change(tun->dev);
3016 static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog **prog_p,
3019 struct bpf_prog *prog;
3022 if (copy_from_user(&fd, data, sizeof(fd)))
3028 prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
3030 return PTR_ERR(prog);
3033 return __tun_set_ebpf(tun, prog_p, prog);
3036 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
3037 unsigned long arg, int ifreq_len)
3039 struct tun_file *tfile = file->private_data;
3040 struct net *net = sock_net(&tfile->sk);
3041 struct tun_struct *tun;
3042 void __user* argp = (void __user*)arg;
3043 unsigned int ifindex, carrier;
3051 bool do_notify = false;
3053 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
3054 (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
3055 if (copy_from_user(&ifr, argp, ifreq_len))
3058 memset(&ifr, 0, sizeof(ifr));
3060 if (cmd == TUNGETFEATURES) {
3061 /* Currently this just means: "what IFF flags are valid?".
3062 * This is needed because we never checked for invalid flags on
3065 return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
3066 (unsigned int __user*)argp);
3067 } else if (cmd == TUNSETQUEUE) {
3068 return tun_set_queue(file, &ifr);
3069 } else if (cmd == SIOCGSKNS) {
3070 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3072 return open_related_ns(&net->ns, get_net_ns);
3078 tun = tun_get(tfile);
3079 if (cmd == TUNSETIFF) {
3084 ifr.ifr_name[IFNAMSIZ-1] = '\0';
3086 ret = tun_set_iff(net, file, &ifr);
3091 if (copy_to_user(argp, &ifr, ifreq_len))
3095 if (cmd == TUNSETIFINDEX) {
3101 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
3105 tfile->ifindex = ifindex;
3113 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
3115 net = dev_net(tun->dev);
3119 tun_get_iff(tun, &ifr);
3121 if (tfile->detached)
3122 ifr.ifr_flags |= IFF_DETACH_QUEUE;
3123 if (!tfile->socket.sk->sk_filter)
3124 ifr.ifr_flags |= IFF_NOFILTER;
3126 if (copy_to_user(argp, &ifr, ifreq_len))
3131 /* Disable/Enable checksum */
3133 /* [unimplemented] */
3134 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
3135 arg ? "disabled" : "enabled");
3139 /* Disable/Enable persist mode. Keep an extra reference to the
3140 * module to prevent the module being unprobed.
3142 if (arg && !(tun->flags & IFF_PERSIST)) {
3143 tun->flags |= IFF_PERSIST;
3144 __module_get(THIS_MODULE);
3147 if (!arg && (tun->flags & IFF_PERSIST)) {
3148 tun->flags &= ~IFF_PERSIST;
3149 module_put(THIS_MODULE);
3153 tun_debug(KERN_INFO, tun, "persist %s\n",
3154 arg ? "enabled" : "disabled");
3158 /* Set owner of the device */
3159 owner = make_kuid(current_user_ns(), arg);
3160 if (!uid_valid(owner)) {
3166 tun_debug(KERN_INFO, tun, "owner set to %u\n",
3167 from_kuid(&init_user_ns, tun->owner));
3171 /* Set group of the device */
3172 group = make_kgid(current_user_ns(), arg);
3173 if (!gid_valid(group)) {
3179 tun_debug(KERN_INFO, tun, "group set to %u\n",
3180 from_kgid(&init_user_ns, tun->group));
3184 /* Only allow setting the type when the interface is down */
3185 if (tun->dev->flags & IFF_UP) {
3186 tun_debug(KERN_INFO, tun,
3187 "Linktype set failed because interface is up\n");
3190 tun->dev->type = (int) arg;
3191 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
3203 ret = set_offload(tun, arg);
3206 case TUNSETTXFILTER:
3207 /* Can be set only for TAPs */
3209 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3211 ret = update_filter(&tun->txflt, (void __user *)arg);
3215 /* Get hw address */
3216 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
3217 ifr.ifr_hwaddr.sa_family = tun->dev->type;
3218 if (copy_to_user(argp, &ifr, ifreq_len))
3223 /* Set hw address */
3224 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
3225 ifr.ifr_hwaddr.sa_data);
3227 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr, NULL);
3231 sndbuf = tfile->socket.sk->sk_sndbuf;
3232 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
3237 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
3246 tun->sndbuf = sndbuf;
3247 tun_set_sndbuf(tun);
3250 case TUNGETVNETHDRSZ:
3251 vnet_hdr_sz = tun->vnet_hdr_sz;
3252 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
3256 case TUNSETVNETHDRSZ:
3257 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
3261 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
3266 tun->vnet_hdr_sz = vnet_hdr_sz;
3270 le = !!(tun->flags & TUN_VNET_LE);
3271 if (put_user(le, (int __user *)argp))
3276 if (get_user(le, (int __user *)argp)) {
3281 tun->flags |= TUN_VNET_LE;
3283 tun->flags &= ~TUN_VNET_LE;
3287 ret = tun_get_vnet_be(tun, argp);
3291 ret = tun_set_vnet_be(tun, argp);
3294 case TUNATTACHFILTER:
3295 /* Can be set only for TAPs */
3297 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3300 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
3303 ret = tun_attach_filter(tun);
3306 case TUNDETACHFILTER:
3307 /* Can be set only for TAPs */
3309 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3312 tun_detach_filter(tun, tun->numqueues);
3317 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3320 if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
3325 case TUNSETSTEERINGEBPF:
3326 ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
3329 case TUNSETFILTEREBPF:
3330 ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3335 if (copy_from_user(&carrier, argp, sizeof(carrier)))
3338 ret = tun_net_change_carrier(tun->dev, (bool)carrier);
3341 case TUNGETDEVNETNS:
3343 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3345 ret = open_related_ns(&net->ns, get_net_ns);
3354 netdev_state_change(tun->dev);
3363 static long tun_chr_ioctl(struct file *file,
3364 unsigned int cmd, unsigned long arg)
3366 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
3369 #ifdef CONFIG_COMPAT
3370 static long tun_chr_compat_ioctl(struct file *file,
3371 unsigned int cmd, unsigned long arg)
3376 case TUNSETTXFILTER:
3381 arg = (unsigned long)compat_ptr(arg);
3384 arg = (compat_ulong_t)arg;
3389 * compat_ifreq is shorter than ifreq, so we must not access beyond
3390 * the end of that structure. All fields that are used in this
3391 * driver are compatible though, we don't need to convert the
3394 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
3396 #endif /* CONFIG_COMPAT */
3398 static int tun_chr_fasync(int fd, struct file *file, int on)
3400 struct tun_file *tfile = file->private_data;
3403 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
3407 __f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
3408 tfile->flags |= TUN_FASYNC;
3410 tfile->flags &= ~TUN_FASYNC;
3416 static int tun_chr_open(struct inode *inode, struct file * file)
3418 struct net *net = current->nsproxy->net_ns;
3419 struct tun_file *tfile;
3421 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
3423 tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
3427 if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
3428 sk_free(&tfile->sk);
3432 mutex_init(&tfile->napi_mutex);
3433 RCU_INIT_POINTER(tfile->tun, NULL);
3437 init_waitqueue_head(&tfile->wq.wait);
3438 RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
3440 tfile->socket.file = file;
3441 tfile->socket.ops = &tun_socket_ops;
3443 sock_init_data(&tfile->socket, &tfile->sk);
3445 tfile->sk.sk_write_space = tun_sock_write_space;
3446 tfile->sk.sk_sndbuf = INT_MAX;
3448 file->private_data = tfile;
3449 INIT_LIST_HEAD(&tfile->next);
3451 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
3456 static int tun_chr_close(struct inode *inode, struct file *file)
3458 struct tun_file *tfile = file->private_data;
3460 tun_detach(tfile, true);
3465 #ifdef CONFIG_PROC_FS
3466 static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
3468 struct tun_file *tfile = file->private_data;
3469 struct tun_struct *tun;
3472 memset(&ifr, 0, sizeof(ifr));
3475 tun = tun_get(tfile);
3477 tun_get_iff(tun, &ifr);
3483 seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
3487 static const struct file_operations tun_fops = {
3488 .owner = THIS_MODULE,
3489 .llseek = no_llseek,
3490 .read_iter = tun_chr_read_iter,
3491 .write_iter = tun_chr_write_iter,
3492 .poll = tun_chr_poll,
3493 .unlocked_ioctl = tun_chr_ioctl,
3494 #ifdef CONFIG_COMPAT
3495 .compat_ioctl = tun_chr_compat_ioctl,
3497 .open = tun_chr_open,
3498 .release = tun_chr_close,
3499 .fasync = tun_chr_fasync,
3500 #ifdef CONFIG_PROC_FS
3501 .show_fdinfo = tun_chr_show_fdinfo,
3505 static struct miscdevice tun_miscdev = {
3508 .nodename = "net/tun",
3512 /* ethtool interface */
3514 static void tun_default_link_ksettings(struct net_device *dev,
3515 struct ethtool_link_ksettings *cmd)
3517 ethtool_link_ksettings_zero_link_mode(cmd, supported);
3518 ethtool_link_ksettings_zero_link_mode(cmd, advertising);
3519 cmd->base.speed = SPEED_10;
3520 cmd->base.duplex = DUPLEX_FULL;
3521 cmd->base.port = PORT_TP;
3522 cmd->base.phy_address = 0;
3523 cmd->base.autoneg = AUTONEG_DISABLE;
3526 static int tun_get_link_ksettings(struct net_device *dev,
3527 struct ethtool_link_ksettings *cmd)
3529 struct tun_struct *tun = netdev_priv(dev);
3531 memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
3535 static int tun_set_link_ksettings(struct net_device *dev,
3536 const struct ethtool_link_ksettings *cmd)
3538 struct tun_struct *tun = netdev_priv(dev);
3540 memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
3544 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
3546 struct tun_struct *tun = netdev_priv(dev);
3548 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
3549 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
3551 switch (tun->flags & TUN_TYPE_MASK) {
3553 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
3556 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
3561 static u32 tun_get_msglevel(struct net_device *dev)
3564 struct tun_struct *tun = netdev_priv(dev);
3571 static void tun_set_msglevel(struct net_device *dev, u32 value)
3574 struct tun_struct *tun = netdev_priv(dev);
3579 static int tun_get_coalesce(struct net_device *dev,
3580 struct ethtool_coalesce *ec)
3582 struct tun_struct *tun = netdev_priv(dev);
3584 ec->rx_max_coalesced_frames = tun->rx_batched;
3589 static int tun_set_coalesce(struct net_device *dev,
3590 struct ethtool_coalesce *ec)
3592 struct tun_struct *tun = netdev_priv(dev);
3594 if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
3595 tun->rx_batched = NAPI_POLL_WEIGHT;
3597 tun->rx_batched = ec->rx_max_coalesced_frames;
3602 static const struct ethtool_ops tun_ethtool_ops = {
3603 .get_drvinfo = tun_get_drvinfo,
3604 .get_msglevel = tun_get_msglevel,
3605 .set_msglevel = tun_set_msglevel,
3606 .get_link = ethtool_op_get_link,
3607 .get_ts_info = ethtool_op_get_ts_info,
3608 .get_coalesce = tun_get_coalesce,
3609 .set_coalesce = tun_set_coalesce,
3610 .get_link_ksettings = tun_get_link_ksettings,
3611 .set_link_ksettings = tun_set_link_ksettings,
3614 static int tun_queue_resize(struct tun_struct *tun)
3616 struct net_device *dev = tun->dev;
3617 struct tun_file *tfile;
3618 struct ptr_ring **rings;
3619 int n = tun->numqueues + tun->numdisabled;
3622 rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
3626 for (i = 0; i < tun->numqueues; i++) {
3627 tfile = rtnl_dereference(tun->tfiles[i]);
3628 rings[i] = &tfile->tx_ring;
3630 list_for_each_entry(tfile, &tun->disabled, next)
3631 rings[i++] = &tfile->tx_ring;
3633 ret = ptr_ring_resize_multiple(rings, n,
3634 dev->tx_queue_len, GFP_KERNEL,
3641 static int tun_device_event(struct notifier_block *unused,
3642 unsigned long event, void *ptr)
3644 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3645 struct tun_struct *tun = netdev_priv(dev);
3647 if (dev->rtnl_link_ops != &tun_link_ops)
3651 case NETDEV_CHANGE_TX_QUEUE_LEN:
3652 if (tun_queue_resize(tun))
3662 static struct notifier_block tun_notifier_block __read_mostly = {
3663 .notifier_call = tun_device_event,
3666 static int __init tun_init(void)
3670 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
3672 ret = rtnl_link_register(&tun_link_ops);
3674 pr_err("Can't register link_ops\n");
3678 ret = misc_register(&tun_miscdev);
3680 pr_err("Can't register misc device %d\n", TUN_MINOR);
3684 ret = register_netdevice_notifier(&tun_notifier_block);
3686 pr_err("Can't register netdevice notifier\n");
3693 misc_deregister(&tun_miscdev);
3695 rtnl_link_unregister(&tun_link_ops);
3700 static void tun_cleanup(void)
3702 misc_deregister(&tun_miscdev);
3703 rtnl_link_unregister(&tun_link_ops);
3704 unregister_netdevice_notifier(&tun_notifier_block);
3707 /* Get an underlying socket object from tun file. Returns error unless file is
3708 * attached to a device. The returned object works like a packet socket, it
3709 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
3710 * holding a reference to the file for as long as the socket is in use. */
3711 struct socket *tun_get_socket(struct file *file)
3713 struct tun_file *tfile;
3714 if (file->f_op != &tun_fops)
3715 return ERR_PTR(-EINVAL);
3716 tfile = file->private_data;
3718 return ERR_PTR(-EBADFD);
3719 return &tfile->socket;
3721 EXPORT_SYMBOL_GPL(tun_get_socket);
3723 struct ptr_ring *tun_get_tx_ring(struct file *file)
3725 struct tun_file *tfile;
3727 if (file->f_op != &tun_fops)
3728 return ERR_PTR(-EINVAL);
3729 tfile = file->private_data;
3731 return ERR_PTR(-EBADFD);
3732 return &tfile->tx_ring;
3734 EXPORT_SYMBOL_GPL(tun_get_tx_ring);
3736 module_init(tun_init);
3737 module_exit(tun_cleanup);
3738 MODULE_DESCRIPTION(DRV_DESCRIPTION);
3739 MODULE_AUTHOR(DRV_COPYRIGHT);
3740 MODULE_LICENSE("GPL");
3741 MODULE_ALIAS_MISCDEV(TUN_MINOR);
3742 MODULE_ALIAS("devname:net/tun");