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>
72 #include <linux/uaccess.h>
73 #include <linux/proc_fs.h>
75 static void tun_default_link_ksettings(struct net_device
*dev
,
76 struct ethtool_link_ksettings
*cmd
);
78 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
80 /* TUN device flags */
82 /* IFF_ATTACH_QUEUE is never stored in device flags,
83 * overload it to mean fasync when stored there.
85 #define TUN_FASYNC IFF_ATTACH_QUEUE
86 /* High bits in flags field are unused. */
87 #define TUN_VNET_LE 0x80000000
88 #define TUN_VNET_BE 0x40000000
90 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
91 IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
93 #define GOODCOPY_LEN 128
95 #define FLT_EXACT_COUNT 8
97 unsigned int count
; /* Number of addrs. Zero means disabled */
98 u32 mask
[2]; /* Mask of the hashed addrs */
99 unsigned char addr
[FLT_EXACT_COUNT
][ETH_ALEN
];
102 /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
103 * to max number of VCPUs in guest. */
104 #define MAX_TAP_QUEUES 256
105 #define MAX_TAP_FLOWS 4096
107 #define TUN_FLOW_EXPIRE (3 * HZ)
109 struct tun_pcpu_stats
{
110 u64_stats_t rx_packets
;
111 u64_stats_t rx_bytes
;
112 u64_stats_t tx_packets
;
113 u64_stats_t tx_bytes
;
114 struct u64_stats_sync syncp
;
120 /* A tun_file connects an open character device to a tuntap netdevice. It
121 * also contains all socket related structures (except sock_fprog and tap_filter)
122 * to serve as one transmit queue for tuntap device. The sock_fprog and
123 * tap_filter were kept in tun_struct since they were used for filtering for the
124 * netdevice not for a specific queue (at least I didn't see the requirement for
128 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
129 * other can only be read while rcu_read_lock or rtnl_lock is held.
133 struct socket socket
;
134 struct tun_struct __rcu
*tun
;
135 struct fasync_struct
*fasync
;
136 /* only used for fasnyc */
140 unsigned int ifindex
;
142 struct napi_struct napi
;
144 bool napi_frags_enabled
;
145 struct mutex napi_mutex
; /* Protects access to the above napi */
146 struct list_head next
;
147 struct tun_struct
*detached
;
148 struct ptr_ring tx_ring
;
149 struct xdp_rxq_info xdp_rxq
;
157 struct tun_flow_entry
{
158 struct hlist_node hash_link
;
160 struct tun_struct
*tun
;
165 unsigned long updated ____cacheline_aligned_in_smp
;
168 #define TUN_NUM_FLOW_ENTRIES 1024
169 #define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
173 struct bpf_prog
*prog
;
176 /* Since the socket were moved to tun_file, to preserve the behavior of persist
177 * device, socket filter, sndbuf and vnet header size were restore when the
178 * file were attached to a persist device.
181 struct tun_file __rcu
*tfiles
[MAX_TAP_QUEUES
];
182 unsigned int numqueues
;
187 struct net_device
*dev
;
188 netdev_features_t set_features
;
189 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
195 struct tap_filter txflt
;
196 struct sock_fprog fprog
;
197 /* protected by rtnl lock */
198 bool filter_attached
;
201 struct hlist_head flows
[TUN_NUM_FLOW_ENTRIES
];
202 struct timer_list flow_gc_timer
;
203 unsigned long ageing_time
;
204 unsigned int numdisabled
;
205 struct list_head disabled
;
209 struct tun_pcpu_stats __percpu
*pcpu_stats
;
210 struct bpf_prog __rcu
*xdp_prog
;
211 struct tun_prog __rcu
*steering_prog
;
212 struct tun_prog __rcu
*filter_prog
;
213 struct ethtool_link_ksettings link_ksettings
;
221 bool tun_is_xdp_frame(void *ptr
)
223 return (unsigned long)ptr
& TUN_XDP_FLAG
;
225 EXPORT_SYMBOL(tun_is_xdp_frame
);
227 void *tun_xdp_to_ptr(void *ptr
)
229 return (void *)((unsigned long)ptr
| TUN_XDP_FLAG
);
231 EXPORT_SYMBOL(tun_xdp_to_ptr
);
233 void *tun_ptr_to_xdp(void *ptr
)
235 return (void *)((unsigned long)ptr
& ~TUN_XDP_FLAG
);
237 EXPORT_SYMBOL(tun_ptr_to_xdp
);
239 static int tun_napi_receive(struct napi_struct
*napi
, int budget
)
241 struct tun_file
*tfile
= container_of(napi
, struct tun_file
, napi
);
242 struct sk_buff_head
*queue
= &tfile
->sk
.sk_write_queue
;
243 struct sk_buff_head process_queue
;
247 __skb_queue_head_init(&process_queue
);
249 spin_lock(&queue
->lock
);
250 skb_queue_splice_tail_init(queue
, &process_queue
);
251 spin_unlock(&queue
->lock
);
253 while (received
< budget
&& (skb
= __skb_dequeue(&process_queue
))) {
254 napi_gro_receive(napi
, skb
);
258 if (!skb_queue_empty(&process_queue
)) {
259 spin_lock(&queue
->lock
);
260 skb_queue_splice(&process_queue
, queue
);
261 spin_unlock(&queue
->lock
);
267 static int tun_napi_poll(struct napi_struct
*napi
, int budget
)
269 unsigned int received
;
271 received
= tun_napi_receive(napi
, budget
);
273 if (received
< budget
)
274 napi_complete_done(napi
, received
);
279 static void tun_napi_init(struct tun_struct
*tun
, struct tun_file
*tfile
,
280 bool napi_en
, bool napi_frags
)
282 tfile
->napi_enabled
= napi_en
;
283 tfile
->napi_frags_enabled
= napi_en
&& napi_frags
;
285 netif_tx_napi_add(tun
->dev
, &tfile
->napi
, tun_napi_poll
,
287 napi_enable(&tfile
->napi
);
291 static void tun_napi_disable(struct tun_file
*tfile
)
293 if (tfile
->napi_enabled
)
294 napi_disable(&tfile
->napi
);
297 static void tun_napi_del(struct tun_file
*tfile
)
299 if (tfile
->napi_enabled
)
300 netif_napi_del(&tfile
->napi
);
303 static bool tun_napi_frags_enabled(const struct tun_file
*tfile
)
305 return tfile
->napi_frags_enabled
;
308 #ifdef CONFIG_TUN_VNET_CROSS_LE
309 static inline bool tun_legacy_is_little_endian(struct tun_struct
*tun
)
311 return tun
->flags
& TUN_VNET_BE
? false :
312 virtio_legacy_is_little_endian();
315 static long tun_get_vnet_be(struct tun_struct
*tun
, int __user
*argp
)
317 int be
= !!(tun
->flags
& TUN_VNET_BE
);
319 if (put_user(be
, argp
))
325 static long tun_set_vnet_be(struct tun_struct
*tun
, int __user
*argp
)
329 if (get_user(be
, argp
))
333 tun
->flags
|= TUN_VNET_BE
;
335 tun
->flags
&= ~TUN_VNET_BE
;
340 static inline bool tun_legacy_is_little_endian(struct tun_struct
*tun
)
342 return virtio_legacy_is_little_endian();
345 static long tun_get_vnet_be(struct tun_struct
*tun
, int __user
*argp
)
350 static long tun_set_vnet_be(struct tun_struct
*tun
, int __user
*argp
)
354 #endif /* CONFIG_TUN_VNET_CROSS_LE */
356 static inline bool tun_is_little_endian(struct tun_struct
*tun
)
358 return tun
->flags
& TUN_VNET_LE
||
359 tun_legacy_is_little_endian(tun
);
362 static inline u16
tun16_to_cpu(struct tun_struct
*tun
, __virtio16 val
)
364 return __virtio16_to_cpu(tun_is_little_endian(tun
), val
);
367 static inline __virtio16
cpu_to_tun16(struct tun_struct
*tun
, u16 val
)
369 return __cpu_to_virtio16(tun_is_little_endian(tun
), val
);
372 static inline u32
tun_hashfn(u32 rxhash
)
374 return rxhash
& TUN_MASK_FLOW_ENTRIES
;
377 static struct tun_flow_entry
*tun_flow_find(struct hlist_head
*head
, u32 rxhash
)
379 struct tun_flow_entry
*e
;
381 hlist_for_each_entry_rcu(e
, head
, hash_link
) {
382 if (e
->rxhash
== rxhash
)
388 static struct tun_flow_entry
*tun_flow_create(struct tun_struct
*tun
,
389 struct hlist_head
*head
,
390 u32 rxhash
, u16 queue_index
)
392 struct tun_flow_entry
*e
= kmalloc(sizeof(*e
), GFP_ATOMIC
);
395 netif_info(tun
, tx_queued
, tun
->dev
,
396 "create flow: hash %u index %u\n",
397 rxhash
, queue_index
);
398 e
->updated
= jiffies
;
401 e
->queue_index
= queue_index
;
403 hlist_add_head_rcu(&e
->hash_link
, head
);
409 static void tun_flow_delete(struct tun_struct
*tun
, struct tun_flow_entry
*e
)
411 netif_info(tun
, tx_queued
, tun
->dev
, "delete flow: hash %u index %u\n",
412 e
->rxhash
, e
->queue_index
);
413 hlist_del_rcu(&e
->hash_link
);
418 static void tun_flow_flush(struct tun_struct
*tun
)
422 spin_lock_bh(&tun
->lock
);
423 for (i
= 0; i
< TUN_NUM_FLOW_ENTRIES
; i
++) {
424 struct tun_flow_entry
*e
;
425 struct hlist_node
*n
;
427 hlist_for_each_entry_safe(e
, n
, &tun
->flows
[i
], hash_link
)
428 tun_flow_delete(tun
, e
);
430 spin_unlock_bh(&tun
->lock
);
433 static void tun_flow_delete_by_queue(struct tun_struct
*tun
, u16 queue_index
)
437 spin_lock_bh(&tun
->lock
);
438 for (i
= 0; i
< TUN_NUM_FLOW_ENTRIES
; i
++) {
439 struct tun_flow_entry
*e
;
440 struct hlist_node
*n
;
442 hlist_for_each_entry_safe(e
, n
, &tun
->flows
[i
], hash_link
) {
443 if (e
->queue_index
== queue_index
)
444 tun_flow_delete(tun
, e
);
447 spin_unlock_bh(&tun
->lock
);
450 static void tun_flow_cleanup(struct timer_list
*t
)
452 struct tun_struct
*tun
= from_timer(tun
, t
, flow_gc_timer
);
453 unsigned long delay
= tun
->ageing_time
;
454 unsigned long next_timer
= jiffies
+ delay
;
455 unsigned long count
= 0;
458 spin_lock(&tun
->lock
);
459 for (i
= 0; i
< TUN_NUM_FLOW_ENTRIES
; i
++) {
460 struct tun_flow_entry
*e
;
461 struct hlist_node
*n
;
463 hlist_for_each_entry_safe(e
, n
, &tun
->flows
[i
], hash_link
) {
464 unsigned long this_timer
;
466 this_timer
= e
->updated
+ delay
;
467 if (time_before_eq(this_timer
, jiffies
)) {
468 tun_flow_delete(tun
, e
);
472 if (time_before(this_timer
, next_timer
))
473 next_timer
= this_timer
;
478 mod_timer(&tun
->flow_gc_timer
, round_jiffies_up(next_timer
));
479 spin_unlock(&tun
->lock
);
482 static void tun_flow_update(struct tun_struct
*tun
, u32 rxhash
,
483 struct tun_file
*tfile
)
485 struct hlist_head
*head
;
486 struct tun_flow_entry
*e
;
487 unsigned long delay
= tun
->ageing_time
;
488 u16 queue_index
= tfile
->queue_index
;
490 head
= &tun
->flows
[tun_hashfn(rxhash
)];
494 e
= tun_flow_find(head
, rxhash
);
496 /* TODO: keep queueing to old queue until it's empty? */
497 if (READ_ONCE(e
->queue_index
) != queue_index
)
498 WRITE_ONCE(e
->queue_index
, queue_index
);
499 if (e
->updated
!= jiffies
)
500 e
->updated
= jiffies
;
501 sock_rps_record_flow_hash(e
->rps_rxhash
);
503 spin_lock_bh(&tun
->lock
);
504 if (!tun_flow_find(head
, rxhash
) &&
505 tun
->flow_count
< MAX_TAP_FLOWS
)
506 tun_flow_create(tun
, head
, rxhash
, queue_index
);
508 if (!timer_pending(&tun
->flow_gc_timer
))
509 mod_timer(&tun
->flow_gc_timer
,
510 round_jiffies_up(jiffies
+ delay
));
511 spin_unlock_bh(&tun
->lock
);
517 /* Save the hash received in the stack receive path and update the
518 * flow_hash table accordingly.
520 static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry
*e
, u32 hash
)
522 if (unlikely(e
->rps_rxhash
!= hash
))
523 e
->rps_rxhash
= hash
;
526 /* We try to identify a flow through its rxhash. The reason that
527 * we do not check rxq no. is because some cards(e.g 82599), chooses
528 * the rxq based on the txq where the last packet of the flow comes. As
529 * the userspace application move between processors, we may get a
530 * different rxq no. here.
532 static u16
tun_automq_select_queue(struct tun_struct
*tun
, struct sk_buff
*skb
)
534 struct tun_flow_entry
*e
;
538 numqueues
= READ_ONCE(tun
->numqueues
);
540 txq
= __skb_get_hash_symmetric(skb
);
541 e
= tun_flow_find(&tun
->flows
[tun_hashfn(txq
)], txq
);
543 tun_flow_save_rps_rxhash(e
, txq
);
544 txq
= e
->queue_index
;
546 /* use multiply and shift instead of expensive divide */
547 txq
= ((u64
)txq
* numqueues
) >> 32;
553 static u16
tun_ebpf_select_queue(struct tun_struct
*tun
, struct sk_buff
*skb
)
555 struct tun_prog
*prog
;
559 numqueues
= READ_ONCE(tun
->numqueues
);
563 prog
= rcu_dereference(tun
->steering_prog
);
565 ret
= bpf_prog_run_clear_cb(prog
->prog
, skb
);
567 return ret
% numqueues
;
570 static u16
tun_select_queue(struct net_device
*dev
, struct sk_buff
*skb
,
571 struct net_device
*sb_dev
)
573 struct tun_struct
*tun
= netdev_priv(dev
);
577 if (rcu_dereference(tun
->steering_prog
))
578 ret
= tun_ebpf_select_queue(tun
, skb
);
580 ret
= tun_automq_select_queue(tun
, skb
);
586 static inline bool tun_not_capable(struct tun_struct
*tun
)
588 const struct cred
*cred
= current_cred();
589 struct net
*net
= dev_net(tun
->dev
);
591 return ((uid_valid(tun
->owner
) && !uid_eq(cred
->euid
, tun
->owner
)) ||
592 (gid_valid(tun
->group
) && !in_egroup_p(tun
->group
))) &&
593 !ns_capable(net
->user_ns
, CAP_NET_ADMIN
);
596 static void tun_set_real_num_queues(struct tun_struct
*tun
)
598 netif_set_real_num_tx_queues(tun
->dev
, tun
->numqueues
);
599 netif_set_real_num_rx_queues(tun
->dev
, tun
->numqueues
);
602 static void tun_disable_queue(struct tun_struct
*tun
, struct tun_file
*tfile
)
604 tfile
->detached
= tun
;
605 list_add_tail(&tfile
->next
, &tun
->disabled
);
609 static struct tun_struct
*tun_enable_queue(struct tun_file
*tfile
)
611 struct tun_struct
*tun
= tfile
->detached
;
613 tfile
->detached
= NULL
;
614 list_del_init(&tfile
->next
);
619 void tun_ptr_free(void *ptr
)
623 if (tun_is_xdp_frame(ptr
)) {
624 struct xdp_frame
*xdpf
= tun_ptr_to_xdp(ptr
);
626 xdp_return_frame(xdpf
);
628 __skb_array_destroy_skb(ptr
);
631 EXPORT_SYMBOL_GPL(tun_ptr_free
);
633 static void tun_queue_purge(struct tun_file
*tfile
)
637 while ((ptr
= ptr_ring_consume(&tfile
->tx_ring
)) != NULL
)
640 skb_queue_purge(&tfile
->sk
.sk_write_queue
);
641 skb_queue_purge(&tfile
->sk
.sk_error_queue
);
644 static void __tun_detach(struct tun_file
*tfile
, bool clean
)
646 struct tun_file
*ntfile
;
647 struct tun_struct
*tun
;
649 tun
= rtnl_dereference(tfile
->tun
);
652 tun_napi_disable(tfile
);
656 if (tun
&& !tfile
->detached
) {
657 u16 index
= tfile
->queue_index
;
658 BUG_ON(index
>= tun
->numqueues
);
660 rcu_assign_pointer(tun
->tfiles
[index
],
661 tun
->tfiles
[tun
->numqueues
- 1]);
662 ntfile
= rtnl_dereference(tun
->tfiles
[index
]);
663 ntfile
->queue_index
= index
;
664 rcu_assign_pointer(tun
->tfiles
[tun
->numqueues
- 1],
669 RCU_INIT_POINTER(tfile
->tun
, NULL
);
670 sock_put(&tfile
->sk
);
672 tun_disable_queue(tun
, tfile
);
675 tun_flow_delete_by_queue(tun
, tun
->numqueues
+ 1);
676 /* Drop read queue */
677 tun_queue_purge(tfile
);
678 tun_set_real_num_queues(tun
);
679 } else if (tfile
->detached
&& clean
) {
680 tun
= tun_enable_queue(tfile
);
681 sock_put(&tfile
->sk
);
685 if (tun
&& tun
->numqueues
== 0 && tun
->numdisabled
== 0) {
686 netif_carrier_off(tun
->dev
);
688 if (!(tun
->flags
& IFF_PERSIST
) &&
689 tun
->dev
->reg_state
== NETREG_REGISTERED
)
690 unregister_netdevice(tun
->dev
);
693 xdp_rxq_info_unreg(&tfile
->xdp_rxq
);
694 ptr_ring_cleanup(&tfile
->tx_ring
, tun_ptr_free
);
695 sock_put(&tfile
->sk
);
699 static void tun_detach(struct tun_file
*tfile
, bool clean
)
701 struct tun_struct
*tun
;
702 struct net_device
*dev
;
705 tun
= rtnl_dereference(tfile
->tun
);
706 dev
= tun
? tun
->dev
: NULL
;
707 __tun_detach(tfile
, clean
);
709 netdev_state_change(dev
);
713 static void tun_detach_all(struct net_device
*dev
)
715 struct tun_struct
*tun
= netdev_priv(dev
);
716 struct tun_file
*tfile
, *tmp
;
717 int i
, n
= tun
->numqueues
;
719 for (i
= 0; i
< n
; i
++) {
720 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
722 tun_napi_disable(tfile
);
723 tfile
->socket
.sk
->sk_shutdown
= RCV_SHUTDOWN
;
724 tfile
->socket
.sk
->sk_data_ready(tfile
->socket
.sk
);
725 RCU_INIT_POINTER(tfile
->tun
, NULL
);
728 list_for_each_entry(tfile
, &tun
->disabled
, next
) {
729 tfile
->socket
.sk
->sk_shutdown
= RCV_SHUTDOWN
;
730 tfile
->socket
.sk
->sk_data_ready(tfile
->socket
.sk
);
731 RCU_INIT_POINTER(tfile
->tun
, NULL
);
733 BUG_ON(tun
->numqueues
!= 0);
736 for (i
= 0; i
< n
; i
++) {
737 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
739 /* Drop read queue */
740 tun_queue_purge(tfile
);
741 xdp_rxq_info_unreg(&tfile
->xdp_rxq
);
742 sock_put(&tfile
->sk
);
744 list_for_each_entry_safe(tfile
, tmp
, &tun
->disabled
, next
) {
745 tun_enable_queue(tfile
);
746 tun_queue_purge(tfile
);
747 xdp_rxq_info_unreg(&tfile
->xdp_rxq
);
748 sock_put(&tfile
->sk
);
750 BUG_ON(tun
->numdisabled
!= 0);
752 if (tun
->flags
& IFF_PERSIST
)
753 module_put(THIS_MODULE
);
756 static int tun_attach(struct tun_struct
*tun
, struct file
*file
,
757 bool skip_filter
, bool napi
, bool napi_frags
,
760 struct tun_file
*tfile
= file
->private_data
;
761 struct net_device
*dev
= tun
->dev
;
764 err
= security_tun_dev_attach(tfile
->socket
.sk
, tun
->security
);
769 if (rtnl_dereference(tfile
->tun
) && !tfile
->detached
)
773 if (!(tun
->flags
& IFF_MULTI_QUEUE
) && tun
->numqueues
== 1)
777 if (!tfile
->detached
&&
778 tun
->numqueues
+ tun
->numdisabled
== MAX_TAP_QUEUES
)
783 /* Re-attach the filter to persist device */
784 if (!skip_filter
&& (tun
->filter_attached
== true)) {
785 lock_sock(tfile
->socket
.sk
);
786 err
= sk_attach_filter(&tun
->fprog
, tfile
->socket
.sk
);
787 release_sock(tfile
->socket
.sk
);
792 if (!tfile
->detached
&&
793 ptr_ring_resize(&tfile
->tx_ring
, dev
->tx_queue_len
,
794 GFP_KERNEL
, tun_ptr_free
)) {
799 tfile
->queue_index
= tun
->numqueues
;
800 tfile
->socket
.sk
->sk_shutdown
&= ~RCV_SHUTDOWN
;
802 if (tfile
->detached
) {
803 /* Re-attach detached tfile, updating XDP queue_index */
804 WARN_ON(!xdp_rxq_info_is_reg(&tfile
->xdp_rxq
));
806 if (tfile
->xdp_rxq
.queue_index
!= tfile
->queue_index
)
807 tfile
->xdp_rxq
.queue_index
= tfile
->queue_index
;
809 /* Setup XDP RX-queue info, for new tfile getting attached */
810 err
= xdp_rxq_info_reg(&tfile
->xdp_rxq
,
811 tun
->dev
, tfile
->queue_index
);
814 err
= xdp_rxq_info_reg_mem_model(&tfile
->xdp_rxq
,
815 MEM_TYPE_PAGE_SHARED
, NULL
);
817 xdp_rxq_info_unreg(&tfile
->xdp_rxq
);
823 if (tfile
->detached
) {
824 tun_enable_queue(tfile
);
826 sock_hold(&tfile
->sk
);
827 tun_napi_init(tun
, tfile
, napi
, napi_frags
);
830 if (rtnl_dereference(tun
->xdp_prog
))
831 sock_set_flag(&tfile
->sk
, SOCK_XDP
);
833 /* device is allowed to go away first, so no need to hold extra
837 /* Publish tfile->tun and tun->tfiles only after we've fully
838 * initialized tfile; otherwise we risk using half-initialized
842 rcu_assign_pointer(tfile
->tun
, tun
);
843 rcu_assign_pointer(tun
->tfiles
[tun
->numqueues
], tfile
);
845 tun_set_real_num_queues(tun
);
850 static struct tun_struct
*tun_get(struct tun_file
*tfile
)
852 struct tun_struct
*tun
;
855 tun
= rcu_dereference(tfile
->tun
);
863 static void tun_put(struct tun_struct
*tun
)
869 static void addr_hash_set(u32
*mask
, const u8
*addr
)
871 int n
= ether_crc(ETH_ALEN
, addr
) >> 26;
872 mask
[n
>> 5] |= (1 << (n
& 31));
875 static unsigned int addr_hash_test(const u32
*mask
, const u8
*addr
)
877 int n
= ether_crc(ETH_ALEN
, addr
) >> 26;
878 return mask
[n
>> 5] & (1 << (n
& 31));
881 static int update_filter(struct tap_filter
*filter
, void __user
*arg
)
883 struct { u8 u
[ETH_ALEN
]; } *addr
;
884 struct tun_filter uf
;
885 int err
, alen
, n
, nexact
;
887 if (copy_from_user(&uf
, arg
, sizeof(uf
)))
896 alen
= ETH_ALEN
* uf
.count
;
897 addr
= memdup_user(arg
+ sizeof(uf
), alen
);
899 return PTR_ERR(addr
);
901 /* The filter is updated without holding any locks. Which is
902 * perfectly safe. We disable it first and in the worst
903 * case we'll accept a few undesired packets. */
907 /* Use first set of addresses as an exact filter */
908 for (n
= 0; n
< uf
.count
&& n
< FLT_EXACT_COUNT
; n
++)
909 memcpy(filter
->addr
[n
], addr
[n
].u
, ETH_ALEN
);
913 /* Remaining multicast addresses are hashed,
914 * unicast will leave the filter disabled. */
915 memset(filter
->mask
, 0, sizeof(filter
->mask
));
916 for (; n
< uf
.count
; n
++) {
917 if (!is_multicast_ether_addr(addr
[n
].u
)) {
918 err
= 0; /* no filter */
921 addr_hash_set(filter
->mask
, addr
[n
].u
);
924 /* For ALLMULTI just set the mask to all ones.
925 * This overrides the mask populated above. */
926 if ((uf
.flags
& TUN_FLT_ALLMULTI
))
927 memset(filter
->mask
, ~0, sizeof(filter
->mask
));
929 /* Now enable the filter */
931 filter
->count
= nexact
;
933 /* Return the number of exact filters */
940 /* Returns: 0 - drop, !=0 - accept */
941 static int run_filter(struct tap_filter
*filter
, const struct sk_buff
*skb
)
943 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
945 struct ethhdr
*eh
= (struct ethhdr
*) skb
->data
;
949 for (i
= 0; i
< filter
->count
; i
++)
950 if (ether_addr_equal(eh
->h_dest
, filter
->addr
[i
]))
953 /* Inexact match (multicast only) */
954 if (is_multicast_ether_addr(eh
->h_dest
))
955 return addr_hash_test(filter
->mask
, eh
->h_dest
);
961 * Checks whether the packet is accepted or not.
962 * Returns: 0 - drop, !=0 - accept
964 static int check_filter(struct tap_filter
*filter
, const struct sk_buff
*skb
)
969 return run_filter(filter
, skb
);
972 /* Network device part of the driver */
974 static const struct ethtool_ops tun_ethtool_ops
;
976 /* Net device detach from fd. */
977 static void tun_net_uninit(struct net_device
*dev
)
982 /* Net device open. */
983 static int tun_net_open(struct net_device
*dev
)
985 netif_tx_start_all_queues(dev
);
990 /* Net device close. */
991 static int tun_net_close(struct net_device
*dev
)
993 netif_tx_stop_all_queues(dev
);
997 /* Net device start xmit */
998 static void tun_automq_xmit(struct tun_struct
*tun
, struct sk_buff
*skb
)
1001 if (tun
->numqueues
== 1 && static_branch_unlikely(&rps_needed
)) {
1002 /* Select queue was not called for the skbuff, so we extract the
1003 * RPS hash and save it into the flow_table here.
1005 struct tun_flow_entry
*e
;
1008 rxhash
= __skb_get_hash_symmetric(skb
);
1009 e
= tun_flow_find(&tun
->flows
[tun_hashfn(rxhash
)], rxhash
);
1011 tun_flow_save_rps_rxhash(e
, rxhash
);
1016 static unsigned int run_ebpf_filter(struct tun_struct
*tun
,
1017 struct sk_buff
*skb
,
1020 struct tun_prog
*prog
= rcu_dereference(tun
->filter_prog
);
1023 len
= bpf_prog_run_clear_cb(prog
->prog
, skb
);
1028 /* Net device start xmit */
1029 static netdev_tx_t
tun_net_xmit(struct sk_buff
*skb
, struct net_device
*dev
)
1031 struct tun_struct
*tun
= netdev_priv(dev
);
1032 int txq
= skb
->queue_mapping
;
1033 struct tun_file
*tfile
;
1037 tfile
= rcu_dereference(tun
->tfiles
[txq
]);
1039 /* Drop packet if interface is not attached */
1043 if (!rcu_dereference(tun
->steering_prog
))
1044 tun_automq_xmit(tun
, skb
);
1046 netif_info(tun
, tx_queued
, tun
->dev
, "%s %d\n", __func__
, skb
->len
);
1048 /* Drop if the filter does not like it.
1049 * This is a noop if the filter is disabled.
1050 * Filter can be enabled only for the TAP devices. */
1051 if (!check_filter(&tun
->txflt
, skb
))
1054 if (tfile
->socket
.sk
->sk_filter
&&
1055 sk_filter(tfile
->socket
.sk
, skb
))
1058 len
= run_ebpf_filter(tun
, skb
, len
);
1059 if (len
== 0 || pskb_trim(skb
, len
))
1062 if (unlikely(skb_orphan_frags_rx(skb
, GFP_ATOMIC
)))
1065 skb_tx_timestamp(skb
);
1067 /* Orphan the skb - required as we might hang on to it
1068 * for indefinite time.
1074 if (ptr_ring_produce(&tfile
->tx_ring
, skb
))
1077 /* Notify and wake up reader process */
1078 if (tfile
->flags
& TUN_FASYNC
)
1079 kill_fasync(&tfile
->fasync
, SIGIO
, POLL_IN
);
1080 tfile
->socket
.sk
->sk_data_ready(tfile
->socket
.sk
);
1083 return NETDEV_TX_OK
;
1086 this_cpu_inc(tun
->pcpu_stats
->tx_dropped
);
1090 return NET_XMIT_DROP
;
1093 static void tun_net_mclist(struct net_device
*dev
)
1096 * This callback is supposed to deal with mc filter in
1097 * _rx_ path and has nothing to do with the _tx_ path.
1098 * In rx path we always accept everything userspace gives us.
1102 static netdev_features_t
tun_net_fix_features(struct net_device
*dev
,
1103 netdev_features_t features
)
1105 struct tun_struct
*tun
= netdev_priv(dev
);
1107 return (features
& tun
->set_features
) | (features
& ~TUN_USER_FEATURES
);
1110 static void tun_set_headroom(struct net_device
*dev
, int new_hr
)
1112 struct tun_struct
*tun
= netdev_priv(dev
);
1114 if (new_hr
< NET_SKB_PAD
)
1115 new_hr
= NET_SKB_PAD
;
1117 tun
->align
= new_hr
;
1121 tun_net_get_stats64(struct net_device
*dev
, struct rtnl_link_stats64
*stats
)
1123 u32 rx_dropped
= 0, tx_dropped
= 0, rx_frame_errors
= 0;
1124 struct tun_struct
*tun
= netdev_priv(dev
);
1125 struct tun_pcpu_stats
*p
;
1128 for_each_possible_cpu(i
) {
1129 u64 rxpackets
, rxbytes
, txpackets
, txbytes
;
1132 p
= per_cpu_ptr(tun
->pcpu_stats
, i
);
1134 start
= u64_stats_fetch_begin(&p
->syncp
);
1135 rxpackets
= u64_stats_read(&p
->rx_packets
);
1136 rxbytes
= u64_stats_read(&p
->rx_bytes
);
1137 txpackets
= u64_stats_read(&p
->tx_packets
);
1138 txbytes
= u64_stats_read(&p
->tx_bytes
);
1139 } while (u64_stats_fetch_retry(&p
->syncp
, start
));
1141 stats
->rx_packets
+= rxpackets
;
1142 stats
->rx_bytes
+= rxbytes
;
1143 stats
->tx_packets
+= txpackets
;
1144 stats
->tx_bytes
+= txbytes
;
1147 rx_dropped
+= p
->rx_dropped
;
1148 rx_frame_errors
+= p
->rx_frame_errors
;
1149 tx_dropped
+= p
->tx_dropped
;
1151 stats
->rx_dropped
= rx_dropped
;
1152 stats
->rx_frame_errors
= rx_frame_errors
;
1153 stats
->tx_dropped
= tx_dropped
;
1156 static int tun_xdp_set(struct net_device
*dev
, struct bpf_prog
*prog
,
1157 struct netlink_ext_ack
*extack
)
1159 struct tun_struct
*tun
= netdev_priv(dev
);
1160 struct tun_file
*tfile
;
1161 struct bpf_prog
*old_prog
;
1164 old_prog
= rtnl_dereference(tun
->xdp_prog
);
1165 rcu_assign_pointer(tun
->xdp_prog
, prog
);
1167 bpf_prog_put(old_prog
);
1169 for (i
= 0; i
< tun
->numqueues
; i
++) {
1170 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
1172 sock_set_flag(&tfile
->sk
, SOCK_XDP
);
1174 sock_reset_flag(&tfile
->sk
, SOCK_XDP
);
1176 list_for_each_entry(tfile
, &tun
->disabled
, next
) {
1178 sock_set_flag(&tfile
->sk
, SOCK_XDP
);
1180 sock_reset_flag(&tfile
->sk
, SOCK_XDP
);
1186 static u32
tun_xdp_query(struct net_device
*dev
)
1188 struct tun_struct
*tun
= netdev_priv(dev
);
1189 const struct bpf_prog
*xdp_prog
;
1191 xdp_prog
= rtnl_dereference(tun
->xdp_prog
);
1193 return xdp_prog
->aux
->id
;
1198 static int tun_xdp(struct net_device
*dev
, struct netdev_bpf
*xdp
)
1200 switch (xdp
->command
) {
1201 case XDP_SETUP_PROG
:
1202 return tun_xdp_set(dev
, xdp
->prog
, xdp
->extack
);
1203 case XDP_QUERY_PROG
:
1204 xdp
->prog_id
= tun_xdp_query(dev
);
1211 static int tun_net_change_carrier(struct net_device
*dev
, bool new_carrier
)
1214 struct tun_struct
*tun
= netdev_priv(dev
);
1216 if (!tun
->numqueues
)
1219 netif_carrier_on(dev
);
1221 netif_carrier_off(dev
);
1226 static const struct net_device_ops tun_netdev_ops
= {
1227 .ndo_uninit
= tun_net_uninit
,
1228 .ndo_open
= tun_net_open
,
1229 .ndo_stop
= tun_net_close
,
1230 .ndo_start_xmit
= tun_net_xmit
,
1231 .ndo_fix_features
= tun_net_fix_features
,
1232 .ndo_select_queue
= tun_select_queue
,
1233 .ndo_set_rx_headroom
= tun_set_headroom
,
1234 .ndo_get_stats64
= tun_net_get_stats64
,
1235 .ndo_change_carrier
= tun_net_change_carrier
,
1238 static void __tun_xdp_flush_tfile(struct tun_file
*tfile
)
1240 /* Notify and wake up reader process */
1241 if (tfile
->flags
& TUN_FASYNC
)
1242 kill_fasync(&tfile
->fasync
, SIGIO
, POLL_IN
);
1243 tfile
->socket
.sk
->sk_data_ready(tfile
->socket
.sk
);
1246 static int tun_xdp_xmit(struct net_device
*dev
, int n
,
1247 struct xdp_frame
**frames
, u32 flags
)
1249 struct tun_struct
*tun
= netdev_priv(dev
);
1250 struct tun_file
*tfile
;
1256 if (unlikely(flags
& ~XDP_XMIT_FLAGS_MASK
))
1262 numqueues
= READ_ONCE(tun
->numqueues
);
1265 return -ENXIO
; /* Caller will free/return all frames */
1268 tfile
= rcu_dereference(tun
->tfiles
[smp_processor_id() %
1270 if (unlikely(!tfile
))
1273 spin_lock(&tfile
->tx_ring
.producer_lock
);
1274 for (i
= 0; i
< n
; i
++) {
1275 struct xdp_frame
*xdp
= frames
[i
];
1276 /* Encode the XDP flag into lowest bit for consumer to differ
1277 * XDP buffer from sk_buff.
1279 void *frame
= tun_xdp_to_ptr(xdp
);
1281 if (__ptr_ring_produce(&tfile
->tx_ring
, frame
)) {
1282 this_cpu_inc(tun
->pcpu_stats
->tx_dropped
);
1283 xdp_return_frame_rx_napi(xdp
);
1287 spin_unlock(&tfile
->tx_ring
.producer_lock
);
1289 if (flags
& XDP_XMIT_FLUSH
)
1290 __tun_xdp_flush_tfile(tfile
);
1296 static int tun_xdp_tx(struct net_device
*dev
, struct xdp_buff
*xdp
)
1298 struct xdp_frame
*frame
= convert_to_xdp_frame(xdp
);
1300 if (unlikely(!frame
))
1303 return tun_xdp_xmit(dev
, 1, &frame
, XDP_XMIT_FLUSH
);
1306 static const struct net_device_ops tap_netdev_ops
= {
1307 .ndo_uninit
= tun_net_uninit
,
1308 .ndo_open
= tun_net_open
,
1309 .ndo_stop
= tun_net_close
,
1310 .ndo_start_xmit
= tun_net_xmit
,
1311 .ndo_fix_features
= tun_net_fix_features
,
1312 .ndo_set_rx_mode
= tun_net_mclist
,
1313 .ndo_set_mac_address
= eth_mac_addr
,
1314 .ndo_validate_addr
= eth_validate_addr
,
1315 .ndo_select_queue
= tun_select_queue
,
1316 .ndo_features_check
= passthru_features_check
,
1317 .ndo_set_rx_headroom
= tun_set_headroom
,
1318 .ndo_get_stats64
= tun_net_get_stats64
,
1320 .ndo_xdp_xmit
= tun_xdp_xmit
,
1321 .ndo_change_carrier
= tun_net_change_carrier
,
1324 static void tun_flow_init(struct tun_struct
*tun
)
1328 for (i
= 0; i
< TUN_NUM_FLOW_ENTRIES
; i
++)
1329 INIT_HLIST_HEAD(&tun
->flows
[i
]);
1331 tun
->ageing_time
= TUN_FLOW_EXPIRE
;
1332 timer_setup(&tun
->flow_gc_timer
, tun_flow_cleanup
, 0);
1333 mod_timer(&tun
->flow_gc_timer
,
1334 round_jiffies_up(jiffies
+ tun
->ageing_time
));
1337 static void tun_flow_uninit(struct tun_struct
*tun
)
1339 del_timer_sync(&tun
->flow_gc_timer
);
1340 tun_flow_flush(tun
);
1344 #define MAX_MTU 65535
1346 /* Initialize net device. */
1347 static void tun_net_init(struct net_device
*dev
)
1349 struct tun_struct
*tun
= netdev_priv(dev
);
1351 switch (tun
->flags
& TUN_TYPE_MASK
) {
1353 dev
->netdev_ops
= &tun_netdev_ops
;
1355 /* Point-to-Point TUN Device */
1356 dev
->hard_header_len
= 0;
1360 /* Zero header length */
1361 dev
->type
= ARPHRD_NONE
;
1362 dev
->flags
= IFF_POINTOPOINT
| IFF_NOARP
| IFF_MULTICAST
;
1366 dev
->netdev_ops
= &tap_netdev_ops
;
1367 /* Ethernet TAP Device */
1369 dev
->priv_flags
&= ~IFF_TX_SKB_SHARING
;
1370 dev
->priv_flags
|= IFF_LIVE_ADDR_CHANGE
;
1372 eth_hw_addr_random(dev
);
1377 dev
->min_mtu
= MIN_MTU
;
1378 dev
->max_mtu
= MAX_MTU
- dev
->hard_header_len
;
1381 static bool tun_sock_writeable(struct tun_struct
*tun
, struct tun_file
*tfile
)
1383 struct sock
*sk
= tfile
->socket
.sk
;
1385 return (tun
->dev
->flags
& IFF_UP
) && sock_writeable(sk
);
1388 /* Character device part */
1391 static __poll_t
tun_chr_poll(struct file
*file
, poll_table
*wait
)
1393 struct tun_file
*tfile
= file
->private_data
;
1394 struct tun_struct
*tun
= tun_get(tfile
);
1401 sk
= tfile
->socket
.sk
;
1403 poll_wait(file
, sk_sleep(sk
), wait
);
1405 if (!ptr_ring_empty(&tfile
->tx_ring
))
1406 mask
|= EPOLLIN
| EPOLLRDNORM
;
1408 /* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
1409 * guarantee EPOLLOUT to be raised by either here or
1410 * tun_sock_write_space(). Then process could get notification
1411 * after it writes to a down device and meets -EIO.
1413 if (tun_sock_writeable(tun
, tfile
) ||
1414 (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE
, &sk
->sk_socket
->flags
) &&
1415 tun_sock_writeable(tun
, tfile
)))
1416 mask
|= EPOLLOUT
| EPOLLWRNORM
;
1418 if (tun
->dev
->reg_state
!= NETREG_REGISTERED
)
1425 static struct sk_buff
*tun_napi_alloc_frags(struct tun_file
*tfile
,
1427 const struct iov_iter
*it
)
1429 struct sk_buff
*skb
;
1434 if (it
->nr_segs
> MAX_SKB_FRAGS
+ 1)
1435 return ERR_PTR(-ENOMEM
);
1438 skb
= napi_get_frags(&tfile
->napi
);
1441 return ERR_PTR(-ENOMEM
);
1443 linear
= iov_iter_single_seg_count(it
);
1444 err
= __skb_grow(skb
, linear
);
1449 skb
->data_len
= len
- linear
;
1450 skb
->truesize
+= skb
->data_len
;
1452 for (i
= 1; i
< it
->nr_segs
; i
++) {
1453 size_t fragsz
= it
->iov
[i
].iov_len
;
1457 if (fragsz
== 0 || fragsz
> PAGE_SIZE
) {
1461 frag
= netdev_alloc_frag(fragsz
);
1466 page
= virt_to_head_page(frag
);
1467 skb_fill_page_desc(skb
, i
- 1, page
,
1468 frag
- page_address(page
), fragsz
);
1473 /* frees skb and all frags allocated with napi_alloc_frag() */
1474 napi_free_frags(&tfile
->napi
);
1475 return ERR_PTR(err
);
1478 /* prepad is the amount to reserve at front. len is length after that.
1479 * linear is a hint as to how much to copy (usually headers). */
1480 static struct sk_buff
*tun_alloc_skb(struct tun_file
*tfile
,
1481 size_t prepad
, size_t len
,
1482 size_t linear
, int noblock
)
1484 struct sock
*sk
= tfile
->socket
.sk
;
1485 struct sk_buff
*skb
;
1488 /* Under a page? Don't bother with paged skb. */
1489 if (prepad
+ len
< PAGE_SIZE
|| !linear
)
1492 skb
= sock_alloc_send_pskb(sk
, prepad
+ linear
, len
- linear
, noblock
,
1495 return ERR_PTR(err
);
1497 skb_reserve(skb
, prepad
);
1498 skb_put(skb
, linear
);
1499 skb
->data_len
= len
- linear
;
1500 skb
->len
+= len
- linear
;
1505 static void tun_rx_batched(struct tun_struct
*tun
, struct tun_file
*tfile
,
1506 struct sk_buff
*skb
, int more
)
1508 struct sk_buff_head
*queue
= &tfile
->sk
.sk_write_queue
;
1509 struct sk_buff_head process_queue
;
1510 u32 rx_batched
= tun
->rx_batched
;
1513 if (!rx_batched
|| (!more
&& skb_queue_empty(queue
))) {
1515 skb_record_rx_queue(skb
, tfile
->queue_index
);
1516 netif_receive_skb(skb
);
1521 spin_lock(&queue
->lock
);
1522 if (!more
|| skb_queue_len(queue
) == rx_batched
) {
1523 __skb_queue_head_init(&process_queue
);
1524 skb_queue_splice_tail_init(queue
, &process_queue
);
1527 __skb_queue_tail(queue
, skb
);
1529 spin_unlock(&queue
->lock
);
1532 struct sk_buff
*nskb
;
1535 while ((nskb
= __skb_dequeue(&process_queue
))) {
1536 skb_record_rx_queue(nskb
, tfile
->queue_index
);
1537 netif_receive_skb(nskb
);
1539 skb_record_rx_queue(skb
, tfile
->queue_index
);
1540 netif_receive_skb(skb
);
1545 static bool tun_can_build_skb(struct tun_struct
*tun
, struct tun_file
*tfile
,
1546 int len
, int noblock
, bool zerocopy
)
1548 if ((tun
->flags
& TUN_TYPE_MASK
) != IFF_TAP
)
1551 if (tfile
->socket
.sk
->sk_sndbuf
!= INT_MAX
)
1560 if (SKB_DATA_ALIGN(len
+ TUN_RX_PAD
) +
1561 SKB_DATA_ALIGN(sizeof(struct skb_shared_info
)) > PAGE_SIZE
)
1567 static struct sk_buff
*__tun_build_skb(struct tun_file
*tfile
,
1568 struct page_frag
*alloc_frag
, char *buf
,
1569 int buflen
, int len
, int pad
)
1571 struct sk_buff
*skb
= build_skb(buf
, buflen
);
1574 return ERR_PTR(-ENOMEM
);
1576 skb_reserve(skb
, pad
);
1578 skb_set_owner_w(skb
, tfile
->socket
.sk
);
1580 get_page(alloc_frag
->page
);
1581 alloc_frag
->offset
+= buflen
;
1586 static int tun_xdp_act(struct tun_struct
*tun
, struct bpf_prog
*xdp_prog
,
1587 struct xdp_buff
*xdp
, u32 act
)
1593 err
= xdp_do_redirect(tun
->dev
, xdp
, xdp_prog
);
1598 err
= tun_xdp_tx(tun
->dev
, xdp
);
1605 bpf_warn_invalid_xdp_action(act
);
1608 trace_xdp_exception(tun
->dev
, xdp_prog
, act
);
1611 this_cpu_inc(tun
->pcpu_stats
->rx_dropped
);
1618 static struct sk_buff
*tun_build_skb(struct tun_struct
*tun
,
1619 struct tun_file
*tfile
,
1620 struct iov_iter
*from
,
1621 struct virtio_net_hdr
*hdr
,
1622 int len
, int *skb_xdp
)
1624 struct page_frag
*alloc_frag
= ¤t
->task_frag
;
1625 struct bpf_prog
*xdp_prog
;
1626 int buflen
= SKB_DATA_ALIGN(sizeof(struct skb_shared_info
));
1629 int pad
= TUN_RX_PAD
;
1633 xdp_prog
= rcu_dereference(tun
->xdp_prog
);
1635 pad
+= XDP_PACKET_HEADROOM
;
1636 buflen
+= SKB_DATA_ALIGN(len
+ pad
);
1639 alloc_frag
->offset
= ALIGN((u64
)alloc_frag
->offset
, SMP_CACHE_BYTES
);
1640 if (unlikely(!skb_page_frag_refill(buflen
, alloc_frag
, GFP_KERNEL
)))
1641 return ERR_PTR(-ENOMEM
);
1643 buf
= (char *)page_address(alloc_frag
->page
) + alloc_frag
->offset
;
1644 copied
= copy_page_from_iter(alloc_frag
->page
,
1645 alloc_frag
->offset
+ pad
,
1648 return ERR_PTR(-EFAULT
);
1650 /* There's a small window that XDP may be set after the check
1651 * of xdp_prog above, this should be rare and for simplicity
1652 * we do XDP on skb in case the headroom is not enough.
1654 if (hdr
->gso_type
|| !xdp_prog
) {
1656 return __tun_build_skb(tfile
, alloc_frag
, buf
, buflen
, len
,
1664 xdp_prog
= rcu_dereference(tun
->xdp_prog
);
1666 struct xdp_buff xdp
;
1669 xdp
.data_hard_start
= buf
;
1670 xdp
.data
= buf
+ pad
;
1671 xdp_set_data_meta_invalid(&xdp
);
1672 xdp
.data_end
= xdp
.data
+ len
;
1673 xdp
.rxq
= &tfile
->xdp_rxq
;
1675 act
= bpf_prog_run_xdp(xdp_prog
, &xdp
);
1676 if (act
== XDP_REDIRECT
|| act
== XDP_TX
) {
1677 get_page(alloc_frag
->page
);
1678 alloc_frag
->offset
+= buflen
;
1680 err
= tun_xdp_act(tun
, xdp_prog
, &xdp
, act
);
1683 if (err
== XDP_REDIRECT
)
1685 if (err
!= XDP_PASS
)
1688 pad
= xdp
.data
- xdp
.data_hard_start
;
1689 len
= xdp
.data_end
- xdp
.data
;
1694 return __tun_build_skb(tfile
, alloc_frag
, buf
, buflen
, len
, pad
);
1697 put_page(alloc_frag
->page
);
1704 /* Get packet from user space buffer */
1705 static ssize_t
tun_get_user(struct tun_struct
*tun
, struct tun_file
*tfile
,
1706 void *msg_control
, struct iov_iter
*from
,
1707 int noblock
, bool more
)
1709 struct tun_pi pi
= { 0, cpu_to_be16(ETH_P_IP
) };
1710 struct sk_buff
*skb
;
1711 size_t total_len
= iov_iter_count(from
);
1712 size_t len
= total_len
, align
= tun
->align
, linear
;
1713 struct virtio_net_hdr gso
= { 0 };
1714 struct tun_pcpu_stats
*stats
;
1717 bool zerocopy
= false;
1721 bool frags
= tun_napi_frags_enabled(tfile
);
1723 if (!(tun
->flags
& IFF_NO_PI
)) {
1724 if (len
< sizeof(pi
))
1728 if (!copy_from_iter_full(&pi
, sizeof(pi
), from
))
1732 if (tun
->flags
& IFF_VNET_HDR
) {
1733 int vnet_hdr_sz
= READ_ONCE(tun
->vnet_hdr_sz
);
1735 if (len
< vnet_hdr_sz
)
1739 if (!copy_from_iter_full(&gso
, sizeof(gso
), from
))
1742 if ((gso
.flags
& VIRTIO_NET_HDR_F_NEEDS_CSUM
) &&
1743 tun16_to_cpu(tun
, gso
.csum_start
) + tun16_to_cpu(tun
, gso
.csum_offset
) + 2 > tun16_to_cpu(tun
, gso
.hdr_len
))
1744 gso
.hdr_len
= cpu_to_tun16(tun
, tun16_to_cpu(tun
, gso
.csum_start
) + tun16_to_cpu(tun
, gso
.csum_offset
) + 2);
1746 if (tun16_to_cpu(tun
, gso
.hdr_len
) > len
)
1748 iov_iter_advance(from
, vnet_hdr_sz
- sizeof(gso
));
1751 if ((tun
->flags
& TUN_TYPE_MASK
) == IFF_TAP
) {
1752 align
+= NET_IP_ALIGN
;
1753 if (unlikely(len
< ETH_HLEN
||
1754 (gso
.hdr_len
&& tun16_to_cpu(tun
, gso
.hdr_len
) < ETH_HLEN
)))
1758 good_linear
= SKB_MAX_HEAD(align
);
1761 struct iov_iter i
= *from
;
1763 /* There are 256 bytes to be copied in skb, so there is
1764 * enough room for skb expand head in case it is used.
1765 * The rest of the buffer is mapped from userspace.
1767 copylen
= gso
.hdr_len
? tun16_to_cpu(tun
, gso
.hdr_len
) : GOODCOPY_LEN
;
1768 if (copylen
> good_linear
)
1769 copylen
= good_linear
;
1771 iov_iter_advance(&i
, copylen
);
1772 if (iov_iter_npages(&i
, INT_MAX
) <= MAX_SKB_FRAGS
)
1776 if (!frags
&& tun_can_build_skb(tun
, tfile
, len
, noblock
, zerocopy
)) {
1777 /* For the packet that is not easy to be processed
1778 * (e.g gso or jumbo packet), we will do it at after
1779 * skb was created with generic XDP routine.
1781 skb
= tun_build_skb(tun
, tfile
, from
, &gso
, len
, &skb_xdp
);
1783 this_cpu_inc(tun
->pcpu_stats
->rx_dropped
);
1784 return PTR_ERR(skb
);
1791 if (tun16_to_cpu(tun
, gso
.hdr_len
) > good_linear
)
1792 linear
= good_linear
;
1794 linear
= tun16_to_cpu(tun
, gso
.hdr_len
);
1798 mutex_lock(&tfile
->napi_mutex
);
1799 skb
= tun_napi_alloc_frags(tfile
, copylen
, from
);
1800 /* tun_napi_alloc_frags() enforces a layout for the skb.
1801 * If zerocopy is enabled, then this layout will be
1802 * overwritten by zerocopy_sg_from_iter().
1806 skb
= tun_alloc_skb(tfile
, align
, copylen
, linear
,
1811 if (PTR_ERR(skb
) != -EAGAIN
)
1812 this_cpu_inc(tun
->pcpu_stats
->rx_dropped
);
1814 mutex_unlock(&tfile
->napi_mutex
);
1815 return PTR_ERR(skb
);
1819 err
= zerocopy_sg_from_iter(skb
, from
);
1821 err
= skb_copy_datagram_from_iter(skb
, 0, from
, len
);
1826 this_cpu_inc(tun
->pcpu_stats
->rx_dropped
);
1829 tfile
->napi
.skb
= NULL
;
1830 mutex_unlock(&tfile
->napi_mutex
);
1837 if (virtio_net_hdr_to_skb(skb
, &gso
, tun_is_little_endian(tun
))) {
1838 this_cpu_inc(tun
->pcpu_stats
->rx_frame_errors
);
1841 tfile
->napi
.skb
= NULL
;
1842 mutex_unlock(&tfile
->napi_mutex
);
1848 switch (tun
->flags
& TUN_TYPE_MASK
) {
1850 if (tun
->flags
& IFF_NO_PI
) {
1851 u8 ip_version
= skb
->len
? (skb
->data
[0] >> 4) : 0;
1853 switch (ip_version
) {
1855 pi
.proto
= htons(ETH_P_IP
);
1858 pi
.proto
= htons(ETH_P_IPV6
);
1861 this_cpu_inc(tun
->pcpu_stats
->rx_dropped
);
1867 skb_reset_mac_header(skb
);
1868 skb
->protocol
= pi
.proto
;
1869 skb
->dev
= tun
->dev
;
1873 skb
->protocol
= eth_type_trans(skb
, tun
->dev
);
1877 /* copy skb_ubuf_info for callback when skb has no error */
1879 skb_shinfo(skb
)->destructor_arg
= msg_control
;
1880 skb_shinfo(skb
)->tx_flags
|= SKBTX_DEV_ZEROCOPY
;
1881 skb_shinfo(skb
)->tx_flags
|= SKBTX_SHARED_FRAG
;
1882 } else if (msg_control
) {
1883 struct ubuf_info
*uarg
= msg_control
;
1884 uarg
->callback(uarg
, false);
1887 skb_reset_network_header(skb
);
1888 skb_probe_transport_header(skb
);
1891 struct bpf_prog
*xdp_prog
;
1896 xdp_prog
= rcu_dereference(tun
->xdp_prog
);
1898 ret
= do_xdp_generic(xdp_prog
, skb
);
1899 if (ret
!= XDP_PASS
) {
1903 tfile
->napi
.skb
= NULL
;
1904 mutex_unlock(&tfile
->napi_mutex
);
1913 /* Compute the costly rx hash only if needed for flow updates.
1914 * We may get a very small possibility of OOO during switching, not
1915 * worth to optimize.
1917 if (!rcu_access_pointer(tun
->steering_prog
) && tun
->numqueues
> 1 &&
1919 rxhash
= __skb_get_hash_symmetric(skb
);
1922 if (unlikely(!(tun
->dev
->flags
& IFF_UP
))) {
1929 /* Exercise flow dissector code path. */
1930 u32 headlen
= eth_get_headlen(tun
->dev
, skb
->data
,
1933 if (unlikely(headlen
> skb_headlen(skb
))) {
1934 this_cpu_inc(tun
->pcpu_stats
->rx_dropped
);
1935 napi_free_frags(&tfile
->napi
);
1937 mutex_unlock(&tfile
->napi_mutex
);
1943 napi_gro_frags(&tfile
->napi
);
1945 mutex_unlock(&tfile
->napi_mutex
);
1946 } else if (tfile
->napi_enabled
) {
1947 struct sk_buff_head
*queue
= &tfile
->sk
.sk_write_queue
;
1950 spin_lock_bh(&queue
->lock
);
1951 __skb_queue_tail(queue
, skb
);
1952 queue_len
= skb_queue_len(queue
);
1953 spin_unlock(&queue
->lock
);
1955 if (!more
|| queue_len
> NAPI_POLL_WEIGHT
)
1956 napi_schedule(&tfile
->napi
);
1959 } else if (!IS_ENABLED(CONFIG_4KSTACKS
)) {
1960 tun_rx_batched(tun
, tfile
, skb
, more
);
1966 stats
= get_cpu_ptr(tun
->pcpu_stats
);
1967 u64_stats_update_begin(&stats
->syncp
);
1968 u64_stats_inc(&stats
->rx_packets
);
1969 u64_stats_add(&stats
->rx_bytes
, len
);
1970 u64_stats_update_end(&stats
->syncp
);
1974 tun_flow_update(tun
, rxhash
, tfile
);
1979 static ssize_t
tun_chr_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
1981 struct file
*file
= iocb
->ki_filp
;
1982 struct tun_file
*tfile
= file
->private_data
;
1983 struct tun_struct
*tun
= tun_get(tfile
);
1989 result
= tun_get_user(tun
, tfile
, NULL
, from
,
1990 file
->f_flags
& O_NONBLOCK
, false);
1996 static ssize_t
tun_put_user_xdp(struct tun_struct
*tun
,
1997 struct tun_file
*tfile
,
1998 struct xdp_frame
*xdp_frame
,
1999 struct iov_iter
*iter
)
2001 int vnet_hdr_sz
= 0;
2002 size_t size
= xdp_frame
->len
;
2003 struct tun_pcpu_stats
*stats
;
2006 if (tun
->flags
& IFF_VNET_HDR
) {
2007 struct virtio_net_hdr gso
= { 0 };
2009 vnet_hdr_sz
= READ_ONCE(tun
->vnet_hdr_sz
);
2010 if (unlikely(iov_iter_count(iter
) < vnet_hdr_sz
))
2012 if (unlikely(copy_to_iter(&gso
, sizeof(gso
), iter
) !=
2015 iov_iter_advance(iter
, vnet_hdr_sz
- sizeof(gso
));
2018 ret
= copy_to_iter(xdp_frame
->data
, size
, iter
) + vnet_hdr_sz
;
2020 stats
= get_cpu_ptr(tun
->pcpu_stats
);
2021 u64_stats_update_begin(&stats
->syncp
);
2022 u64_stats_inc(&stats
->tx_packets
);
2023 u64_stats_add(&stats
->tx_bytes
, ret
);
2024 u64_stats_update_end(&stats
->syncp
);
2025 put_cpu_ptr(tun
->pcpu_stats
);
2030 /* Put packet to the user space buffer */
2031 static ssize_t
tun_put_user(struct tun_struct
*tun
,
2032 struct tun_file
*tfile
,
2033 struct sk_buff
*skb
,
2034 struct iov_iter
*iter
)
2036 struct tun_pi pi
= { 0, skb
->protocol
};
2037 struct tun_pcpu_stats
*stats
;
2039 int vlan_offset
= 0;
2041 int vnet_hdr_sz
= 0;
2043 if (skb_vlan_tag_present(skb
))
2044 vlan_hlen
= VLAN_HLEN
;
2046 if (tun
->flags
& IFF_VNET_HDR
)
2047 vnet_hdr_sz
= READ_ONCE(tun
->vnet_hdr_sz
);
2049 total
= skb
->len
+ vlan_hlen
+ vnet_hdr_sz
;
2051 if (!(tun
->flags
& IFF_NO_PI
)) {
2052 if (iov_iter_count(iter
) < sizeof(pi
))
2055 total
+= sizeof(pi
);
2056 if (iov_iter_count(iter
) < total
) {
2057 /* Packet will be striped */
2058 pi
.flags
|= TUN_PKT_STRIP
;
2061 if (copy_to_iter(&pi
, sizeof(pi
), iter
) != sizeof(pi
))
2066 struct virtio_net_hdr gso
;
2068 if (iov_iter_count(iter
) < vnet_hdr_sz
)
2071 if (virtio_net_hdr_from_skb(skb
, &gso
,
2072 tun_is_little_endian(tun
), true,
2074 struct skb_shared_info
*sinfo
= skb_shinfo(skb
);
2075 pr_err("unexpected GSO type: "
2076 "0x%x, gso_size %d, hdr_len %d\n",
2077 sinfo
->gso_type
, tun16_to_cpu(tun
, gso
.gso_size
),
2078 tun16_to_cpu(tun
, gso
.hdr_len
));
2079 print_hex_dump(KERN_ERR
, "tun: ",
2082 min((int)tun16_to_cpu(tun
, gso
.hdr_len
), 64), true);
2087 if (copy_to_iter(&gso
, sizeof(gso
), iter
) != sizeof(gso
))
2090 iov_iter_advance(iter
, vnet_hdr_sz
- sizeof(gso
));
2097 veth
.h_vlan_proto
= skb
->vlan_proto
;
2098 veth
.h_vlan_TCI
= htons(skb_vlan_tag_get(skb
));
2100 vlan_offset
= offsetof(struct vlan_ethhdr
, h_vlan_proto
);
2102 ret
= skb_copy_datagram_iter(skb
, 0, iter
, vlan_offset
);
2103 if (ret
|| !iov_iter_count(iter
))
2106 ret
= copy_to_iter(&veth
, sizeof(veth
), iter
);
2107 if (ret
!= sizeof(veth
) || !iov_iter_count(iter
))
2111 skb_copy_datagram_iter(skb
, vlan_offset
, iter
, skb
->len
- vlan_offset
);
2114 /* caller is in process context, */
2115 stats
= get_cpu_ptr(tun
->pcpu_stats
);
2116 u64_stats_update_begin(&stats
->syncp
);
2117 u64_stats_inc(&stats
->tx_packets
);
2118 u64_stats_add(&stats
->tx_bytes
, skb
->len
+ vlan_hlen
);
2119 u64_stats_update_end(&stats
->syncp
);
2120 put_cpu_ptr(tun
->pcpu_stats
);
2125 static void *tun_ring_recv(struct tun_file
*tfile
, int noblock
, int *err
)
2127 DECLARE_WAITQUEUE(wait
, current
);
2131 ptr
= ptr_ring_consume(&tfile
->tx_ring
);
2139 add_wait_queue(&tfile
->socket
.wq
.wait
, &wait
);
2142 set_current_state(TASK_INTERRUPTIBLE
);
2143 ptr
= ptr_ring_consume(&tfile
->tx_ring
);
2146 if (signal_pending(current
)) {
2147 error
= -ERESTARTSYS
;
2150 if (tfile
->socket
.sk
->sk_shutdown
& RCV_SHUTDOWN
) {
2158 __set_current_state(TASK_RUNNING
);
2159 remove_wait_queue(&tfile
->socket
.wq
.wait
, &wait
);
2166 static ssize_t
tun_do_read(struct tun_struct
*tun
, struct tun_file
*tfile
,
2167 struct iov_iter
*to
,
2168 int noblock
, void *ptr
)
2173 if (!iov_iter_count(to
)) {
2179 /* Read frames from ring */
2180 ptr
= tun_ring_recv(tfile
, noblock
, &err
);
2185 if (tun_is_xdp_frame(ptr
)) {
2186 struct xdp_frame
*xdpf
= tun_ptr_to_xdp(ptr
);
2188 ret
= tun_put_user_xdp(tun
, tfile
, xdpf
, to
);
2189 xdp_return_frame(xdpf
);
2191 struct sk_buff
*skb
= ptr
;
2193 ret
= tun_put_user(tun
, tfile
, skb
, to
);
2194 if (unlikely(ret
< 0))
2203 static ssize_t
tun_chr_read_iter(struct kiocb
*iocb
, struct iov_iter
*to
)
2205 struct file
*file
= iocb
->ki_filp
;
2206 struct tun_file
*tfile
= file
->private_data
;
2207 struct tun_struct
*tun
= tun_get(tfile
);
2208 ssize_t len
= iov_iter_count(to
), ret
;
2212 ret
= tun_do_read(tun
, tfile
, to
, file
->f_flags
& O_NONBLOCK
, NULL
);
2213 ret
= min_t(ssize_t
, ret
, len
);
2220 static void tun_prog_free(struct rcu_head
*rcu
)
2222 struct tun_prog
*prog
= container_of(rcu
, struct tun_prog
, rcu
);
2224 bpf_prog_destroy(prog
->prog
);
2228 static int __tun_set_ebpf(struct tun_struct
*tun
,
2229 struct tun_prog __rcu
**prog_p
,
2230 struct bpf_prog
*prog
)
2232 struct tun_prog
*old
, *new = NULL
;
2235 new = kmalloc(sizeof(*new), GFP_KERNEL
);
2241 spin_lock_bh(&tun
->lock
);
2242 old
= rcu_dereference_protected(*prog_p
,
2243 lockdep_is_held(&tun
->lock
));
2244 rcu_assign_pointer(*prog_p
, new);
2245 spin_unlock_bh(&tun
->lock
);
2248 call_rcu(&old
->rcu
, tun_prog_free
);
2253 static void tun_free_netdev(struct net_device
*dev
)
2255 struct tun_struct
*tun
= netdev_priv(dev
);
2257 BUG_ON(!(list_empty(&tun
->disabled
)));
2259 free_percpu(tun
->pcpu_stats
);
2260 /* We clear pcpu_stats so that tun_set_iff() can tell if
2261 * tun_free_netdev() has been called from register_netdevice().
2263 tun
->pcpu_stats
= NULL
;
2265 tun_flow_uninit(tun
);
2266 security_tun_dev_free_security(tun
->security
);
2267 __tun_set_ebpf(tun
, &tun
->steering_prog
, NULL
);
2268 __tun_set_ebpf(tun
, &tun
->filter_prog
, NULL
);
2271 static void tun_setup(struct net_device
*dev
)
2273 struct tun_struct
*tun
= netdev_priv(dev
);
2275 tun
->owner
= INVALID_UID
;
2276 tun
->group
= INVALID_GID
;
2277 tun_default_link_ksettings(dev
, &tun
->link_ksettings
);
2279 dev
->ethtool_ops
= &tun_ethtool_ops
;
2280 dev
->needs_free_netdev
= true;
2281 dev
->priv_destructor
= tun_free_netdev
;
2282 /* We prefer our own queue length */
2283 dev
->tx_queue_len
= TUN_READQ_SIZE
;
2286 /* Trivial set of netlink ops to allow deleting tun or tap
2287 * device with netlink.
2289 static int tun_validate(struct nlattr
*tb
[], struct nlattr
*data
[],
2290 struct netlink_ext_ack
*extack
)
2292 NL_SET_ERR_MSG(extack
,
2293 "tun/tap creation via rtnetlink is not supported.");
2297 static size_t tun_get_size(const struct net_device
*dev
)
2299 BUILD_BUG_ON(sizeof(u32
) != sizeof(uid_t
));
2300 BUILD_BUG_ON(sizeof(u32
) != sizeof(gid_t
));
2302 return nla_total_size(sizeof(uid_t
)) + /* OWNER */
2303 nla_total_size(sizeof(gid_t
)) + /* GROUP */
2304 nla_total_size(sizeof(u8
)) + /* TYPE */
2305 nla_total_size(sizeof(u8
)) + /* PI */
2306 nla_total_size(sizeof(u8
)) + /* VNET_HDR */
2307 nla_total_size(sizeof(u8
)) + /* PERSIST */
2308 nla_total_size(sizeof(u8
)) + /* MULTI_QUEUE */
2309 nla_total_size(sizeof(u32
)) + /* NUM_QUEUES */
2310 nla_total_size(sizeof(u32
)) + /* NUM_DISABLED_QUEUES */
2314 static int tun_fill_info(struct sk_buff
*skb
, const struct net_device
*dev
)
2316 struct tun_struct
*tun
= netdev_priv(dev
);
2318 if (nla_put_u8(skb
, IFLA_TUN_TYPE
, tun
->flags
& TUN_TYPE_MASK
))
2319 goto nla_put_failure
;
2320 if (uid_valid(tun
->owner
) &&
2321 nla_put_u32(skb
, IFLA_TUN_OWNER
,
2322 from_kuid_munged(current_user_ns(), tun
->owner
)))
2323 goto nla_put_failure
;
2324 if (gid_valid(tun
->group
) &&
2325 nla_put_u32(skb
, IFLA_TUN_GROUP
,
2326 from_kgid_munged(current_user_ns(), tun
->group
)))
2327 goto nla_put_failure
;
2328 if (nla_put_u8(skb
, IFLA_TUN_PI
, !(tun
->flags
& IFF_NO_PI
)))
2329 goto nla_put_failure
;
2330 if (nla_put_u8(skb
, IFLA_TUN_VNET_HDR
, !!(tun
->flags
& IFF_VNET_HDR
)))
2331 goto nla_put_failure
;
2332 if (nla_put_u8(skb
, IFLA_TUN_PERSIST
, !!(tun
->flags
& IFF_PERSIST
)))
2333 goto nla_put_failure
;
2334 if (nla_put_u8(skb
, IFLA_TUN_MULTI_QUEUE
,
2335 !!(tun
->flags
& IFF_MULTI_QUEUE
)))
2336 goto nla_put_failure
;
2337 if (tun
->flags
& IFF_MULTI_QUEUE
) {
2338 if (nla_put_u32(skb
, IFLA_TUN_NUM_QUEUES
, tun
->numqueues
))
2339 goto nla_put_failure
;
2340 if (nla_put_u32(skb
, IFLA_TUN_NUM_DISABLED_QUEUES
,
2342 goto nla_put_failure
;
2351 static struct rtnl_link_ops tun_link_ops __read_mostly
= {
2353 .priv_size
= sizeof(struct tun_struct
),
2355 .validate
= tun_validate
,
2356 .get_size
= tun_get_size
,
2357 .fill_info
= tun_fill_info
,
2360 static void tun_sock_write_space(struct sock
*sk
)
2362 struct tun_file
*tfile
;
2363 wait_queue_head_t
*wqueue
;
2365 if (!sock_writeable(sk
))
2368 if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE
, &sk
->sk_socket
->flags
))
2371 wqueue
= sk_sleep(sk
);
2372 if (wqueue
&& waitqueue_active(wqueue
))
2373 wake_up_interruptible_sync_poll(wqueue
, EPOLLOUT
|
2374 EPOLLWRNORM
| EPOLLWRBAND
);
2376 tfile
= container_of(sk
, struct tun_file
, sk
);
2377 kill_fasync(&tfile
->fasync
, SIGIO
, POLL_OUT
);
2380 static void tun_put_page(struct tun_page
*tpage
)
2383 __page_frag_cache_drain(tpage
->page
, tpage
->count
);
2386 static int tun_xdp_one(struct tun_struct
*tun
,
2387 struct tun_file
*tfile
,
2388 struct xdp_buff
*xdp
, int *flush
,
2389 struct tun_page
*tpage
)
2391 unsigned int datasize
= xdp
->data_end
- xdp
->data
;
2392 struct tun_xdp_hdr
*hdr
= xdp
->data_hard_start
;
2393 struct virtio_net_hdr
*gso
= &hdr
->gso
;
2394 struct tun_pcpu_stats
*stats
;
2395 struct bpf_prog
*xdp_prog
;
2396 struct sk_buff
*skb
= NULL
;
2397 u32 rxhash
= 0, act
;
2398 int buflen
= hdr
->buflen
;
2400 bool skb_xdp
= false;
2403 xdp_prog
= rcu_dereference(tun
->xdp_prog
);
2405 if (gso
->gso_type
) {
2409 xdp_set_data_meta_invalid(xdp
);
2410 xdp
->rxq
= &tfile
->xdp_rxq
;
2412 act
= bpf_prog_run_xdp(xdp_prog
, xdp
);
2413 err
= tun_xdp_act(tun
, xdp_prog
, xdp
, act
);
2415 put_page(virt_to_head_page(xdp
->data
));
2428 page
= virt_to_head_page(xdp
->data
);
2429 if (tpage
->page
== page
) {
2432 tun_put_page(tpage
);
2441 skb
= build_skb(xdp
->data_hard_start
, buflen
);
2447 skb_reserve(skb
, xdp
->data
- xdp
->data_hard_start
);
2448 skb_put(skb
, xdp
->data_end
- xdp
->data
);
2450 if (virtio_net_hdr_to_skb(skb
, gso
, tun_is_little_endian(tun
))) {
2451 this_cpu_inc(tun
->pcpu_stats
->rx_frame_errors
);
2457 skb
->protocol
= eth_type_trans(skb
, tun
->dev
);
2458 skb_reset_network_header(skb
);
2459 skb_probe_transport_header(skb
);
2462 err
= do_xdp_generic(xdp_prog
, skb
);
2463 if (err
!= XDP_PASS
)
2467 if (!rcu_dereference(tun
->steering_prog
) && tun
->numqueues
> 1 &&
2469 rxhash
= __skb_get_hash_symmetric(skb
);
2471 skb_record_rx_queue(skb
, tfile
->queue_index
);
2472 netif_receive_skb(skb
);
2474 /* No need for get_cpu_ptr() here since this function is
2475 * always called with bh disabled
2477 stats
= this_cpu_ptr(tun
->pcpu_stats
);
2478 u64_stats_update_begin(&stats
->syncp
);
2479 u64_stats_inc(&stats
->rx_packets
);
2480 u64_stats_add(&stats
->rx_bytes
, datasize
);
2481 u64_stats_update_end(&stats
->syncp
);
2484 tun_flow_update(tun
, rxhash
, tfile
);
2490 static int tun_sendmsg(struct socket
*sock
, struct msghdr
*m
, size_t total_len
)
2493 struct tun_file
*tfile
= container_of(sock
, struct tun_file
, socket
);
2494 struct tun_struct
*tun
= tun_get(tfile
);
2495 struct tun_msg_ctl
*ctl
= m
->msg_control
;
2496 struct xdp_buff
*xdp
;
2501 if (ctl
&& (ctl
->type
== TUN_MSG_PTR
)) {
2502 struct tun_page tpage
;
2506 memset(&tpage
, 0, sizeof(tpage
));
2511 for (i
= 0; i
< n
; i
++) {
2512 xdp
= &((struct xdp_buff
*)ctl
->ptr
)[i
];
2513 tun_xdp_one(tun
, tfile
, xdp
, &flush
, &tpage
);
2522 tun_put_page(&tpage
);
2528 ret
= tun_get_user(tun
, tfile
, ctl
? ctl
->ptr
: NULL
, &m
->msg_iter
,
2529 m
->msg_flags
& MSG_DONTWAIT
,
2530 m
->msg_flags
& MSG_MORE
);
2536 static int tun_recvmsg(struct socket
*sock
, struct msghdr
*m
, size_t total_len
,
2539 struct tun_file
*tfile
= container_of(sock
, struct tun_file
, socket
);
2540 struct tun_struct
*tun
= tun_get(tfile
);
2541 void *ptr
= m
->msg_control
;
2549 if (flags
& ~(MSG_DONTWAIT
|MSG_TRUNC
|MSG_ERRQUEUE
)) {
2553 if (flags
& MSG_ERRQUEUE
) {
2554 ret
= sock_recv_errqueue(sock
->sk
, m
, total_len
,
2555 SOL_PACKET
, TUN_TX_TIMESTAMP
);
2558 ret
= tun_do_read(tun
, tfile
, &m
->msg_iter
, flags
& MSG_DONTWAIT
, ptr
);
2559 if (ret
> (ssize_t
)total_len
) {
2560 m
->msg_flags
|= MSG_TRUNC
;
2561 ret
= flags
& MSG_TRUNC
? ret
: total_len
;
2574 static int tun_ptr_peek_len(void *ptr
)
2577 if (tun_is_xdp_frame(ptr
)) {
2578 struct xdp_frame
*xdpf
= tun_ptr_to_xdp(ptr
);
2582 return __skb_array_len_with_tag(ptr
);
2588 static int tun_peek_len(struct socket
*sock
)
2590 struct tun_file
*tfile
= container_of(sock
, struct tun_file
, socket
);
2591 struct tun_struct
*tun
;
2594 tun
= tun_get(tfile
);
2598 ret
= PTR_RING_PEEK_CALL(&tfile
->tx_ring
, tun_ptr_peek_len
);
2604 /* Ops structure to mimic raw sockets with tun */
2605 static const struct proto_ops tun_socket_ops
= {
2606 .peek_len
= tun_peek_len
,
2607 .sendmsg
= tun_sendmsg
,
2608 .recvmsg
= tun_recvmsg
,
2611 static struct proto tun_proto
= {
2613 .owner
= THIS_MODULE
,
2614 .obj_size
= sizeof(struct tun_file
),
2617 static int tun_flags(struct tun_struct
*tun
)
2619 return tun
->flags
& (TUN_FEATURES
| IFF_PERSIST
| IFF_TUN
| IFF_TAP
);
2622 static ssize_t
tun_show_flags(struct device
*dev
, struct device_attribute
*attr
,
2625 struct tun_struct
*tun
= netdev_priv(to_net_dev(dev
));
2626 return sprintf(buf
, "0x%x\n", tun_flags(tun
));
2629 static ssize_t
tun_show_owner(struct device
*dev
, struct device_attribute
*attr
,
2632 struct tun_struct
*tun
= netdev_priv(to_net_dev(dev
));
2633 return uid_valid(tun
->owner
)?
2634 sprintf(buf
, "%u\n",
2635 from_kuid_munged(current_user_ns(), tun
->owner
)):
2636 sprintf(buf
, "-1\n");
2639 static ssize_t
tun_show_group(struct device
*dev
, struct device_attribute
*attr
,
2642 struct tun_struct
*tun
= netdev_priv(to_net_dev(dev
));
2643 return gid_valid(tun
->group
) ?
2644 sprintf(buf
, "%u\n",
2645 from_kgid_munged(current_user_ns(), tun
->group
)):
2646 sprintf(buf
, "-1\n");
2649 static DEVICE_ATTR(tun_flags
, 0444, tun_show_flags
, NULL
);
2650 static DEVICE_ATTR(owner
, 0444, tun_show_owner
, NULL
);
2651 static DEVICE_ATTR(group
, 0444, tun_show_group
, NULL
);
2653 static struct attribute
*tun_dev_attrs
[] = {
2654 &dev_attr_tun_flags
.attr
,
2655 &dev_attr_owner
.attr
,
2656 &dev_attr_group
.attr
,
2660 static const struct attribute_group tun_attr_group
= {
2661 .attrs
= tun_dev_attrs
2664 static int tun_set_iff(struct net
*net
, struct file
*file
, struct ifreq
*ifr
)
2666 struct tun_struct
*tun
;
2667 struct tun_file
*tfile
= file
->private_data
;
2668 struct net_device
*dev
;
2671 if (tfile
->detached
)
2674 if ((ifr
->ifr_flags
& IFF_NAPI_FRAGS
)) {
2675 if (!capable(CAP_NET_ADMIN
))
2678 if (!(ifr
->ifr_flags
& IFF_NAPI
) ||
2679 (ifr
->ifr_flags
& TUN_TYPE_MASK
) != IFF_TAP
)
2683 dev
= __dev_get_by_name(net
, ifr
->ifr_name
);
2685 if (ifr
->ifr_flags
& IFF_TUN_EXCL
)
2687 if ((ifr
->ifr_flags
& IFF_TUN
) && dev
->netdev_ops
== &tun_netdev_ops
)
2688 tun
= netdev_priv(dev
);
2689 else if ((ifr
->ifr_flags
& IFF_TAP
) && dev
->netdev_ops
== &tap_netdev_ops
)
2690 tun
= netdev_priv(dev
);
2694 if (!!(ifr
->ifr_flags
& IFF_MULTI_QUEUE
) !=
2695 !!(tun
->flags
& IFF_MULTI_QUEUE
))
2698 if (tun_not_capable(tun
))
2700 err
= security_tun_dev_open(tun
->security
);
2704 err
= tun_attach(tun
, file
, ifr
->ifr_flags
& IFF_NOFILTER
,
2705 ifr
->ifr_flags
& IFF_NAPI
,
2706 ifr
->ifr_flags
& IFF_NAPI_FRAGS
, true);
2710 if (tun
->flags
& IFF_MULTI_QUEUE
&&
2711 (tun
->numqueues
+ tun
->numdisabled
> 1)) {
2712 /* One or more queue has already been attached, no need
2713 * to initialize the device again.
2715 netdev_state_change(dev
);
2719 tun
->flags
= (tun
->flags
& ~TUN_FEATURES
) |
2720 (ifr
->ifr_flags
& TUN_FEATURES
);
2722 netdev_state_change(dev
);
2725 unsigned long flags
= 0;
2726 int queues
= ifr
->ifr_flags
& IFF_MULTI_QUEUE
?
2729 if (!ns_capable(net
->user_ns
, CAP_NET_ADMIN
))
2731 err
= security_tun_dev_create();
2736 if (ifr
->ifr_flags
& IFF_TUN
) {
2740 } else if (ifr
->ifr_flags
& IFF_TAP
) {
2748 name
= ifr
->ifr_name
;
2750 dev
= alloc_netdev_mqs(sizeof(struct tun_struct
), name
,
2751 NET_NAME_UNKNOWN
, tun_setup
, queues
,
2757 dev_net_set(dev
, net
);
2758 dev
->rtnl_link_ops
= &tun_link_ops
;
2759 dev
->ifindex
= tfile
->ifindex
;
2760 dev
->sysfs_groups
[0] = &tun_attr_group
;
2762 tun
= netdev_priv(dev
);
2765 tun
->txflt
.count
= 0;
2766 tun
->vnet_hdr_sz
= sizeof(struct virtio_net_hdr
);
2768 tun
->align
= NET_SKB_PAD
;
2769 tun
->filter_attached
= false;
2770 tun
->sndbuf
= tfile
->socket
.sk
->sk_sndbuf
;
2771 tun
->rx_batched
= 0;
2772 RCU_INIT_POINTER(tun
->steering_prog
, NULL
);
2774 tun
->pcpu_stats
= netdev_alloc_pcpu_stats(struct tun_pcpu_stats
);
2775 if (!tun
->pcpu_stats
) {
2780 spin_lock_init(&tun
->lock
);
2782 err
= security_tun_dev_alloc_security(&tun
->security
);
2789 dev
->hw_features
= NETIF_F_SG
| NETIF_F_FRAGLIST
|
2790 TUN_USER_FEATURES
| NETIF_F_HW_VLAN_CTAG_TX
|
2791 NETIF_F_HW_VLAN_STAG_TX
;
2792 dev
->features
= dev
->hw_features
| NETIF_F_LLTX
;
2793 dev
->vlan_features
= dev
->features
&
2794 ~(NETIF_F_HW_VLAN_CTAG_TX
|
2795 NETIF_F_HW_VLAN_STAG_TX
);
2797 tun
->flags
= (tun
->flags
& ~TUN_FEATURES
) |
2798 (ifr
->ifr_flags
& TUN_FEATURES
);
2800 INIT_LIST_HEAD(&tun
->disabled
);
2801 err
= tun_attach(tun
, file
, false, ifr
->ifr_flags
& IFF_NAPI
,
2802 ifr
->ifr_flags
& IFF_NAPI_FRAGS
, false);
2806 err
= register_netdevice(tun
->dev
);
2809 /* free_netdev() won't check refcnt, to aovid race
2810 * with dev_put() we need publish tun after registration.
2812 rcu_assign_pointer(tfile
->tun
, tun
);
2815 netif_carrier_on(tun
->dev
);
2817 /* Make sure persistent devices do not get stuck in
2820 if (netif_running(tun
->dev
))
2821 netif_tx_wake_all_queues(tun
->dev
);
2823 strcpy(ifr
->ifr_name
, tun
->dev
->name
);
2827 tun_detach_all(dev
);
2828 /* We are here because register_netdevice() has failed.
2829 * If register_netdevice() already called tun_free_netdev()
2830 * while dealing with the error, tun->pcpu_stats has been cleared.
2832 if (!tun
->pcpu_stats
)
2836 tun_flow_uninit(tun
);
2837 security_tun_dev_free_security(tun
->security
);
2839 free_percpu(tun
->pcpu_stats
);
2845 static void tun_get_iff(struct tun_struct
*tun
, struct ifreq
*ifr
)
2847 strcpy(ifr
->ifr_name
, tun
->dev
->name
);
2849 ifr
->ifr_flags
= tun_flags(tun
);
2853 /* This is like a cut-down ethtool ops, except done via tun fd so no
2854 * privs required. */
2855 static int set_offload(struct tun_struct
*tun
, unsigned long arg
)
2857 netdev_features_t features
= 0;
2859 if (arg
& TUN_F_CSUM
) {
2860 features
|= NETIF_F_HW_CSUM
;
2863 if (arg
& (TUN_F_TSO4
|TUN_F_TSO6
)) {
2864 if (arg
& TUN_F_TSO_ECN
) {
2865 features
|= NETIF_F_TSO_ECN
;
2866 arg
&= ~TUN_F_TSO_ECN
;
2868 if (arg
& TUN_F_TSO4
)
2869 features
|= NETIF_F_TSO
;
2870 if (arg
& TUN_F_TSO6
)
2871 features
|= NETIF_F_TSO6
;
2872 arg
&= ~(TUN_F_TSO4
|TUN_F_TSO6
);
2878 /* This gives the user a way to test for new features in future by
2879 * trying to set them. */
2883 tun
->set_features
= features
;
2884 tun
->dev
->wanted_features
&= ~TUN_USER_FEATURES
;
2885 tun
->dev
->wanted_features
|= features
;
2886 netdev_update_features(tun
->dev
);
2891 static void tun_detach_filter(struct tun_struct
*tun
, int n
)
2894 struct tun_file
*tfile
;
2896 for (i
= 0; i
< n
; i
++) {
2897 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
2898 lock_sock(tfile
->socket
.sk
);
2899 sk_detach_filter(tfile
->socket
.sk
);
2900 release_sock(tfile
->socket
.sk
);
2903 tun
->filter_attached
= false;
2906 static int tun_attach_filter(struct tun_struct
*tun
)
2909 struct tun_file
*tfile
;
2911 for (i
= 0; i
< tun
->numqueues
; i
++) {
2912 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
2913 lock_sock(tfile
->socket
.sk
);
2914 ret
= sk_attach_filter(&tun
->fprog
, tfile
->socket
.sk
);
2915 release_sock(tfile
->socket
.sk
);
2917 tun_detach_filter(tun
, i
);
2922 tun
->filter_attached
= true;
2926 static void tun_set_sndbuf(struct tun_struct
*tun
)
2928 struct tun_file
*tfile
;
2931 for (i
= 0; i
< tun
->numqueues
; i
++) {
2932 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
2933 tfile
->socket
.sk
->sk_sndbuf
= tun
->sndbuf
;
2937 static int tun_set_queue(struct file
*file
, struct ifreq
*ifr
)
2939 struct tun_file
*tfile
= file
->private_data
;
2940 struct tun_struct
*tun
;
2945 if (ifr
->ifr_flags
& IFF_ATTACH_QUEUE
) {
2946 tun
= tfile
->detached
;
2951 ret
= security_tun_dev_attach_queue(tun
->security
);
2954 ret
= tun_attach(tun
, file
, false, tun
->flags
& IFF_NAPI
,
2955 tun
->flags
& IFF_NAPI_FRAGS
, true);
2956 } else if (ifr
->ifr_flags
& IFF_DETACH_QUEUE
) {
2957 tun
= rtnl_dereference(tfile
->tun
);
2958 if (!tun
|| !(tun
->flags
& IFF_MULTI_QUEUE
) || tfile
->detached
)
2961 __tun_detach(tfile
, false);
2966 netdev_state_change(tun
->dev
);
2973 static int tun_set_ebpf(struct tun_struct
*tun
, struct tun_prog
**prog_p
,
2976 struct bpf_prog
*prog
;
2979 if (copy_from_user(&fd
, data
, sizeof(fd
)))
2985 prog
= bpf_prog_get_type(fd
, BPF_PROG_TYPE_SOCKET_FILTER
);
2987 return PTR_ERR(prog
);
2990 return __tun_set_ebpf(tun
, prog_p
, prog
);
2993 static long __tun_chr_ioctl(struct file
*file
, unsigned int cmd
,
2994 unsigned long arg
, int ifreq_len
)
2996 struct tun_file
*tfile
= file
->private_data
;
2997 struct net
*net
= sock_net(&tfile
->sk
);
2998 struct tun_struct
*tun
;
2999 void __user
* argp
= (void __user
*)arg
;
3000 unsigned int ifindex
, carrier
;
3008 bool do_notify
= false;
3010 if (cmd
== TUNSETIFF
|| cmd
== TUNSETQUEUE
||
3011 (_IOC_TYPE(cmd
) == SOCK_IOC_TYPE
&& cmd
!= SIOCGSKNS
)) {
3012 if (copy_from_user(&ifr
, argp
, ifreq_len
))
3015 memset(&ifr
, 0, sizeof(ifr
));
3017 if (cmd
== TUNGETFEATURES
) {
3018 /* Currently this just means: "what IFF flags are valid?".
3019 * This is needed because we never checked for invalid flags on
3022 return put_user(IFF_TUN
| IFF_TAP
| TUN_FEATURES
,
3023 (unsigned int __user
*)argp
);
3024 } else if (cmd
== TUNSETQUEUE
) {
3025 return tun_set_queue(file
, &ifr
);
3026 } else if (cmd
== SIOCGSKNS
) {
3027 if (!ns_capable(net
->user_ns
, CAP_NET_ADMIN
))
3029 return open_related_ns(&net
->ns
, get_net_ns
);
3035 tun
= tun_get(tfile
);
3036 if (cmd
== TUNSETIFF
) {
3041 ifr
.ifr_name
[IFNAMSIZ
-1] = '\0';
3043 ret
= tun_set_iff(net
, file
, &ifr
);
3048 if (copy_to_user(argp
, &ifr
, ifreq_len
))
3052 if (cmd
== TUNSETIFINDEX
) {
3058 if (copy_from_user(&ifindex
, argp
, sizeof(ifindex
)))
3062 tfile
->ifindex
= ifindex
;
3070 netif_info(tun
, drv
, tun
->dev
, "tun_chr_ioctl cmd %u\n", cmd
);
3072 net
= dev_net(tun
->dev
);
3076 tun_get_iff(tun
, &ifr
);
3078 if (tfile
->detached
)
3079 ifr
.ifr_flags
|= IFF_DETACH_QUEUE
;
3080 if (!tfile
->socket
.sk
->sk_filter
)
3081 ifr
.ifr_flags
|= IFF_NOFILTER
;
3083 if (copy_to_user(argp
, &ifr
, ifreq_len
))
3088 /* Disable/Enable checksum */
3090 /* [unimplemented] */
3091 netif_info(tun
, drv
, tun
->dev
, "ignored: set checksum %s\n",
3092 arg
? "disabled" : "enabled");
3096 /* Disable/Enable persist mode. Keep an extra reference to the
3097 * module to prevent the module being unprobed.
3099 if (arg
&& !(tun
->flags
& IFF_PERSIST
)) {
3100 tun
->flags
|= IFF_PERSIST
;
3101 __module_get(THIS_MODULE
);
3104 if (!arg
&& (tun
->flags
& IFF_PERSIST
)) {
3105 tun
->flags
&= ~IFF_PERSIST
;
3106 module_put(THIS_MODULE
);
3110 netif_info(tun
, drv
, tun
->dev
, "persist %s\n",
3111 arg
? "enabled" : "disabled");
3115 /* Set owner of the device */
3116 owner
= make_kuid(current_user_ns(), arg
);
3117 if (!uid_valid(owner
)) {
3123 netif_info(tun
, drv
, tun
->dev
, "owner set to %u\n",
3124 from_kuid(&init_user_ns
, tun
->owner
));
3128 /* Set group of the device */
3129 group
= make_kgid(current_user_ns(), arg
);
3130 if (!gid_valid(group
)) {
3136 netif_info(tun
, drv
, tun
->dev
, "group set to %u\n",
3137 from_kgid(&init_user_ns
, tun
->group
));
3141 /* Only allow setting the type when the interface is down */
3142 if (tun
->dev
->flags
& IFF_UP
) {
3143 netif_info(tun
, drv
, tun
->dev
,
3144 "Linktype set failed because interface is up\n");
3147 tun
->dev
->type
= (int) arg
;
3148 netif_info(tun
, drv
, tun
->dev
, "linktype set to %d\n",
3155 tun
->msg_enable
= (u32
)arg
;
3159 ret
= set_offload(tun
, arg
);
3162 case TUNSETTXFILTER
:
3163 /* Can be set only for TAPs */
3165 if ((tun
->flags
& TUN_TYPE_MASK
) != IFF_TAP
)
3167 ret
= update_filter(&tun
->txflt
, (void __user
*)arg
);
3171 /* Get hw address */
3172 memcpy(ifr
.ifr_hwaddr
.sa_data
, tun
->dev
->dev_addr
, ETH_ALEN
);
3173 ifr
.ifr_hwaddr
.sa_family
= tun
->dev
->type
;
3174 if (copy_to_user(argp
, &ifr
, ifreq_len
))
3179 /* Set hw address */
3180 ret
= dev_set_mac_address(tun
->dev
, &ifr
.ifr_hwaddr
, NULL
);
3184 sndbuf
= tfile
->socket
.sk
->sk_sndbuf
;
3185 if (copy_to_user(argp
, &sndbuf
, sizeof(sndbuf
)))
3190 if (copy_from_user(&sndbuf
, argp
, sizeof(sndbuf
))) {
3199 tun
->sndbuf
= sndbuf
;
3200 tun_set_sndbuf(tun
);
3203 case TUNGETVNETHDRSZ
:
3204 vnet_hdr_sz
= tun
->vnet_hdr_sz
;
3205 if (copy_to_user(argp
, &vnet_hdr_sz
, sizeof(vnet_hdr_sz
)))
3209 case TUNSETVNETHDRSZ
:
3210 if (copy_from_user(&vnet_hdr_sz
, argp
, sizeof(vnet_hdr_sz
))) {
3214 if (vnet_hdr_sz
< (int)sizeof(struct virtio_net_hdr
)) {
3219 tun
->vnet_hdr_sz
= vnet_hdr_sz
;
3223 le
= !!(tun
->flags
& TUN_VNET_LE
);
3224 if (put_user(le
, (int __user
*)argp
))
3229 if (get_user(le
, (int __user
*)argp
)) {
3234 tun
->flags
|= TUN_VNET_LE
;
3236 tun
->flags
&= ~TUN_VNET_LE
;
3240 ret
= tun_get_vnet_be(tun
, argp
);
3244 ret
= tun_set_vnet_be(tun
, argp
);
3247 case TUNATTACHFILTER
:
3248 /* Can be set only for TAPs */
3250 if ((tun
->flags
& TUN_TYPE_MASK
) != IFF_TAP
)
3253 if (copy_from_user(&tun
->fprog
, argp
, sizeof(tun
->fprog
)))
3256 ret
= tun_attach_filter(tun
);
3259 case TUNDETACHFILTER
:
3260 /* Can be set only for TAPs */
3262 if ((tun
->flags
& TUN_TYPE_MASK
) != IFF_TAP
)
3265 tun_detach_filter(tun
, tun
->numqueues
);
3270 if ((tun
->flags
& TUN_TYPE_MASK
) != IFF_TAP
)
3273 if (copy_to_user(argp
, &tun
->fprog
, sizeof(tun
->fprog
)))
3278 case TUNSETSTEERINGEBPF
:
3279 ret
= tun_set_ebpf(tun
, &tun
->steering_prog
, argp
);
3282 case TUNSETFILTEREBPF
:
3283 ret
= tun_set_ebpf(tun
, &tun
->filter_prog
, argp
);
3288 if (copy_from_user(&carrier
, argp
, sizeof(carrier
)))
3291 ret
= tun_net_change_carrier(tun
->dev
, (bool)carrier
);
3294 case TUNGETDEVNETNS
:
3296 if (!ns_capable(net
->user_ns
, CAP_NET_ADMIN
))
3298 ret
= open_related_ns(&net
->ns
, get_net_ns
);
3307 netdev_state_change(tun
->dev
);
3316 static long tun_chr_ioctl(struct file
*file
,
3317 unsigned int cmd
, unsigned long arg
)
3319 return __tun_chr_ioctl(file
, cmd
, arg
, sizeof (struct ifreq
));
3322 #ifdef CONFIG_COMPAT
3323 static long tun_chr_compat_ioctl(struct file
*file
,
3324 unsigned int cmd
, unsigned long arg
)
3329 case TUNSETTXFILTER
:
3334 arg
= (unsigned long)compat_ptr(arg
);
3337 arg
= (compat_ulong_t
)arg
;
3342 * compat_ifreq is shorter than ifreq, so we must not access beyond
3343 * the end of that structure. All fields that are used in this
3344 * driver are compatible though, we don't need to convert the
3347 return __tun_chr_ioctl(file
, cmd
, arg
, sizeof(struct compat_ifreq
));
3349 #endif /* CONFIG_COMPAT */
3351 static int tun_chr_fasync(int fd
, struct file
*file
, int on
)
3353 struct tun_file
*tfile
= file
->private_data
;
3356 if ((ret
= fasync_helper(fd
, file
, on
, &tfile
->fasync
)) < 0)
3360 __f_setown(file
, task_pid(current
), PIDTYPE_TGID
, 0);
3361 tfile
->flags
|= TUN_FASYNC
;
3363 tfile
->flags
&= ~TUN_FASYNC
;
3369 static int tun_chr_open(struct inode
*inode
, struct file
* file
)
3371 struct net
*net
= current
->nsproxy
->net_ns
;
3372 struct tun_file
*tfile
;
3374 tfile
= (struct tun_file
*)sk_alloc(net
, AF_UNSPEC
, GFP_KERNEL
,
3378 if (ptr_ring_init(&tfile
->tx_ring
, 0, GFP_KERNEL
)) {
3379 sk_free(&tfile
->sk
);
3383 mutex_init(&tfile
->napi_mutex
);
3384 RCU_INIT_POINTER(tfile
->tun
, NULL
);
3388 init_waitqueue_head(&tfile
->socket
.wq
.wait
);
3390 tfile
->socket
.file
= file
;
3391 tfile
->socket
.ops
= &tun_socket_ops
;
3393 sock_init_data(&tfile
->socket
, &tfile
->sk
);
3395 tfile
->sk
.sk_write_space
= tun_sock_write_space
;
3396 tfile
->sk
.sk_sndbuf
= INT_MAX
;
3398 file
->private_data
= tfile
;
3399 INIT_LIST_HEAD(&tfile
->next
);
3401 sock_set_flag(&tfile
->sk
, SOCK_ZEROCOPY
);
3406 static int tun_chr_close(struct inode
*inode
, struct file
*file
)
3408 struct tun_file
*tfile
= file
->private_data
;
3410 tun_detach(tfile
, true);
3415 #ifdef CONFIG_PROC_FS
3416 static void tun_chr_show_fdinfo(struct seq_file
*m
, struct file
*file
)
3418 struct tun_file
*tfile
= file
->private_data
;
3419 struct tun_struct
*tun
;
3422 memset(&ifr
, 0, sizeof(ifr
));
3425 tun
= tun_get(tfile
);
3427 tun_get_iff(tun
, &ifr
);
3433 seq_printf(m
, "iff:\t%s\n", ifr
.ifr_name
);
3437 static const struct file_operations tun_fops
= {
3438 .owner
= THIS_MODULE
,
3439 .llseek
= no_llseek
,
3440 .read_iter
= tun_chr_read_iter
,
3441 .write_iter
= tun_chr_write_iter
,
3442 .poll
= tun_chr_poll
,
3443 .unlocked_ioctl
= tun_chr_ioctl
,
3444 #ifdef CONFIG_COMPAT
3445 .compat_ioctl
= tun_chr_compat_ioctl
,
3447 .open
= tun_chr_open
,
3448 .release
= tun_chr_close
,
3449 .fasync
= tun_chr_fasync
,
3450 #ifdef CONFIG_PROC_FS
3451 .show_fdinfo
= tun_chr_show_fdinfo
,
3455 static struct miscdevice tun_miscdev
= {
3458 .nodename
= "net/tun",
3462 /* ethtool interface */
3464 static void tun_default_link_ksettings(struct net_device
*dev
,
3465 struct ethtool_link_ksettings
*cmd
)
3467 ethtool_link_ksettings_zero_link_mode(cmd
, supported
);
3468 ethtool_link_ksettings_zero_link_mode(cmd
, advertising
);
3469 cmd
->base
.speed
= SPEED_10
;
3470 cmd
->base
.duplex
= DUPLEX_FULL
;
3471 cmd
->base
.port
= PORT_TP
;
3472 cmd
->base
.phy_address
= 0;
3473 cmd
->base
.autoneg
= AUTONEG_DISABLE
;
3476 static int tun_get_link_ksettings(struct net_device
*dev
,
3477 struct ethtool_link_ksettings
*cmd
)
3479 struct tun_struct
*tun
= netdev_priv(dev
);
3481 memcpy(cmd
, &tun
->link_ksettings
, sizeof(*cmd
));
3485 static int tun_set_link_ksettings(struct net_device
*dev
,
3486 const struct ethtool_link_ksettings
*cmd
)
3488 struct tun_struct
*tun
= netdev_priv(dev
);
3490 memcpy(&tun
->link_ksettings
, cmd
, sizeof(*cmd
));
3494 static void tun_get_drvinfo(struct net_device
*dev
, struct ethtool_drvinfo
*info
)
3496 struct tun_struct
*tun
= netdev_priv(dev
);
3498 strlcpy(info
->driver
, DRV_NAME
, sizeof(info
->driver
));
3499 strlcpy(info
->version
, DRV_VERSION
, sizeof(info
->version
));
3501 switch (tun
->flags
& TUN_TYPE_MASK
) {
3503 strlcpy(info
->bus_info
, "tun", sizeof(info
->bus_info
));
3506 strlcpy(info
->bus_info
, "tap", sizeof(info
->bus_info
));
3511 static u32
tun_get_msglevel(struct net_device
*dev
)
3513 struct tun_struct
*tun
= netdev_priv(dev
);
3515 return tun
->msg_enable
;
3518 static void tun_set_msglevel(struct net_device
*dev
, u32 value
)
3520 struct tun_struct
*tun
= netdev_priv(dev
);
3522 tun
->msg_enable
= value
;
3525 static int tun_get_coalesce(struct net_device
*dev
,
3526 struct ethtool_coalesce
*ec
)
3528 struct tun_struct
*tun
= netdev_priv(dev
);
3530 ec
->rx_max_coalesced_frames
= tun
->rx_batched
;
3535 static int tun_set_coalesce(struct net_device
*dev
,
3536 struct ethtool_coalesce
*ec
)
3538 struct tun_struct
*tun
= netdev_priv(dev
);
3540 if (ec
->rx_max_coalesced_frames
> NAPI_POLL_WEIGHT
)
3541 tun
->rx_batched
= NAPI_POLL_WEIGHT
;
3543 tun
->rx_batched
= ec
->rx_max_coalesced_frames
;
3548 static const struct ethtool_ops tun_ethtool_ops
= {
3549 .supported_coalesce_params
= ETHTOOL_COALESCE_RX_MAX_FRAMES
,
3550 .get_drvinfo
= tun_get_drvinfo
,
3551 .get_msglevel
= tun_get_msglevel
,
3552 .set_msglevel
= tun_set_msglevel
,
3553 .get_link
= ethtool_op_get_link
,
3554 .get_ts_info
= ethtool_op_get_ts_info
,
3555 .get_coalesce
= tun_get_coalesce
,
3556 .set_coalesce
= tun_set_coalesce
,
3557 .get_link_ksettings
= tun_get_link_ksettings
,
3558 .set_link_ksettings
= tun_set_link_ksettings
,
3561 static int tun_queue_resize(struct tun_struct
*tun
)
3563 struct net_device
*dev
= tun
->dev
;
3564 struct tun_file
*tfile
;
3565 struct ptr_ring
**rings
;
3566 int n
= tun
->numqueues
+ tun
->numdisabled
;
3569 rings
= kmalloc_array(n
, sizeof(*rings
), GFP_KERNEL
);
3573 for (i
= 0; i
< tun
->numqueues
; i
++) {
3574 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
3575 rings
[i
] = &tfile
->tx_ring
;
3577 list_for_each_entry(tfile
, &tun
->disabled
, next
)
3578 rings
[i
++] = &tfile
->tx_ring
;
3580 ret
= ptr_ring_resize_multiple(rings
, n
,
3581 dev
->tx_queue_len
, GFP_KERNEL
,
3588 static int tun_device_event(struct notifier_block
*unused
,
3589 unsigned long event
, void *ptr
)
3591 struct net_device
*dev
= netdev_notifier_info_to_dev(ptr
);
3592 struct tun_struct
*tun
= netdev_priv(dev
);
3595 if (dev
->rtnl_link_ops
!= &tun_link_ops
)
3599 case NETDEV_CHANGE_TX_QUEUE_LEN
:
3600 if (tun_queue_resize(tun
))
3604 for (i
= 0; i
< tun
->numqueues
; i
++) {
3605 struct tun_file
*tfile
;
3607 tfile
= rtnl_dereference(tun
->tfiles
[i
]);
3608 tfile
->socket
.sk
->sk_write_space(tfile
->socket
.sk
);
3618 static struct notifier_block tun_notifier_block __read_mostly
= {
3619 .notifier_call
= tun_device_event
,
3622 static int __init
tun_init(void)
3626 pr_info("%s, %s\n", DRV_DESCRIPTION
, DRV_VERSION
);
3628 ret
= rtnl_link_register(&tun_link_ops
);
3630 pr_err("Can't register link_ops\n");
3634 ret
= misc_register(&tun_miscdev
);
3636 pr_err("Can't register misc device %d\n", TUN_MINOR
);
3640 ret
= register_netdevice_notifier(&tun_notifier_block
);
3642 pr_err("Can't register netdevice notifier\n");
3649 misc_deregister(&tun_miscdev
);
3651 rtnl_link_unregister(&tun_link_ops
);
3656 static void tun_cleanup(void)
3658 misc_deregister(&tun_miscdev
);
3659 rtnl_link_unregister(&tun_link_ops
);
3660 unregister_netdevice_notifier(&tun_notifier_block
);
3663 /* Get an underlying socket object from tun file. Returns error unless file is
3664 * attached to a device. The returned object works like a packet socket, it
3665 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
3666 * holding a reference to the file for as long as the socket is in use. */
3667 struct socket
*tun_get_socket(struct file
*file
)
3669 struct tun_file
*tfile
;
3670 if (file
->f_op
!= &tun_fops
)
3671 return ERR_PTR(-EINVAL
);
3672 tfile
= file
->private_data
;
3674 return ERR_PTR(-EBADFD
);
3675 return &tfile
->socket
;
3677 EXPORT_SYMBOL_GPL(tun_get_socket
);
3679 struct ptr_ring
*tun_get_tx_ring(struct file
*file
)
3681 struct tun_file
*tfile
;
3683 if (file
->f_op
!= &tun_fops
)
3684 return ERR_PTR(-EINVAL
);
3685 tfile
= file
->private_data
;
3687 return ERR_PTR(-EBADFD
);
3688 return &tfile
->tx_ring
;
3690 EXPORT_SYMBOL_GPL(tun_get_tx_ring
);
3692 module_init(tun_init
);
3693 module_exit(tun_cleanup
);
3694 MODULE_DESCRIPTION(DRV_DESCRIPTION
);
3695 MODULE_AUTHOR(DRV_COPYRIGHT
);
3696 MODULE_LICENSE("GPL");
3697 MODULE_ALIAS_MISCDEV(TUN_MINOR
);
3698 MODULE_ALIAS("devname:net/tun");