1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * TUN - Universal TUN/TAP device driver.
4 * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
6 * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
12 * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
13 * Add TUNSETLINK ioctl to set the link encapsulation
15 * Mark Smith <markzzzsmith@yahoo.com.au>
16 * Use eth_random_addr() for tap MAC address.
18 * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20
19 * Fixes in packet dropping, queue length setting and queue wakeup.
20 * Increased default tx queue length.
24 * Daniel Podlejski <underley@underley.eu.org>
25 * Modifications for 2.3.99-pre5 kernel.
28 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
30 #define DRV_NAME "tun"
31 #define DRV_VERSION "1.6"
32 #define DRV_DESCRIPTION "Universal TUN/TAP device driver"
33 #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
35 #include <linux/module.h>
36 #include <linux/errno.h>
37 #include <linux/kernel.h>
38 #include <linux/sched/signal.h>
39 #include <linux/major.h>
40 #include <linux/slab.h>
41 #include <linux/poll.h>
42 #include <linux/fcntl.h>
43 #include <linux/init.h>
44 #include <linux/skbuff.h>
45 #include <linux/netdevice.h>
46 #include <linux/etherdevice.h>
47 #include <linux/miscdevice.h>
48 #include <linux/ethtool.h>
49 #include <linux/rtnetlink.h>
50 #include <linux/compat.h>
52 #include <linux/if_arp.h>
53 #include <linux/if_ether.h>
54 #include <linux/if_tun.h>
55 #include <linux/if_vlan.h>
56 #include <linux/crc32.h>
57 #include <linux/nsproxy.h>
58 #include <linux/virtio_net.h>
59 #include <linux/rcupdate.h>
60 #include <net/net_namespace.h>
61 #include <net/netns/generic.h>
62 #include <net/rtnetlink.h>
65 #include <linux/seq_file.h>
66 #include <linux/uio.h>
67 #include <linux/skb_array.h>
68 #include <linux/bpf.h>
69 #include <linux/bpf_trace.h>
70 #include <linux/mutex.h>
71 #include <linux/ieee802154.h>
72 #include <linux/if_ltalk.h>
73 #include <uapi/linux/if_fddi.h>
74 #include <uapi/linux/if_hippi.h>
75 #include <uapi/linux/if_fc.h>
78 #include <net/6lowpan.h>
80 #include <linux/uaccess.h>
81 #include <linux/proc_fs.h>
83 static void tun_default_link_ksettings(struct net_device *dev,
84 struct ethtool_link_ksettings *cmd);
86 /* Uncomment to enable debugging */
87 /* #define TUN_DEBUG 1 */
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); \
103 #define tun_debug(level, tun, fmt, args...) \
106 netdev_printk(level, tun->dev, fmt, ##args); \
108 #define DBG1(level, fmt, args...) \
111 printk(level fmt, ##args); \
115 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
117 /* TUN device flags */
119 /* IFF_ATTACH_QUEUE is never stored in device flags,
120 * overload it to mean fasync when stored there.
122 #define TUN_FASYNC IFF_ATTACH_QUEUE
123 /* High bits in flags field are unused. */
124 #define TUN_VNET_LE 0x80000000
125 #define TUN_VNET_BE 0x40000000
127 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
128 IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
130 #define GOODCOPY_LEN 128
132 #define FLT_EXACT_COUNT 8
134 unsigned int count; /* Number of addrs. Zero means disabled */
135 u32 mask[2]; /* Mask of the hashed addrs */
136 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
139 /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
140 * to max number of VCPUs in guest. */
141 #define MAX_TAP_QUEUES 256
142 #define MAX_TAP_FLOWS 4096
144 #define TUN_FLOW_EXPIRE (3 * HZ)
146 struct tun_pcpu_stats {
151 struct u64_stats_sync syncp;
157 /* A tun_file connects an open character device to a tuntap netdevice. It
158 * also contains all socket related structures (except sock_fprog and tap_filter)
159 * to serve as one transmit queue for tuntap device. The sock_fprog and
160 * tap_filter were kept in tun_struct since they were used for filtering for the
161 * netdevice not for a specific queue (at least I didn't see the requirement for
165 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
166 * other can only be read while rcu_read_lock or rtnl_lock is held.
170 struct socket socket;
171 struct tun_struct __rcu *tun;
172 struct fasync_struct *fasync;
173 /* only used for fasnyc */
177 unsigned int ifindex;
179 struct napi_struct napi;
181 bool napi_frags_enabled;
182 struct mutex napi_mutex; /* Protects access to the above napi */
183 struct list_head next;
184 struct tun_struct *detached;
185 struct ptr_ring tx_ring;
186 struct xdp_rxq_info xdp_rxq;
194 struct tun_flow_entry {
195 struct hlist_node hash_link;
197 struct tun_struct *tun;
202 unsigned long updated ____cacheline_aligned_in_smp;
205 #define TUN_NUM_FLOW_ENTRIES 1024
206 #define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
210 struct bpf_prog *prog;
213 /* Since the socket were moved to tun_file, to preserve the behavior of persist
214 * device, socket filter, sndbuf and vnet header size were restore when the
215 * file were attached to a persist device.
218 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
219 unsigned int numqueues;
224 struct net_device *dev;
225 netdev_features_t set_features;
226 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
232 struct tap_filter txflt;
233 struct sock_fprog fprog;
234 /* protected by rtnl lock */
235 bool filter_attached;
240 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
241 struct timer_list flow_gc_timer;
242 unsigned long ageing_time;
243 unsigned int numdisabled;
244 struct list_head disabled;
248 struct tun_pcpu_stats __percpu *pcpu_stats;
249 struct bpf_prog __rcu *xdp_prog;
250 struct tun_prog __rcu *steering_prog;
251 struct tun_prog __rcu *filter_prog;
252 struct ethtool_link_ksettings link_ksettings;
263 bool tun_is_xdp_frame(void *ptr)
265 return (unsigned long)ptr & TUN_XDP_FLAG;
267 EXPORT_SYMBOL(tun_is_xdp_frame);
269 void *tun_xdp_to_ptr(void *ptr)
271 return (void *)((unsigned long)ptr | TUN_XDP_FLAG);
273 EXPORT_SYMBOL(tun_xdp_to_ptr);
275 void *tun_ptr_to_xdp(void *ptr)
277 return (void *)((unsigned long)ptr & ~TUN_XDP_FLAG);
279 EXPORT_SYMBOL(tun_ptr_to_xdp);
281 static void tun_flow_init(struct tun_struct *tun);
282 static void tun_flow_uninit(struct tun_struct *tun);
284 static int tun_napi_receive(struct napi_struct *napi, int budget)
286 struct tun_file *tfile = container_of(napi, struct tun_file, napi);
287 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
288 struct sk_buff_head process_queue;
292 __skb_queue_head_init(&process_queue);
294 spin_lock(&queue->lock);
295 skb_queue_splice_tail_init(queue, &process_queue);
296 spin_unlock(&queue->lock);
298 while (received < budget && (skb = __skb_dequeue(&process_queue))) {
299 napi_gro_receive(napi, skb);
303 if (!skb_queue_empty(&process_queue)) {
304 spin_lock(&queue->lock);
305 skb_queue_splice(&process_queue, queue);
306 spin_unlock(&queue->lock);
312 static int tun_napi_poll(struct napi_struct *napi, int budget)
314 unsigned int received;
316 received = tun_napi_receive(napi, budget);
318 if (received < budget)
319 napi_complete_done(napi, received);
324 static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
325 bool napi_en, bool napi_frags)
327 tfile->napi_enabled = napi_en;
328 tfile->napi_frags_enabled = napi_en && napi_frags;
330 netif_tx_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
332 napi_enable(&tfile->napi);
336 static void tun_napi_enable(struct tun_file *tfile)
338 if (tfile->napi_enabled)
339 napi_enable(&tfile->napi);
342 static void tun_napi_disable(struct tun_file *tfile)
344 if (tfile->napi_enabled)
345 napi_disable(&tfile->napi);
348 static void tun_napi_del(struct tun_file *tfile)
350 if (tfile->napi_enabled)
351 netif_napi_del(&tfile->napi);
354 static bool tun_napi_frags_enabled(const struct tun_file *tfile)
356 return tfile->napi_frags_enabled;
359 #ifdef CONFIG_TUN_VNET_CROSS_LE
360 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
362 return tun->flags & TUN_VNET_BE ? false :
363 virtio_legacy_is_little_endian();
366 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
368 int be = !!(tun->flags & TUN_VNET_BE);
370 if (put_user(be, argp))
376 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
380 if (get_user(be, argp))
384 tun->flags |= TUN_VNET_BE;
386 tun->flags &= ~TUN_VNET_BE;
391 static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
393 return virtio_legacy_is_little_endian();
396 static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
401 static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
405 #endif /* CONFIG_TUN_VNET_CROSS_LE */
407 static inline bool tun_is_little_endian(struct tun_struct *tun)
409 return tun->flags & TUN_VNET_LE ||
410 tun_legacy_is_little_endian(tun);
413 static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
415 return __virtio16_to_cpu(tun_is_little_endian(tun), val);
418 static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
420 return __cpu_to_virtio16(tun_is_little_endian(tun), val);
423 static inline u32 tun_hashfn(u32 rxhash)
425 return rxhash & TUN_MASK_FLOW_ENTRIES;
428 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
430 struct tun_flow_entry *e;
432 hlist_for_each_entry_rcu(e, head, hash_link) {
433 if (e->rxhash == rxhash)
439 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
440 struct hlist_head *head,
441 u32 rxhash, u16 queue_index)
443 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
446 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
447 rxhash, queue_index);
448 e->updated = jiffies;
451 e->queue_index = queue_index;
453 hlist_add_head_rcu(&e->hash_link, head);
459 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
461 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
462 e->rxhash, e->queue_index);
463 hlist_del_rcu(&e->hash_link);
468 static void tun_flow_flush(struct tun_struct *tun)
472 spin_lock_bh(&tun->lock);
473 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
474 struct tun_flow_entry *e;
475 struct hlist_node *n;
477 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
478 tun_flow_delete(tun, e);
480 spin_unlock_bh(&tun->lock);
483 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
487 spin_lock_bh(&tun->lock);
488 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
489 struct tun_flow_entry *e;
490 struct hlist_node *n;
492 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
493 if (e->queue_index == queue_index)
494 tun_flow_delete(tun, e);
497 spin_unlock_bh(&tun->lock);
500 static void tun_flow_cleanup(struct timer_list *t)
502 struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
503 unsigned long delay = tun->ageing_time;
504 unsigned long next_timer = jiffies + delay;
505 unsigned long count = 0;
508 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
510 spin_lock(&tun->lock);
511 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
512 struct tun_flow_entry *e;
513 struct hlist_node *n;
515 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
516 unsigned long this_timer;
518 this_timer = e->updated + delay;
519 if (time_before_eq(this_timer, jiffies)) {
520 tun_flow_delete(tun, e);
524 if (time_before(this_timer, next_timer))
525 next_timer = this_timer;
530 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
531 spin_unlock(&tun->lock);
534 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
535 struct tun_file *tfile)
537 struct hlist_head *head;
538 struct tun_flow_entry *e;
539 unsigned long delay = tun->ageing_time;
540 u16 queue_index = tfile->queue_index;
542 head = &tun->flows[tun_hashfn(rxhash)];
546 e = tun_flow_find(head, rxhash);
548 /* TODO: keep queueing to old queue until it's empty? */
549 if (READ_ONCE(e->queue_index) != queue_index)
550 WRITE_ONCE(e->queue_index, queue_index);
551 if (e->updated != jiffies)
552 e->updated = jiffies;
553 sock_rps_record_flow_hash(e->rps_rxhash);
555 spin_lock_bh(&tun->lock);
556 if (!tun_flow_find(head, rxhash) &&
557 tun->flow_count < MAX_TAP_FLOWS)
558 tun_flow_create(tun, head, rxhash, queue_index);
560 if (!timer_pending(&tun->flow_gc_timer))
561 mod_timer(&tun->flow_gc_timer,
562 round_jiffies_up(jiffies + delay));
563 spin_unlock_bh(&tun->lock);
570 * Save the hash received in the stack receive path and update the
571 * flow_hash table accordingly.
573 static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
575 if (unlikely(e->rps_rxhash != hash))
576 e->rps_rxhash = hash;
579 /* We try to identify a flow through its rxhash. The reason that
580 * we do not check rxq no. is because some cards(e.g 82599), chooses
581 * the rxq based on the txq where the last packet of the flow comes. As
582 * the userspace application move between processors, we may get a
583 * different rxq no. here.
585 static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
587 struct tun_flow_entry *e;
591 numqueues = READ_ONCE(tun->numqueues);
593 txq = __skb_get_hash_symmetric(skb);
594 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
596 tun_flow_save_rps_rxhash(e, txq);
597 txq = e->queue_index;
599 /* use multiply and shift instead of expensive divide */
600 txq = ((u64)txq * numqueues) >> 32;
606 static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
608 struct tun_prog *prog;
612 numqueues = READ_ONCE(tun->numqueues);
616 prog = rcu_dereference(tun->steering_prog);
618 ret = bpf_prog_run_clear_cb(prog->prog, skb);
620 return ret % numqueues;
623 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
624 struct net_device *sb_dev)
626 struct tun_struct *tun = netdev_priv(dev);
630 if (rcu_dereference(tun->steering_prog))
631 ret = tun_ebpf_select_queue(tun, skb);
633 ret = tun_automq_select_queue(tun, skb);
639 static inline bool tun_not_capable(struct tun_struct *tun)
641 const struct cred *cred = current_cred();
642 struct net *net = dev_net(tun->dev);
644 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
645 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
646 !ns_capable(net->user_ns, CAP_NET_ADMIN);
649 static void tun_set_real_num_queues(struct tun_struct *tun)
651 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
652 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
655 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
657 tfile->detached = tun;
658 list_add_tail(&tfile->next, &tun->disabled);
662 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
664 struct tun_struct *tun = tfile->detached;
666 tfile->detached = NULL;
667 list_del_init(&tfile->next);
672 void tun_ptr_free(void *ptr)
676 if (tun_is_xdp_frame(ptr)) {
677 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
679 xdp_return_frame(xdpf);
681 __skb_array_destroy_skb(ptr);
684 EXPORT_SYMBOL_GPL(tun_ptr_free);
686 static void tun_queue_purge(struct tun_file *tfile)
690 while ((ptr = ptr_ring_consume(&tfile->tx_ring)) != NULL)
693 skb_queue_purge(&tfile->sk.sk_write_queue);
694 skb_queue_purge(&tfile->sk.sk_error_queue);
697 static void __tun_detach(struct tun_file *tfile, bool clean)
699 struct tun_file *ntfile;
700 struct tun_struct *tun;
702 tun = rtnl_dereference(tfile->tun);
705 if (!tfile->detached)
706 tun_napi_disable(tfile);
710 if (tun && !tfile->detached) {
711 u16 index = tfile->queue_index;
712 BUG_ON(index >= tun->numqueues);
714 rcu_assign_pointer(tun->tfiles[index],
715 tun->tfiles[tun->numqueues - 1]);
716 ntfile = rtnl_dereference(tun->tfiles[index]);
717 ntfile->queue_index = index;
718 rcu_assign_pointer(tun->tfiles[tun->numqueues - 1],
723 RCU_INIT_POINTER(tfile->tun, NULL);
724 sock_put(&tfile->sk);
726 tun_disable_queue(tun, tfile);
727 tun_napi_disable(tfile);
731 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
732 /* Drop read queue */
733 tun_queue_purge(tfile);
734 tun_set_real_num_queues(tun);
735 } else if (tfile->detached && clean) {
736 tun = tun_enable_queue(tfile);
737 sock_put(&tfile->sk);
741 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
742 netif_carrier_off(tun->dev);
744 if (!(tun->flags & IFF_PERSIST) &&
745 tun->dev->reg_state == NETREG_REGISTERED)
746 unregister_netdevice(tun->dev);
749 xdp_rxq_info_unreg(&tfile->xdp_rxq);
750 ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
754 static void tun_detach(struct tun_file *tfile, bool clean)
756 struct tun_struct *tun;
757 struct net_device *dev;
760 tun = rtnl_dereference(tfile->tun);
761 dev = tun ? tun->dev : NULL;
762 __tun_detach(tfile, clean);
764 netdev_state_change(dev);
768 sock_put(&tfile->sk);
771 static void tun_detach_all(struct net_device *dev)
773 struct tun_struct *tun = netdev_priv(dev);
774 struct tun_file *tfile, *tmp;
775 int i, n = tun->numqueues;
777 for (i = 0; i < n; i++) {
778 tfile = rtnl_dereference(tun->tfiles[i]);
780 tun_napi_disable(tfile);
781 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
782 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
783 RCU_INIT_POINTER(tfile->tun, NULL);
786 list_for_each_entry(tfile, &tun->disabled, next) {
787 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
788 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
789 RCU_INIT_POINTER(tfile->tun, NULL);
791 BUG_ON(tun->numqueues != 0);
794 for (i = 0; i < n; i++) {
795 tfile = rtnl_dereference(tun->tfiles[i]);
797 /* Drop read queue */
798 tun_queue_purge(tfile);
799 xdp_rxq_info_unreg(&tfile->xdp_rxq);
800 sock_put(&tfile->sk);
802 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
804 tun_enable_queue(tfile);
805 tun_queue_purge(tfile);
806 xdp_rxq_info_unreg(&tfile->xdp_rxq);
807 sock_put(&tfile->sk);
809 BUG_ON(tun->numdisabled != 0);
811 if (tun->flags & IFF_PERSIST)
812 module_put(THIS_MODULE);
815 static int tun_attach(struct tun_struct *tun, struct file *file,
816 bool skip_filter, bool napi, bool napi_frags,
819 struct tun_file *tfile = file->private_data;
820 struct net_device *dev = tun->dev;
823 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
828 if (rtnl_dereference(tfile->tun) && !tfile->detached)
832 if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
836 if (!tfile->detached &&
837 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
842 /* Re-attach the filter to persist device */
843 if (!skip_filter && (tun->filter_attached == true)) {
844 lock_sock(tfile->socket.sk);
845 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
846 release_sock(tfile->socket.sk);
851 if (!tfile->detached &&
852 ptr_ring_resize(&tfile->tx_ring, dev->tx_queue_len,
853 GFP_KERNEL, tun_ptr_free)) {
858 tfile->queue_index = tun->numqueues;
859 tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
861 if (tfile->detached) {
862 /* Re-attach detached tfile, updating XDP queue_index */
863 WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
865 if (tfile->xdp_rxq.queue_index != tfile->queue_index)
866 tfile->xdp_rxq.queue_index = tfile->queue_index;
868 /* Setup XDP RX-queue info, for new tfile getting attached */
869 err = xdp_rxq_info_reg(&tfile->xdp_rxq,
870 tun->dev, tfile->queue_index);
873 err = xdp_rxq_info_reg_mem_model(&tfile->xdp_rxq,
874 MEM_TYPE_PAGE_SHARED, NULL);
876 xdp_rxq_info_unreg(&tfile->xdp_rxq);
882 if (tfile->detached) {
883 tun_enable_queue(tfile);
884 tun_napi_enable(tfile);
886 sock_hold(&tfile->sk);
887 tun_napi_init(tun, tfile, napi, napi_frags);
890 if (rtnl_dereference(tun->xdp_prog))
891 sock_set_flag(&tfile->sk, SOCK_XDP);
893 /* device is allowed to go away first, so no need to hold extra
897 /* Publish tfile->tun and tun->tfiles only after we've fully
898 * initialized tfile; otherwise we risk using half-initialized
902 rcu_assign_pointer(tfile->tun, tun);
903 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
905 tun_set_real_num_queues(tun);
910 static struct tun_struct *tun_get(struct tun_file *tfile)
912 struct tun_struct *tun;
915 tun = rcu_dereference(tfile->tun);
923 static void tun_put(struct tun_struct *tun)
929 static void addr_hash_set(u32 *mask, const u8 *addr)
931 int n = ether_crc(ETH_ALEN, addr) >> 26;
932 mask[n >> 5] |= (1 << (n & 31));
935 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
937 int n = ether_crc(ETH_ALEN, addr) >> 26;
938 return mask[n >> 5] & (1 << (n & 31));
941 static int update_filter(struct tap_filter *filter, void __user *arg)
943 struct { u8 u[ETH_ALEN]; } *addr;
944 struct tun_filter uf;
945 int err, alen, n, nexact;
947 if (copy_from_user(&uf, arg, sizeof(uf)))
956 alen = ETH_ALEN * uf.count;
957 addr = memdup_user(arg + sizeof(uf), alen);
959 return PTR_ERR(addr);
961 /* The filter is updated without holding any locks. Which is
962 * perfectly safe. We disable it first and in the worst
963 * case we'll accept a few undesired packets. */
967 /* Use first set of addresses as an exact filter */
968 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
969 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
973 /* Remaining multicast addresses are hashed,
974 * unicast will leave the filter disabled. */
975 memset(filter->mask, 0, sizeof(filter->mask));
976 for (; n < uf.count; n++) {
977 if (!is_multicast_ether_addr(addr[n].u)) {
978 err = 0; /* no filter */
981 addr_hash_set(filter->mask, addr[n].u);
984 /* For ALLMULTI just set the mask to all ones.
985 * This overrides the mask populated above. */
986 if ((uf.flags & TUN_FLT_ALLMULTI))
987 memset(filter->mask, ~0, sizeof(filter->mask));
989 /* Now enable the filter */
991 filter->count = nexact;
993 /* Return the number of exact filters */
1000 /* Returns: 0 - drop, !=0 - accept */
1001 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
1003 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
1005 struct ethhdr *eh = (struct ethhdr *) skb->data;
1009 for (i = 0; i < filter->count; i++)
1010 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
1013 /* Inexact match (multicast only) */
1014 if (is_multicast_ether_addr(eh->h_dest))
1015 return addr_hash_test(filter->mask, eh->h_dest);
1021 * Checks whether the packet is accepted or not.
1022 * Returns: 0 - drop, !=0 - accept
1024 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
1029 return run_filter(filter, skb);
1032 /* Network device part of the driver */
1034 static const struct ethtool_ops tun_ethtool_ops;
1036 static int tun_net_init(struct net_device *dev)
1038 struct tun_struct *tun = netdev_priv(dev);
1039 struct ifreq *ifr = tun->ifr;
1042 tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
1043 if (!tun->pcpu_stats)
1046 spin_lock_init(&tun->lock);
1048 err = security_tun_dev_alloc_security(&tun->security);
1050 free_percpu(tun->pcpu_stats);
1056 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1057 TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
1058 NETIF_F_HW_VLAN_STAG_TX;
1059 dev->features = dev->hw_features | NETIF_F_LLTX;
1060 dev->vlan_features = dev->features &
1061 ~(NETIF_F_HW_VLAN_CTAG_TX |
1062 NETIF_F_HW_VLAN_STAG_TX);
1064 tun->flags = (tun->flags & ~TUN_FEATURES) |
1065 (ifr->ifr_flags & TUN_FEATURES);
1067 INIT_LIST_HEAD(&tun->disabled);
1068 err = tun_attach(tun, tun->file, false, ifr->ifr_flags & IFF_NAPI,
1069 ifr->ifr_flags & IFF_NAPI_FRAGS, false);
1071 tun_flow_uninit(tun);
1072 security_tun_dev_free_security(tun->security);
1073 free_percpu(tun->pcpu_stats);
1079 /* Net device detach from fd. */
1080 static void tun_net_uninit(struct net_device *dev)
1082 tun_detach_all(dev);
1085 /* Net device open. */
1086 static int tun_net_open(struct net_device *dev)
1088 netif_tx_start_all_queues(dev);
1093 /* Net device close. */
1094 static int tun_net_close(struct net_device *dev)
1096 netif_tx_stop_all_queues(dev);
1100 /* Net device start xmit */
1101 static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
1104 if (tun->numqueues == 1 && static_branch_unlikely(&rps_needed)) {
1105 /* Select queue was not called for the skbuff, so we extract the
1106 * RPS hash and save it into the flow_table here.
1108 struct tun_flow_entry *e;
1111 rxhash = __skb_get_hash_symmetric(skb);
1112 e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash);
1114 tun_flow_save_rps_rxhash(e, rxhash);
1119 static unsigned int run_ebpf_filter(struct tun_struct *tun,
1120 struct sk_buff *skb,
1123 struct tun_prog *prog = rcu_dereference(tun->filter_prog);
1126 len = bpf_prog_run_clear_cb(prog->prog, skb);
1131 /* Net device start xmit */
1132 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
1134 struct tun_struct *tun = netdev_priv(dev);
1135 int txq = skb->queue_mapping;
1136 struct netdev_queue *queue;
1137 struct tun_file *tfile;
1141 tfile = rcu_dereference(tun->tfiles[txq]);
1143 /* Drop packet if interface is not attached */
1147 if (!rcu_dereference(tun->steering_prog))
1148 tun_automq_xmit(tun, skb);
1150 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
1154 /* Drop if the filter does not like it.
1155 * This is a noop if the filter is disabled.
1156 * Filter can be enabled only for the TAP devices. */
1157 if (!check_filter(&tun->txflt, skb))
1160 if (tfile->socket.sk->sk_filter &&
1161 sk_filter(tfile->socket.sk, skb))
1164 len = run_ebpf_filter(tun, skb, len);
1165 if (len == 0 || pskb_trim(skb, len))
1168 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
1171 skb_tx_timestamp(skb);
1173 /* Orphan the skb - required as we might hang on to it
1174 * for indefinite time.
1180 if (ptr_ring_produce(&tfile->tx_ring, skb))
1183 /* NETIF_F_LLTX requires to do our own update of trans_start */
1184 queue = netdev_get_tx_queue(dev, txq);
1185 queue->trans_start = jiffies;
1187 /* Notify and wake up reader process */
1188 if (tfile->flags & TUN_FASYNC)
1189 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1190 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1193 return NETDEV_TX_OK;
1196 this_cpu_inc(tun->pcpu_stats->tx_dropped);
1200 return NET_XMIT_DROP;
1203 static void tun_net_mclist(struct net_device *dev)
1206 * This callback is supposed to deal with mc filter in
1207 * _rx_ path and has nothing to do with the _tx_ path.
1208 * In rx path we always accept everything userspace gives us.
1212 static netdev_features_t tun_net_fix_features(struct net_device *dev,
1213 netdev_features_t features)
1215 struct tun_struct *tun = netdev_priv(dev);
1217 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
1220 static void tun_set_headroom(struct net_device *dev, int new_hr)
1222 struct tun_struct *tun = netdev_priv(dev);
1224 if (new_hr < NET_SKB_PAD)
1225 new_hr = NET_SKB_PAD;
1227 tun->align = new_hr;
1231 tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1233 u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1234 struct tun_struct *tun = netdev_priv(dev);
1235 struct tun_pcpu_stats *p;
1238 for_each_possible_cpu(i) {
1239 u64 rxpackets, rxbytes, txpackets, txbytes;
1242 p = per_cpu_ptr(tun->pcpu_stats, i);
1244 start = u64_stats_fetch_begin(&p->syncp);
1245 rxpackets = p->rx_packets;
1246 rxbytes = p->rx_bytes;
1247 txpackets = p->tx_packets;
1248 txbytes = p->tx_bytes;
1249 } while (u64_stats_fetch_retry(&p->syncp, start));
1251 stats->rx_packets += rxpackets;
1252 stats->rx_bytes += rxbytes;
1253 stats->tx_packets += txpackets;
1254 stats->tx_bytes += txbytes;
1257 rx_dropped += p->rx_dropped;
1258 rx_frame_errors += p->rx_frame_errors;
1259 tx_dropped += p->tx_dropped;
1261 stats->rx_dropped = rx_dropped;
1262 stats->rx_frame_errors = rx_frame_errors;
1263 stats->tx_dropped = tx_dropped;
1266 static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1267 struct netlink_ext_ack *extack)
1269 struct tun_struct *tun = netdev_priv(dev);
1270 struct tun_file *tfile;
1271 struct bpf_prog *old_prog;
1274 old_prog = rtnl_dereference(tun->xdp_prog);
1275 rcu_assign_pointer(tun->xdp_prog, prog);
1277 bpf_prog_put(old_prog);
1279 for (i = 0; i < tun->numqueues; i++) {
1280 tfile = rtnl_dereference(tun->tfiles[i]);
1282 sock_set_flag(&tfile->sk, SOCK_XDP);
1284 sock_reset_flag(&tfile->sk, SOCK_XDP);
1286 list_for_each_entry(tfile, &tun->disabled, next) {
1288 sock_set_flag(&tfile->sk, SOCK_XDP);
1290 sock_reset_flag(&tfile->sk, SOCK_XDP);
1296 static u32 tun_xdp_query(struct net_device *dev)
1298 struct tun_struct *tun = netdev_priv(dev);
1299 const struct bpf_prog *xdp_prog;
1301 xdp_prog = rtnl_dereference(tun->xdp_prog);
1303 return xdp_prog->aux->id;
1308 static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1310 switch (xdp->command) {
1311 case XDP_SETUP_PROG:
1312 return tun_xdp_set(dev, xdp->prog, xdp->extack);
1313 case XDP_QUERY_PROG:
1314 xdp->prog_id = tun_xdp_query(dev);
1321 static int tun_net_change_carrier(struct net_device *dev, bool new_carrier)
1324 struct tun_struct *tun = netdev_priv(dev);
1326 if (!tun->numqueues)
1329 netif_carrier_on(dev);
1331 netif_carrier_off(dev);
1336 static const struct net_device_ops tun_netdev_ops = {
1337 .ndo_init = tun_net_init,
1338 .ndo_uninit = tun_net_uninit,
1339 .ndo_open = tun_net_open,
1340 .ndo_stop = tun_net_close,
1341 .ndo_start_xmit = tun_net_xmit,
1342 .ndo_fix_features = tun_net_fix_features,
1343 .ndo_select_queue = tun_select_queue,
1344 .ndo_set_rx_headroom = tun_set_headroom,
1345 .ndo_get_stats64 = tun_net_get_stats64,
1346 .ndo_change_carrier = tun_net_change_carrier,
1349 static void __tun_xdp_flush_tfile(struct tun_file *tfile)
1351 /* Notify and wake up reader process */
1352 if (tfile->flags & TUN_FASYNC)
1353 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1354 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1357 static int tun_xdp_xmit(struct net_device *dev, int n,
1358 struct xdp_frame **frames, u32 flags)
1360 struct tun_struct *tun = netdev_priv(dev);
1361 struct tun_file *tfile;
1367 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
1373 numqueues = READ_ONCE(tun->numqueues);
1376 return -ENXIO; /* Caller will free/return all frames */
1379 tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1381 if (unlikely(!tfile))
1384 spin_lock(&tfile->tx_ring.producer_lock);
1385 for (i = 0; i < n; i++) {
1386 struct xdp_frame *xdp = frames[i];
1387 /* Encode the XDP flag into lowest bit for consumer to differ
1388 * XDP buffer from sk_buff.
1390 void *frame = tun_xdp_to_ptr(xdp);
1392 if (__ptr_ring_produce(&tfile->tx_ring, frame)) {
1393 this_cpu_inc(tun->pcpu_stats->tx_dropped);
1394 xdp_return_frame_rx_napi(xdp);
1398 spin_unlock(&tfile->tx_ring.producer_lock);
1400 if (flags & XDP_XMIT_FLUSH)
1401 __tun_xdp_flush_tfile(tfile);
1407 static int tun_xdp_tx(struct net_device *dev, struct xdp_buff *xdp)
1409 struct xdp_frame *frame = convert_to_xdp_frame(xdp);
1411 if (unlikely(!frame))
1414 return tun_xdp_xmit(dev, 1, &frame, XDP_XMIT_FLUSH);
1417 static const struct net_device_ops tap_netdev_ops = {
1418 .ndo_init = tun_net_init,
1419 .ndo_uninit = tun_net_uninit,
1420 .ndo_open = tun_net_open,
1421 .ndo_stop = tun_net_close,
1422 .ndo_start_xmit = tun_net_xmit,
1423 .ndo_fix_features = tun_net_fix_features,
1424 .ndo_set_rx_mode = tun_net_mclist,
1425 .ndo_set_mac_address = eth_mac_addr,
1426 .ndo_validate_addr = eth_validate_addr,
1427 .ndo_select_queue = tun_select_queue,
1428 .ndo_features_check = passthru_features_check,
1429 .ndo_set_rx_headroom = tun_set_headroom,
1430 .ndo_get_stats64 = tun_net_get_stats64,
1432 .ndo_xdp_xmit = tun_xdp_xmit,
1433 .ndo_change_carrier = tun_net_change_carrier,
1436 static void tun_flow_init(struct tun_struct *tun)
1440 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
1441 INIT_HLIST_HEAD(&tun->flows[i]);
1443 tun->ageing_time = TUN_FLOW_EXPIRE;
1444 timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1445 mod_timer(&tun->flow_gc_timer,
1446 round_jiffies_up(jiffies + tun->ageing_time));
1449 static void tun_flow_uninit(struct tun_struct *tun)
1451 del_timer_sync(&tun->flow_gc_timer);
1452 tun_flow_flush(tun);
1456 #define MAX_MTU 65535
1458 /* Initialize net device. */
1459 static void tun_net_initialize(struct net_device *dev)
1461 struct tun_struct *tun = netdev_priv(dev);
1463 switch (tun->flags & TUN_TYPE_MASK) {
1465 dev->netdev_ops = &tun_netdev_ops;
1467 /* Point-to-Point TUN Device */
1468 dev->hard_header_len = 0;
1472 /* Zero header length */
1473 dev->type = ARPHRD_NONE;
1474 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
1478 dev->netdev_ops = &tap_netdev_ops;
1479 /* Ethernet TAP Device */
1481 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1482 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
1484 eth_hw_addr_random(dev);
1489 dev->min_mtu = MIN_MTU;
1490 dev->max_mtu = MAX_MTU - dev->hard_header_len;
1493 static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
1495 struct sock *sk = tfile->socket.sk;
1497 return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
1500 /* Character device part */
1503 static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
1505 struct tun_file *tfile = file->private_data;
1506 struct tun_struct *tun = tun_get(tfile);
1513 sk = tfile->socket.sk;
1515 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
1517 poll_wait(file, sk_sleep(sk), wait);
1519 if (!ptr_ring_empty(&tfile->tx_ring))
1520 mask |= EPOLLIN | EPOLLRDNORM;
1522 /* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
1523 * guarantee EPOLLOUT to be raised by either here or
1524 * tun_sock_write_space(). Then process could get notification
1525 * after it writes to a down device and meets -EIO.
1527 if (tun_sock_writeable(tun, tfile) ||
1528 (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1529 tun_sock_writeable(tun, tfile)))
1530 mask |= EPOLLOUT | EPOLLWRNORM;
1532 if (tun->dev->reg_state != NETREG_REGISTERED)
1539 static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
1541 const struct iov_iter *it)
1543 struct sk_buff *skb;
1548 if (it->nr_segs > MAX_SKB_FRAGS + 1 ||
1549 len > (ETH_MAX_MTU - NET_SKB_PAD - NET_IP_ALIGN))
1550 return ERR_PTR(-EMSGSIZE);
1553 skb = napi_get_frags(&tfile->napi);
1556 return ERR_PTR(-ENOMEM);
1558 linear = iov_iter_single_seg_count(it);
1559 err = __skb_grow(skb, linear);
1564 skb->data_len = len - linear;
1565 skb->truesize += skb->data_len;
1567 for (i = 1; i < it->nr_segs; i++) {
1568 size_t fragsz = it->iov[i].iov_len;
1572 if (fragsz == 0 || fragsz > PAGE_SIZE) {
1576 frag = netdev_alloc_frag(fragsz);
1581 page = virt_to_head_page(frag);
1582 skb_fill_page_desc(skb, i - 1, page,
1583 frag - page_address(page), fragsz);
1588 /* frees skb and all frags allocated with napi_alloc_frag() */
1589 napi_free_frags(&tfile->napi);
1590 return ERR_PTR(err);
1593 /* prepad is the amount to reserve at front. len is length after that.
1594 * linear is a hint as to how much to copy (usually headers). */
1595 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
1596 size_t prepad, size_t len,
1597 size_t linear, int noblock)
1599 struct sock *sk = tfile->socket.sk;
1600 struct sk_buff *skb;
1603 /* Under a page? Don't bother with paged skb. */
1604 if (prepad + len < PAGE_SIZE || !linear)
1607 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
1610 return ERR_PTR(err);
1612 skb_reserve(skb, prepad);
1613 skb_put(skb, linear);
1614 skb->data_len = len - linear;
1615 skb->len += len - linear;
1620 static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
1621 struct sk_buff *skb, int more)
1623 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1624 struct sk_buff_head process_queue;
1625 u32 rx_batched = tun->rx_batched;
1628 if (!rx_batched || (!more && skb_queue_empty(queue))) {
1630 skb_record_rx_queue(skb, tfile->queue_index);
1631 netif_receive_skb(skb);
1636 spin_lock(&queue->lock);
1637 if (!more || skb_queue_len(queue) == rx_batched) {
1638 __skb_queue_head_init(&process_queue);
1639 skb_queue_splice_tail_init(queue, &process_queue);
1642 __skb_queue_tail(queue, skb);
1644 spin_unlock(&queue->lock);
1647 struct sk_buff *nskb;
1650 while ((nskb = __skb_dequeue(&process_queue))) {
1651 skb_record_rx_queue(nskb, tfile->queue_index);
1652 netif_receive_skb(nskb);
1654 skb_record_rx_queue(skb, tfile->queue_index);
1655 netif_receive_skb(skb);
1660 static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
1661 int len, int noblock, bool zerocopy)
1663 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
1666 if (tfile->socket.sk->sk_sndbuf != INT_MAX)
1675 if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
1676 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
1682 static struct sk_buff *__tun_build_skb(struct tun_file *tfile,
1683 struct page_frag *alloc_frag, char *buf,
1684 int buflen, int len, int pad)
1686 struct sk_buff *skb = build_skb(buf, buflen);
1689 return ERR_PTR(-ENOMEM);
1691 skb_reserve(skb, pad);
1693 skb_set_owner_w(skb, tfile->socket.sk);
1695 get_page(alloc_frag->page);
1696 alloc_frag->offset += buflen;
1701 static int tun_xdp_act(struct tun_struct *tun, struct bpf_prog *xdp_prog,
1702 struct xdp_buff *xdp, u32 act)
1708 err = xdp_do_redirect(tun->dev, xdp, xdp_prog);
1713 err = tun_xdp_tx(tun->dev, xdp);
1720 bpf_warn_invalid_xdp_action(act);
1723 trace_xdp_exception(tun->dev, xdp_prog, act);
1726 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1733 static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1734 struct tun_file *tfile,
1735 struct iov_iter *from,
1736 struct virtio_net_hdr *hdr,
1737 int len, int *skb_xdp)
1739 struct page_frag *alloc_frag = ¤t->task_frag;
1740 struct bpf_prog *xdp_prog;
1741 int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1744 int pad = TUN_RX_PAD;
1748 xdp_prog = rcu_dereference(tun->xdp_prog);
1750 pad += XDP_PACKET_HEADROOM;
1751 buflen += SKB_DATA_ALIGN(len + pad);
1754 alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
1755 if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
1756 return ERR_PTR(-ENOMEM);
1758 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1759 copied = copy_page_from_iter(alloc_frag->page,
1760 alloc_frag->offset + pad,
1763 return ERR_PTR(-EFAULT);
1765 /* There's a small window that XDP may be set after the check
1766 * of xdp_prog above, this should be rare and for simplicity
1767 * we do XDP on skb in case the headroom is not enough.
1769 if (hdr->gso_type || !xdp_prog) {
1771 return __tun_build_skb(tfile, alloc_frag, buf, buflen, len,
1779 xdp_prog = rcu_dereference(tun->xdp_prog);
1781 struct xdp_buff xdp;
1784 xdp.data_hard_start = buf;
1785 xdp.data = buf + pad;
1786 xdp_set_data_meta_invalid(&xdp);
1787 xdp.data_end = xdp.data + len;
1788 xdp.rxq = &tfile->xdp_rxq;
1790 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1791 if (act == XDP_REDIRECT || act == XDP_TX) {
1792 get_page(alloc_frag->page);
1793 alloc_frag->offset += buflen;
1795 err = tun_xdp_act(tun, xdp_prog, &xdp, act);
1797 if (act == XDP_REDIRECT || act == XDP_TX)
1798 put_page(alloc_frag->page);
1802 if (err == XDP_REDIRECT)
1804 if (err != XDP_PASS)
1807 pad = xdp.data - xdp.data_hard_start;
1808 len = xdp.data_end - xdp.data;
1813 return __tun_build_skb(tfile, alloc_frag, buf, buflen, len, pad);
1821 /* Get packet from user space buffer */
1822 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1823 void *msg_control, struct iov_iter *from,
1824 int noblock, bool more)
1826 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1827 struct sk_buff *skb;
1828 size_t total_len = iov_iter_count(from);
1829 size_t len = total_len, align = tun->align, linear;
1830 struct virtio_net_hdr gso = { 0 };
1831 struct tun_pcpu_stats *stats;
1834 bool zerocopy = false;
1838 bool frags = tun_napi_frags_enabled(tfile);
1840 if (!(tun->flags & IFF_NO_PI)) {
1841 if (len < sizeof(pi))
1845 if (!copy_from_iter_full(&pi, sizeof(pi), from))
1849 if (tun->flags & IFF_VNET_HDR) {
1850 int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1852 if (len < vnet_hdr_sz)
1856 if (!copy_from_iter_full(&gso, sizeof(gso), from))
1859 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1860 tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
1861 gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
1863 if (tun16_to_cpu(tun, gso.hdr_len) > len)
1865 iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
1868 if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
1869 align += NET_IP_ALIGN;
1870 if (unlikely(len < ETH_HLEN ||
1871 (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
1875 good_linear = SKB_MAX_HEAD(align);
1878 struct iov_iter i = *from;
1880 /* There are 256 bytes to be copied in skb, so there is
1881 * enough room for skb expand head in case it is used.
1882 * The rest of the buffer is mapped from userspace.
1884 copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
1885 if (copylen > good_linear)
1886 copylen = good_linear;
1888 iov_iter_advance(&i, copylen);
1889 if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
1893 if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
1894 /* For the packet that is not easy to be processed
1895 * (e.g gso or jumbo packet), we will do it at after
1896 * skb was created with generic XDP routine.
1898 skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
1900 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1901 return PTR_ERR(skb);
1908 if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
1909 linear = good_linear;
1911 linear = tun16_to_cpu(tun, gso.hdr_len);
1915 mutex_lock(&tfile->napi_mutex);
1916 skb = tun_napi_alloc_frags(tfile, copylen, from);
1917 /* tun_napi_alloc_frags() enforces a layout for the skb.
1918 * If zerocopy is enabled, then this layout will be
1919 * overwritten by zerocopy_sg_from_iter().
1923 skb = tun_alloc_skb(tfile, align, copylen, linear,
1928 if (PTR_ERR(skb) != -EAGAIN)
1929 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1931 mutex_unlock(&tfile->napi_mutex);
1932 return PTR_ERR(skb);
1936 err = zerocopy_sg_from_iter(skb, from);
1938 err = skb_copy_datagram_from_iter(skb, 0, from, len);
1943 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1946 tfile->napi.skb = NULL;
1947 mutex_unlock(&tfile->napi_mutex);
1954 if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
1955 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1958 tfile->napi.skb = NULL;
1959 mutex_unlock(&tfile->napi_mutex);
1965 switch (tun->flags & TUN_TYPE_MASK) {
1967 if (tun->flags & IFF_NO_PI) {
1968 u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
1970 switch (ip_version) {
1972 pi.proto = htons(ETH_P_IP);
1975 pi.proto = htons(ETH_P_IPV6);
1978 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1984 skb_reset_mac_header(skb);
1985 skb->protocol = pi.proto;
1986 skb->dev = tun->dev;
1989 if (frags && !pskb_may_pull(skb, ETH_HLEN)) {
1993 skb->protocol = eth_type_trans(skb, tun->dev);
1997 /* copy skb_ubuf_info for callback when skb has no error */
1999 skb_shinfo(skb)->destructor_arg = msg_control;
2000 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
2001 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
2002 } else if (msg_control) {
2003 struct ubuf_info *uarg = msg_control;
2004 uarg->callback(uarg, false);
2007 skb_reset_network_header(skb);
2008 skb_probe_transport_header(skb);
2009 skb_record_rx_queue(skb, tfile->queue_index);
2012 struct bpf_prog *xdp_prog;
2017 xdp_prog = rcu_dereference(tun->xdp_prog);
2019 ret = do_xdp_generic(xdp_prog, skb);
2020 if (ret != XDP_PASS) {
2024 tfile->napi.skb = NULL;
2025 mutex_unlock(&tfile->napi_mutex);
2034 /* Compute the costly rx hash only if needed for flow updates.
2035 * We may get a very small possibility of OOO during switching, not
2036 * worth to optimize.
2038 if (!rcu_access_pointer(tun->steering_prog) && tun->numqueues > 1 &&
2040 rxhash = __skb_get_hash_symmetric(skb);
2043 if (unlikely(!(tun->dev->flags & IFF_UP))) {
2052 /* Exercise flow dissector code path. */
2053 skb_push(skb, ETH_HLEN);
2054 headlen = eth_get_headlen(tun->dev, skb->data,
2057 if (unlikely(headlen > skb_headlen(skb))) {
2060 this_cpu_inc(tun->pcpu_stats->rx_dropped);
2062 napi_free_frags(&tfile->napi);
2064 mutex_unlock(&tfile->napi_mutex);
2068 if (likely(napi_schedule_prep(&tfile->napi))) {
2070 napi_gro_frags(&tfile->napi);
2071 napi_complete(&tfile->napi);
2077 mutex_unlock(&tfile->napi_mutex);
2078 } else if (tfile->napi_enabled) {
2079 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
2082 spin_lock_bh(&queue->lock);
2083 __skb_queue_tail(queue, skb);
2084 queue_len = skb_queue_len(queue);
2085 spin_unlock(&queue->lock);
2087 if (!more || queue_len > NAPI_POLL_WEIGHT)
2088 napi_schedule(&tfile->napi);
2091 } else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
2092 tun_rx_batched(tun, tfile, skb, more);
2098 stats = get_cpu_ptr(tun->pcpu_stats);
2099 u64_stats_update_begin(&stats->syncp);
2100 stats->rx_packets++;
2101 stats->rx_bytes += len;
2102 u64_stats_update_end(&stats->syncp);
2106 tun_flow_update(tun, rxhash, tfile);
2111 static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
2113 struct file *file = iocb->ki_filp;
2114 struct tun_file *tfile = file->private_data;
2115 struct tun_struct *tun = tun_get(tfile);
2122 if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
2125 result = tun_get_user(tun, tfile, NULL, from, noblock, false);
2131 static ssize_t tun_put_user_xdp(struct tun_struct *tun,
2132 struct tun_file *tfile,
2133 struct xdp_frame *xdp_frame,
2134 struct iov_iter *iter)
2136 int vnet_hdr_sz = 0;
2137 size_t size = xdp_frame->len;
2138 struct tun_pcpu_stats *stats;
2141 if (tun->flags & IFF_VNET_HDR) {
2142 struct virtio_net_hdr gso = { 0 };
2144 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2145 if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
2147 if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
2150 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2153 ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
2155 stats = get_cpu_ptr(tun->pcpu_stats);
2156 u64_stats_update_begin(&stats->syncp);
2157 stats->tx_packets++;
2158 stats->tx_bytes += ret;
2159 u64_stats_update_end(&stats->syncp);
2160 put_cpu_ptr(tun->pcpu_stats);
2165 /* Put packet to the user space buffer */
2166 static ssize_t tun_put_user(struct tun_struct *tun,
2167 struct tun_file *tfile,
2168 struct sk_buff *skb,
2169 struct iov_iter *iter)
2171 struct tun_pi pi = { 0, skb->protocol };
2172 struct tun_pcpu_stats *stats;
2174 int vlan_offset = 0;
2176 int vnet_hdr_sz = 0;
2178 if (skb_vlan_tag_present(skb))
2179 vlan_hlen = VLAN_HLEN;
2181 if (tun->flags & IFF_VNET_HDR)
2182 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2184 total = skb->len + vlan_hlen + vnet_hdr_sz;
2186 if (!(tun->flags & IFF_NO_PI)) {
2187 if (iov_iter_count(iter) < sizeof(pi))
2190 total += sizeof(pi);
2191 if (iov_iter_count(iter) < total) {
2192 /* Packet will be striped */
2193 pi.flags |= TUN_PKT_STRIP;
2196 if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
2201 struct virtio_net_hdr gso;
2203 if (iov_iter_count(iter) < vnet_hdr_sz)
2206 if (virtio_net_hdr_from_skb(skb, &gso,
2207 tun_is_little_endian(tun), true,
2209 struct skb_shared_info *sinfo = skb_shinfo(skb);
2210 pr_err("unexpected GSO type: "
2211 "0x%x, gso_size %d, hdr_len %d\n",
2212 sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
2213 tun16_to_cpu(tun, gso.hdr_len));
2214 print_hex_dump(KERN_ERR, "tun: ",
2217 min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
2222 if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
2225 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2232 veth.h_vlan_proto = skb->vlan_proto;
2233 veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
2235 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
2237 ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
2238 if (ret || !iov_iter_count(iter))
2241 ret = copy_to_iter(&veth, sizeof(veth), iter);
2242 if (ret != sizeof(veth) || !iov_iter_count(iter))
2246 skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
2249 /* caller is in process context, */
2250 stats = get_cpu_ptr(tun->pcpu_stats);
2251 u64_stats_update_begin(&stats->syncp);
2252 stats->tx_packets++;
2253 stats->tx_bytes += skb->len + vlan_hlen;
2254 u64_stats_update_end(&stats->syncp);
2255 put_cpu_ptr(tun->pcpu_stats);
2260 static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
2262 DECLARE_WAITQUEUE(wait, current);
2266 ptr = ptr_ring_consume(&tfile->tx_ring);
2274 add_wait_queue(&tfile->socket.wq.wait, &wait);
2277 set_current_state(TASK_INTERRUPTIBLE);
2278 ptr = ptr_ring_consume(&tfile->tx_ring);
2281 if (signal_pending(current)) {
2282 error = -ERESTARTSYS;
2285 if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
2293 __set_current_state(TASK_RUNNING);
2294 remove_wait_queue(&tfile->socket.wq.wait, &wait);
2301 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
2302 struct iov_iter *to,
2303 int noblock, void *ptr)
2308 tun_debug(KERN_INFO, tun, "tun_do_read\n");
2310 if (!iov_iter_count(to)) {
2316 /* Read frames from ring */
2317 ptr = tun_ring_recv(tfile, noblock, &err);
2322 if (tun_is_xdp_frame(ptr)) {
2323 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2325 ret = tun_put_user_xdp(tun, tfile, xdpf, to);
2326 xdp_return_frame(xdpf);
2328 struct sk_buff *skb = ptr;
2330 ret = tun_put_user(tun, tfile, skb, to);
2331 if (unlikely(ret < 0))
2340 static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
2342 struct file *file = iocb->ki_filp;
2343 struct tun_file *tfile = file->private_data;
2344 struct tun_struct *tun = tun_get(tfile);
2345 ssize_t len = iov_iter_count(to), ret;
2351 if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
2354 ret = tun_do_read(tun, tfile, to, noblock, NULL);
2355 ret = min_t(ssize_t, ret, len);
2362 static void tun_prog_free(struct rcu_head *rcu)
2364 struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
2366 bpf_prog_destroy(prog->prog);
2370 static int __tun_set_ebpf(struct tun_struct *tun,
2371 struct tun_prog __rcu **prog_p,
2372 struct bpf_prog *prog)
2374 struct tun_prog *old, *new = NULL;
2377 new = kmalloc(sizeof(*new), GFP_KERNEL);
2383 spin_lock_bh(&tun->lock);
2384 old = rcu_dereference_protected(*prog_p,
2385 lockdep_is_held(&tun->lock));
2386 rcu_assign_pointer(*prog_p, new);
2387 spin_unlock_bh(&tun->lock);
2390 call_rcu(&old->rcu, tun_prog_free);
2395 static void tun_free_netdev(struct net_device *dev)
2397 struct tun_struct *tun = netdev_priv(dev);
2399 BUG_ON(!(list_empty(&tun->disabled)));
2400 free_percpu(tun->pcpu_stats);
2401 tun_flow_uninit(tun);
2402 security_tun_dev_free_security(tun->security);
2403 __tun_set_ebpf(tun, &tun->steering_prog, NULL);
2404 __tun_set_ebpf(tun, &tun->filter_prog, NULL);
2407 static void tun_setup(struct net_device *dev)
2409 struct tun_struct *tun = netdev_priv(dev);
2411 tun->owner = INVALID_UID;
2412 tun->group = INVALID_GID;
2413 tun_default_link_ksettings(dev, &tun->link_ksettings);
2415 dev->ethtool_ops = &tun_ethtool_ops;
2416 dev->needs_free_netdev = true;
2417 dev->priv_destructor = tun_free_netdev;
2418 /* We prefer our own queue length */
2419 dev->tx_queue_len = TUN_READQ_SIZE;
2422 /* Trivial set of netlink ops to allow deleting tun or tap
2423 * device with netlink.
2425 static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2426 struct netlink_ext_ack *extack)
2428 NL_SET_ERR_MSG(extack,
2429 "tun/tap creation via rtnetlink is not supported.");
2433 static size_t tun_get_size(const struct net_device *dev)
2435 BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
2436 BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
2438 return nla_total_size(sizeof(uid_t)) + /* OWNER */
2439 nla_total_size(sizeof(gid_t)) + /* GROUP */
2440 nla_total_size(sizeof(u8)) + /* TYPE */
2441 nla_total_size(sizeof(u8)) + /* PI */
2442 nla_total_size(sizeof(u8)) + /* VNET_HDR */
2443 nla_total_size(sizeof(u8)) + /* PERSIST */
2444 nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
2445 nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
2446 nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
2450 static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
2452 struct tun_struct *tun = netdev_priv(dev);
2454 if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
2455 goto nla_put_failure;
2456 if (uid_valid(tun->owner) &&
2457 nla_put_u32(skb, IFLA_TUN_OWNER,
2458 from_kuid_munged(current_user_ns(), tun->owner)))
2459 goto nla_put_failure;
2460 if (gid_valid(tun->group) &&
2461 nla_put_u32(skb, IFLA_TUN_GROUP,
2462 from_kgid_munged(current_user_ns(), tun->group)))
2463 goto nla_put_failure;
2464 if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
2465 goto nla_put_failure;
2466 if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
2467 goto nla_put_failure;
2468 if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
2469 goto nla_put_failure;
2470 if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
2471 !!(tun->flags & IFF_MULTI_QUEUE)))
2472 goto nla_put_failure;
2473 if (tun->flags & IFF_MULTI_QUEUE) {
2474 if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
2475 goto nla_put_failure;
2476 if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
2478 goto nla_put_failure;
2487 static struct rtnl_link_ops tun_link_ops __read_mostly = {
2489 .priv_size = sizeof(struct tun_struct),
2491 .validate = tun_validate,
2492 .get_size = tun_get_size,
2493 .fill_info = tun_fill_info,
2496 static void tun_sock_write_space(struct sock *sk)
2498 struct tun_file *tfile;
2499 wait_queue_head_t *wqueue;
2501 if (!sock_writeable(sk))
2504 if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
2507 wqueue = sk_sleep(sk);
2508 if (wqueue && waitqueue_active(wqueue))
2509 wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
2510 EPOLLWRNORM | EPOLLWRBAND);
2512 tfile = container_of(sk, struct tun_file, sk);
2513 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
2516 static void tun_put_page(struct tun_page *tpage)
2519 __page_frag_cache_drain(tpage->page, tpage->count);
2522 static int tun_xdp_one(struct tun_struct *tun,
2523 struct tun_file *tfile,
2524 struct xdp_buff *xdp, int *flush,
2525 struct tun_page *tpage)
2527 unsigned int datasize = xdp->data_end - xdp->data;
2528 struct tun_xdp_hdr *hdr = xdp->data_hard_start;
2529 struct virtio_net_hdr *gso = &hdr->gso;
2530 struct tun_pcpu_stats *stats;
2531 struct bpf_prog *xdp_prog;
2532 struct sk_buff *skb = NULL;
2533 u32 rxhash = 0, act;
2534 int buflen = hdr->buflen;
2536 bool skb_xdp = false;
2539 xdp_prog = rcu_dereference(tun->xdp_prog);
2541 if (gso->gso_type) {
2545 xdp_set_data_meta_invalid(xdp);
2546 xdp->rxq = &tfile->xdp_rxq;
2548 act = bpf_prog_run_xdp(xdp_prog, xdp);
2549 err = tun_xdp_act(tun, xdp_prog, xdp, act);
2551 put_page(virt_to_head_page(xdp->data));
2564 page = virt_to_head_page(xdp->data);
2565 if (tpage->page == page) {
2568 tun_put_page(tpage);
2577 skb = build_skb(xdp->data_hard_start, buflen);
2583 skb_reserve(skb, xdp->data - xdp->data_hard_start);
2584 skb_put(skb, xdp->data_end - xdp->data);
2586 if (virtio_net_hdr_to_skb(skb, gso, tun_is_little_endian(tun))) {
2587 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
2593 skb->protocol = eth_type_trans(skb, tun->dev);
2594 skb_reset_network_header(skb);
2595 skb_probe_transport_header(skb);
2596 skb_record_rx_queue(skb, tfile->queue_index);
2599 err = do_xdp_generic(xdp_prog, skb);
2600 if (err != XDP_PASS)
2604 if (!rcu_dereference(tun->steering_prog) && tun->numqueues > 1 &&
2606 rxhash = __skb_get_hash_symmetric(skb);
2608 netif_receive_skb(skb);
2610 /* No need for get_cpu_ptr() here since this function is
2611 * always called with bh disabled
2613 stats = this_cpu_ptr(tun->pcpu_stats);
2614 u64_stats_update_begin(&stats->syncp);
2615 stats->rx_packets++;
2616 stats->rx_bytes += datasize;
2617 u64_stats_update_end(&stats->syncp);
2620 tun_flow_update(tun, rxhash, tfile);
2626 static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
2629 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2630 struct tun_struct *tun = tun_get(tfile);
2631 struct tun_msg_ctl *ctl = m->msg_control;
2632 struct xdp_buff *xdp;
2637 if (m->msg_controllen == sizeof(struct tun_msg_ctl) &&
2638 ctl && ctl->type == TUN_MSG_PTR) {
2639 struct tun_page tpage;
2643 memset(&tpage, 0, sizeof(tpage));
2648 for (i = 0; i < n; i++) {
2649 xdp = &((struct xdp_buff *)ctl->ptr)[i];
2650 tun_xdp_one(tun, tfile, xdp, &flush, &tpage);
2659 tun_put_page(&tpage);
2665 ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
2666 m->msg_flags & MSG_DONTWAIT,
2667 m->msg_flags & MSG_MORE);
2673 static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
2676 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2677 struct tun_struct *tun = tun_get(tfile);
2678 void *ptr = m->msg_control;
2686 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
2690 if (flags & MSG_ERRQUEUE) {
2691 ret = sock_recv_errqueue(sock->sk, m, total_len,
2692 SOL_PACKET, TUN_TX_TIMESTAMP);
2695 ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
2696 if (ret > (ssize_t)total_len) {
2697 m->msg_flags |= MSG_TRUNC;
2698 ret = flags & MSG_TRUNC ? ret : total_len;
2711 static int tun_ptr_peek_len(void *ptr)
2714 if (tun_is_xdp_frame(ptr)) {
2715 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
2719 return __skb_array_len_with_tag(ptr);
2725 static int tun_peek_len(struct socket *sock)
2727 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2728 struct tun_struct *tun;
2731 tun = tun_get(tfile);
2735 ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
2741 /* Ops structure to mimic raw sockets with tun */
2742 static const struct proto_ops tun_socket_ops = {
2743 .peek_len = tun_peek_len,
2744 .sendmsg = tun_sendmsg,
2745 .recvmsg = tun_recvmsg,
2748 static struct proto tun_proto = {
2750 .owner = THIS_MODULE,
2751 .obj_size = sizeof(struct tun_file),
2754 static int tun_flags(struct tun_struct *tun)
2756 return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
2759 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2762 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2763 return sprintf(buf, "0x%x\n", tun_flags(tun));
2766 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2769 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2770 return uid_valid(tun->owner)?
2771 sprintf(buf, "%u\n",
2772 from_kuid_munged(current_user_ns(), tun->owner)):
2773 sprintf(buf, "-1\n");
2776 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2779 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2780 return gid_valid(tun->group) ?
2781 sprintf(buf, "%u\n",
2782 from_kgid_munged(current_user_ns(), tun->group)):
2783 sprintf(buf, "-1\n");
2786 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2787 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2788 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2790 static struct attribute *tun_dev_attrs[] = {
2791 &dev_attr_tun_flags.attr,
2792 &dev_attr_owner.attr,
2793 &dev_attr_group.attr,
2797 static const struct attribute_group tun_attr_group = {
2798 .attrs = tun_dev_attrs
2801 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
2803 struct tun_struct *tun;
2804 struct tun_file *tfile = file->private_data;
2805 struct net_device *dev;
2808 if (tfile->detached)
2811 if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
2812 if (!capable(CAP_NET_ADMIN))
2815 if (!(ifr->ifr_flags & IFF_NAPI) ||
2816 (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
2820 dev = __dev_get_by_name(net, ifr->ifr_name);
2822 if (ifr->ifr_flags & IFF_TUN_EXCL)
2824 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
2825 tun = netdev_priv(dev);
2826 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
2827 tun = netdev_priv(dev);
2831 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
2832 !!(tun->flags & IFF_MULTI_QUEUE))
2835 if (tun_not_capable(tun))
2837 err = security_tun_dev_open(tun->security);
2841 err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
2842 ifr->ifr_flags & IFF_NAPI,
2843 ifr->ifr_flags & IFF_NAPI_FRAGS, true);
2847 if (tun->flags & IFF_MULTI_QUEUE &&
2848 (tun->numqueues + tun->numdisabled > 1)) {
2849 /* One or more queue has already been attached, no need
2850 * to initialize the device again.
2852 netdev_state_change(dev);
2856 tun->flags = (tun->flags & ~TUN_FEATURES) |
2857 (ifr->ifr_flags & TUN_FEATURES);
2859 netdev_state_change(dev);
2862 unsigned long flags = 0;
2863 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2866 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2868 err = security_tun_dev_create();
2873 if (ifr->ifr_flags & IFF_TUN) {
2877 } else if (ifr->ifr_flags & IFF_TAP) {
2885 name = ifr->ifr_name;
2887 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
2888 NET_NAME_UNKNOWN, tun_setup, queues,
2894 dev_net_set(dev, net);
2895 dev->rtnl_link_ops = &tun_link_ops;
2896 dev->ifindex = tfile->ifindex;
2897 dev->sysfs_groups[0] = &tun_attr_group;
2899 tun = netdev_priv(dev);
2902 tun->txflt.count = 0;
2903 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
2905 tun->align = NET_SKB_PAD;
2906 tun->filter_attached = false;
2907 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
2908 tun->rx_batched = 0;
2909 RCU_INIT_POINTER(tun->steering_prog, NULL);
2914 tun_net_initialize(dev);
2916 err = register_netdevice(tun->dev);
2921 /* free_netdev() won't check refcnt, to aovid race
2922 * with dev_put() we need publish tun after registration.
2924 rcu_assign_pointer(tfile->tun, tun);
2927 netif_carrier_on(tun->dev);
2929 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
2931 /* Make sure persistent devices do not get stuck in
2934 if (netif_running(tun->dev))
2935 netif_tx_wake_all_queues(tun->dev);
2937 strcpy(ifr->ifr_name, tun->dev->name);
2941 static void tun_get_iff(struct tun_struct *tun, struct ifreq *ifr)
2943 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
2945 strcpy(ifr->ifr_name, tun->dev->name);
2947 ifr->ifr_flags = tun_flags(tun);
2951 /* This is like a cut-down ethtool ops, except done via tun fd so no
2952 * privs required. */
2953 static int set_offload(struct tun_struct *tun, unsigned long arg)
2955 netdev_features_t features = 0;
2957 if (arg & TUN_F_CSUM) {
2958 features |= NETIF_F_HW_CSUM;
2961 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
2962 if (arg & TUN_F_TSO_ECN) {
2963 features |= NETIF_F_TSO_ECN;
2964 arg &= ~TUN_F_TSO_ECN;
2966 if (arg & TUN_F_TSO4)
2967 features |= NETIF_F_TSO;
2968 if (arg & TUN_F_TSO6)
2969 features |= NETIF_F_TSO6;
2970 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
2976 /* This gives the user a way to test for new features in future by
2977 * trying to set them. */
2981 tun->set_features = features;
2982 tun->dev->wanted_features &= ~TUN_USER_FEATURES;
2983 tun->dev->wanted_features |= features;
2984 netdev_update_features(tun->dev);
2989 static void tun_detach_filter(struct tun_struct *tun, int n)
2992 struct tun_file *tfile;
2994 for (i = 0; i < n; i++) {
2995 tfile = rtnl_dereference(tun->tfiles[i]);
2996 lock_sock(tfile->socket.sk);
2997 sk_detach_filter(tfile->socket.sk);
2998 release_sock(tfile->socket.sk);
3001 tun->filter_attached = false;
3004 static int tun_attach_filter(struct tun_struct *tun)
3007 struct tun_file *tfile;
3009 for (i = 0; i < tun->numqueues; i++) {
3010 tfile = rtnl_dereference(tun->tfiles[i]);
3011 lock_sock(tfile->socket.sk);
3012 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
3013 release_sock(tfile->socket.sk);
3015 tun_detach_filter(tun, i);
3020 tun->filter_attached = true;
3024 static void tun_set_sndbuf(struct tun_struct *tun)
3026 struct tun_file *tfile;
3029 for (i = 0; i < tun->numqueues; i++) {
3030 tfile = rtnl_dereference(tun->tfiles[i]);
3031 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
3035 static int tun_set_queue(struct file *file, struct ifreq *ifr)
3037 struct tun_file *tfile = file->private_data;
3038 struct tun_struct *tun;
3043 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
3044 tun = tfile->detached;
3049 ret = security_tun_dev_attach_queue(tun->security);
3052 ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
3053 tun->flags & IFF_NAPI_FRAGS, true);
3054 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
3055 tun = rtnl_dereference(tfile->tun);
3056 if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
3059 __tun_detach(tfile, false);
3064 netdev_state_change(tun->dev);
3071 static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog **prog_p,
3074 struct bpf_prog *prog;
3077 if (copy_from_user(&fd, data, sizeof(fd)))
3083 prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
3085 return PTR_ERR(prog);
3088 return __tun_set_ebpf(tun, prog_p, prog);
3091 /* Return correct value for tun->dev->addr_len based on tun->dev->type. */
3092 static unsigned char tun_get_addr_len(unsigned short type)
3096 case ARPHRD_TUNNEL6:
3097 return sizeof(struct in6_addr);
3104 case ARPHRD_IEEE802154:
3105 case ARPHRD_IEEE802154_MONITOR:
3106 return IEEE802154_EXTENDED_ADDR_LEN;
3107 case ARPHRD_PHONET_PIPE:
3111 case ARPHRD_6LOWPAN:
3112 return EUI64_ADDR_LEN;
3117 case ARPHRD_IEEE802:
3120 return ROSE_ADDR_LEN;
3122 return AX25_ADDR_LEN;
3123 case ARPHRD_LOCALTLK:
3130 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
3131 unsigned long arg, int ifreq_len)
3133 struct tun_file *tfile = file->private_data;
3134 struct net *net = sock_net(&tfile->sk);
3135 struct tun_struct *tun;
3136 void __user* argp = (void __user*)arg;
3137 unsigned int ifindex, carrier;
3145 bool do_notify = false;
3147 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
3148 (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
3149 if (copy_from_user(&ifr, argp, ifreq_len))
3152 memset(&ifr, 0, sizeof(ifr));
3154 if (cmd == TUNGETFEATURES) {
3155 /* Currently this just means: "what IFF flags are valid?".
3156 * This is needed because we never checked for invalid flags on
3159 return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
3160 (unsigned int __user*)argp);
3161 } else if (cmd == TUNSETQUEUE) {
3162 return tun_set_queue(file, &ifr);
3163 } else if (cmd == SIOCGSKNS) {
3164 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3166 return open_related_ns(&net->ns, get_net_ns);
3172 tun = tun_get(tfile);
3173 if (cmd == TUNSETIFF) {
3178 ifr.ifr_name[IFNAMSIZ-1] = '\0';
3180 ret = tun_set_iff(net, file, &ifr);
3185 if (copy_to_user(argp, &ifr, ifreq_len))
3189 if (cmd == TUNSETIFINDEX) {
3195 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
3199 tfile->ifindex = ifindex;
3207 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
3209 net = dev_net(tun->dev);
3213 tun_get_iff(tun, &ifr);
3215 if (tfile->detached)
3216 ifr.ifr_flags |= IFF_DETACH_QUEUE;
3217 if (!tfile->socket.sk->sk_filter)
3218 ifr.ifr_flags |= IFF_NOFILTER;
3220 if (copy_to_user(argp, &ifr, ifreq_len))
3225 /* Disable/Enable checksum */
3227 /* [unimplemented] */
3228 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
3229 arg ? "disabled" : "enabled");
3233 /* Disable/Enable persist mode. Keep an extra reference to the
3234 * module to prevent the module being unprobed.
3236 if (arg && !(tun->flags & IFF_PERSIST)) {
3237 tun->flags |= IFF_PERSIST;
3238 __module_get(THIS_MODULE);
3241 if (!arg && (tun->flags & IFF_PERSIST)) {
3242 tun->flags &= ~IFF_PERSIST;
3243 module_put(THIS_MODULE);
3247 tun_debug(KERN_INFO, tun, "persist %s\n",
3248 arg ? "enabled" : "disabled");
3252 /* Set owner of the device */
3253 owner = make_kuid(current_user_ns(), arg);
3254 if (!uid_valid(owner)) {
3260 tun_debug(KERN_INFO, tun, "owner set to %u\n",
3261 from_kuid(&init_user_ns, tun->owner));
3265 /* Set group of the device */
3266 group = make_kgid(current_user_ns(), arg);
3267 if (!gid_valid(group)) {
3273 tun_debug(KERN_INFO, tun, "group set to %u\n",
3274 from_kgid(&init_user_ns, tun->group));
3278 /* Only allow setting the type when the interface is down */
3279 if (tun->dev->flags & IFF_UP) {
3280 tun_debug(KERN_INFO, tun,
3281 "Linktype set failed because interface is up\n");
3284 tun->dev->type = (int) arg;
3285 tun->dev->addr_len = tun_get_addr_len(tun->dev->type);
3286 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
3298 ret = set_offload(tun, arg);
3301 case TUNSETTXFILTER:
3302 /* Can be set only for TAPs */
3304 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3306 ret = update_filter(&tun->txflt, (void __user *)arg);
3310 /* Get hw address */
3311 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
3312 dev_get_mac_address(&ifr.ifr_hwaddr, net, tun->dev->name);
3313 if (copy_to_user(argp, &ifr, ifreq_len))
3318 /* Set hw address */
3319 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
3320 ifr.ifr_hwaddr.sa_data);
3322 ret = dev_set_mac_address_user(tun->dev, &ifr.ifr_hwaddr, NULL);
3326 sndbuf = tfile->socket.sk->sk_sndbuf;
3327 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
3332 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
3341 tun->sndbuf = sndbuf;
3342 tun_set_sndbuf(tun);
3345 case TUNGETVNETHDRSZ:
3346 vnet_hdr_sz = tun->vnet_hdr_sz;
3347 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
3351 case TUNSETVNETHDRSZ:
3352 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
3356 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
3361 tun->vnet_hdr_sz = vnet_hdr_sz;
3365 le = !!(tun->flags & TUN_VNET_LE);
3366 if (put_user(le, (int __user *)argp))
3371 if (get_user(le, (int __user *)argp)) {
3376 tun->flags |= TUN_VNET_LE;
3378 tun->flags &= ~TUN_VNET_LE;
3382 ret = tun_get_vnet_be(tun, argp);
3386 ret = tun_set_vnet_be(tun, argp);
3389 case TUNATTACHFILTER:
3390 /* Can be set only for TAPs */
3392 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3395 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
3398 ret = tun_attach_filter(tun);
3401 case TUNDETACHFILTER:
3402 /* Can be set only for TAPs */
3404 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3407 tun_detach_filter(tun, tun->numqueues);
3412 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
3415 if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
3420 case TUNSETSTEERINGEBPF:
3421 ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
3424 case TUNSETFILTEREBPF:
3425 ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3430 if (copy_from_user(&carrier, argp, sizeof(carrier)))
3433 ret = tun_net_change_carrier(tun->dev, (bool)carrier);
3436 case TUNGETDEVNETNS:
3438 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3440 ret = open_related_ns(&net->ns, get_net_ns);
3449 netdev_state_change(tun->dev);
3458 static long tun_chr_ioctl(struct file *file,
3459 unsigned int cmd, unsigned long arg)
3461 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
3464 #ifdef CONFIG_COMPAT
3465 static long tun_chr_compat_ioctl(struct file *file,
3466 unsigned int cmd, unsigned long arg)
3471 case TUNSETTXFILTER:
3476 arg = (unsigned long)compat_ptr(arg);
3479 arg = (compat_ulong_t)arg;
3484 * compat_ifreq is shorter than ifreq, so we must not access beyond
3485 * the end of that structure. All fields that are used in this
3486 * driver are compatible though, we don't need to convert the
3489 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
3491 #endif /* CONFIG_COMPAT */
3493 static int tun_chr_fasync(int fd, struct file *file, int on)
3495 struct tun_file *tfile = file->private_data;
3498 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
3502 __f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
3503 tfile->flags |= TUN_FASYNC;
3505 tfile->flags &= ~TUN_FASYNC;
3511 static int tun_chr_open(struct inode *inode, struct file * file)
3513 struct net *net = current->nsproxy->net_ns;
3514 struct tun_file *tfile;
3516 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
3518 tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
3522 if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
3523 sk_free(&tfile->sk);
3527 mutex_init(&tfile->napi_mutex);
3528 RCU_INIT_POINTER(tfile->tun, NULL);
3532 init_waitqueue_head(&tfile->socket.wq.wait);
3534 tfile->socket.file = file;
3535 tfile->socket.ops = &tun_socket_ops;
3537 sock_init_data_uid(&tfile->socket, &tfile->sk, inode->i_uid);
3539 tfile->sk.sk_write_space = tun_sock_write_space;
3540 tfile->sk.sk_sndbuf = INT_MAX;
3542 file->private_data = tfile;
3543 INIT_LIST_HEAD(&tfile->next);
3545 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
3550 static int tun_chr_close(struct inode *inode, struct file *file)
3552 struct tun_file *tfile = file->private_data;
3554 tun_detach(tfile, true);
3559 #ifdef CONFIG_PROC_FS
3560 static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
3562 struct tun_file *tfile = file->private_data;
3563 struct tun_struct *tun;
3566 memset(&ifr, 0, sizeof(ifr));
3569 tun = tun_get(tfile);
3571 tun_get_iff(tun, &ifr);
3577 seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
3581 static const struct file_operations tun_fops = {
3582 .owner = THIS_MODULE,
3583 .llseek = no_llseek,
3584 .read_iter = tun_chr_read_iter,
3585 .write_iter = tun_chr_write_iter,
3586 .poll = tun_chr_poll,
3587 .unlocked_ioctl = tun_chr_ioctl,
3588 #ifdef CONFIG_COMPAT
3589 .compat_ioctl = tun_chr_compat_ioctl,
3591 .open = tun_chr_open,
3592 .release = tun_chr_close,
3593 .fasync = tun_chr_fasync,
3594 #ifdef CONFIG_PROC_FS
3595 .show_fdinfo = tun_chr_show_fdinfo,
3599 static struct miscdevice tun_miscdev = {
3602 .nodename = "net/tun",
3606 /* ethtool interface */
3608 static void tun_default_link_ksettings(struct net_device *dev,
3609 struct ethtool_link_ksettings *cmd)
3611 ethtool_link_ksettings_zero_link_mode(cmd, supported);
3612 ethtool_link_ksettings_zero_link_mode(cmd, advertising);
3613 cmd->base.speed = SPEED_10;
3614 cmd->base.duplex = DUPLEX_FULL;
3615 cmd->base.port = PORT_TP;
3616 cmd->base.phy_address = 0;
3617 cmd->base.autoneg = AUTONEG_DISABLE;
3620 static int tun_get_link_ksettings(struct net_device *dev,
3621 struct ethtool_link_ksettings *cmd)
3623 struct tun_struct *tun = netdev_priv(dev);
3625 memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
3629 static int tun_set_link_ksettings(struct net_device *dev,
3630 const struct ethtool_link_ksettings *cmd)
3632 struct tun_struct *tun = netdev_priv(dev);
3634 memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
3638 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
3640 struct tun_struct *tun = netdev_priv(dev);
3642 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
3643 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
3645 switch (tun->flags & TUN_TYPE_MASK) {
3647 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
3650 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
3655 static u32 tun_get_msglevel(struct net_device *dev)
3658 struct tun_struct *tun = netdev_priv(dev);
3665 static void tun_set_msglevel(struct net_device *dev, u32 value)
3668 struct tun_struct *tun = netdev_priv(dev);
3673 static int tun_get_coalesce(struct net_device *dev,
3674 struct ethtool_coalesce *ec)
3676 struct tun_struct *tun = netdev_priv(dev);
3678 ec->rx_max_coalesced_frames = tun->rx_batched;
3683 static int tun_set_coalesce(struct net_device *dev,
3684 struct ethtool_coalesce *ec)
3686 struct tun_struct *tun = netdev_priv(dev);
3688 if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
3689 tun->rx_batched = NAPI_POLL_WEIGHT;
3691 tun->rx_batched = ec->rx_max_coalesced_frames;
3696 static const struct ethtool_ops tun_ethtool_ops = {
3697 .get_drvinfo = tun_get_drvinfo,
3698 .get_msglevel = tun_get_msglevel,
3699 .set_msglevel = tun_set_msglevel,
3700 .get_link = ethtool_op_get_link,
3701 .get_ts_info = ethtool_op_get_ts_info,
3702 .get_coalesce = tun_get_coalesce,
3703 .set_coalesce = tun_set_coalesce,
3704 .get_link_ksettings = tun_get_link_ksettings,
3705 .set_link_ksettings = tun_set_link_ksettings,
3708 static int tun_queue_resize(struct tun_struct *tun)
3710 struct net_device *dev = tun->dev;
3711 struct tun_file *tfile;
3712 struct ptr_ring **rings;
3713 int n = tun->numqueues + tun->numdisabled;
3716 rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
3720 for (i = 0; i < tun->numqueues; i++) {
3721 tfile = rtnl_dereference(tun->tfiles[i]);
3722 rings[i] = &tfile->tx_ring;
3724 list_for_each_entry(tfile, &tun->disabled, next)
3725 rings[i++] = &tfile->tx_ring;
3727 ret = ptr_ring_resize_multiple(rings, n,
3728 dev->tx_queue_len, GFP_KERNEL,
3735 static int tun_device_event(struct notifier_block *unused,
3736 unsigned long event, void *ptr)
3738 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3739 struct tun_struct *tun = netdev_priv(dev);
3742 if (dev->rtnl_link_ops != &tun_link_ops)
3746 case NETDEV_CHANGE_TX_QUEUE_LEN:
3747 if (tun_queue_resize(tun))
3751 for (i = 0; i < tun->numqueues; i++) {
3752 struct tun_file *tfile;
3754 tfile = rtnl_dereference(tun->tfiles[i]);
3755 tfile->socket.sk->sk_write_space(tfile->socket.sk);
3765 static struct notifier_block tun_notifier_block __read_mostly = {
3766 .notifier_call = tun_device_event,
3769 static int __init tun_init(void)
3773 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
3775 ret = rtnl_link_register(&tun_link_ops);
3777 pr_err("Can't register link_ops\n");
3781 ret = misc_register(&tun_miscdev);
3783 pr_err("Can't register misc device %d\n", TUN_MINOR);
3787 ret = register_netdevice_notifier(&tun_notifier_block);
3789 pr_err("Can't register netdevice notifier\n");
3796 misc_deregister(&tun_miscdev);
3798 rtnl_link_unregister(&tun_link_ops);
3803 static void tun_cleanup(void)
3805 misc_deregister(&tun_miscdev);
3806 rtnl_link_unregister(&tun_link_ops);
3807 unregister_netdevice_notifier(&tun_notifier_block);
3810 /* Get an underlying socket object from tun file. Returns error unless file is
3811 * attached to a device. The returned object works like a packet socket, it
3812 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
3813 * holding a reference to the file for as long as the socket is in use. */
3814 struct socket *tun_get_socket(struct file *file)
3816 struct tun_file *tfile;
3817 if (file->f_op != &tun_fops)
3818 return ERR_PTR(-EINVAL);
3819 tfile = file->private_data;
3821 return ERR_PTR(-EBADFD);
3822 return &tfile->socket;
3824 EXPORT_SYMBOL_GPL(tun_get_socket);
3826 struct ptr_ring *tun_get_tx_ring(struct file *file)
3828 struct tun_file *tfile;
3830 if (file->f_op != &tun_fops)
3831 return ERR_PTR(-EINVAL);
3832 tfile = file->private_data;
3834 return ERR_PTR(-EBADFD);
3835 return &tfile->tx_ring;
3837 EXPORT_SYMBOL_GPL(tun_get_tx_ring);
3839 module_init(tun_init);
3840 module_exit(tun_cleanup);
3841 MODULE_DESCRIPTION(DRV_DESCRIPTION);
3842 MODULE_AUTHOR(DRV_COPYRIGHT);
3843 MODULE_LICENSE("GPL");
3844 MODULE_ALIAS_MISCDEV(TUN_MINOR);
3845 MODULE_ALIAS("devname:net/tun");