]> git.proxmox.com Git - mirror_ubuntu-disco-kernel.git/blame - drivers/net/tun.c
UBUNTU: Ubuntu-5.0.0-29.31
[mirror_ubuntu-disco-kernel.git] / drivers / net / tun.c
CommitLineData
1da177e4
LT
1/*
2 * TUN - Universal TUN/TAP device driver.
3 * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
16 */
17
18/*
19 * Changes:
20 *
ff4cc3ac
MK
21 * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
22 * Add TUNSETLINK ioctl to set the link encapsulation
23 *
1da177e4 24 * Mark Smith <markzzzsmith@yahoo.com.au>
344dc8ed 25 * Use eth_random_addr() for tap MAC address.
1da177e4
LT
26 *
27 * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20
28 * Fixes in packet dropping, queue length setting and queue wakeup.
29 * Increased default tx queue length.
30 * Added ethtool API.
31 * Minor cleanups
32 *
33 * Daniel Podlejski <underley@underley.eu.org>
34 * Modifications for 2.3.99-pre5 kernel.
35 */
36
6b8a66ee
JP
37#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
38
1da177e4
LT
39#define DRV_NAME "tun"
40#define DRV_VERSION "1.6"
41#define DRV_DESCRIPTION "Universal TUN/TAP device driver"
42#define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
43
1da177e4
LT
44#include <linux/module.h>
45#include <linux/errno.h>
46#include <linux/kernel.h>
174cd4b1 47#include <linux/sched/signal.h>
1da177e4
LT
48#include <linux/major.h>
49#include <linux/slab.h>
50#include <linux/poll.h>
51#include <linux/fcntl.h>
52#include <linux/init.h>
53#include <linux/skbuff.h>
54#include <linux/netdevice.h>
55#include <linux/etherdevice.h>
56#include <linux/miscdevice.h>
57#include <linux/ethtool.h>
58#include <linux/rtnetlink.h>
50857e2a 59#include <linux/compat.h>
1da177e4
LT
60#include <linux/if.h>
61#include <linux/if_arp.h>
62#include <linux/if_ether.h>
63#include <linux/if_tun.h>
6680ec68 64#include <linux/if_vlan.h>
1da177e4 65#include <linux/crc32.h>
d647a591 66#include <linux/nsproxy.h>
f43798c2 67#include <linux/virtio_net.h>
99405162 68#include <linux/rcupdate.h>
881d966b 69#include <net/net_namespace.h>
79d17604 70#include <net/netns/generic.h>
f019a7a5 71#include <net/rtnetlink.h>
33dccbb0 72#include <net/sock.h>
735fc405 73#include <net/xdp.h>
93e14b6d 74#include <linux/seq_file.h>
e0b46d0e 75#include <linux/uio.h>
1576d986 76#include <linux/skb_array.h>
761876c8
JW
77#include <linux/bpf.h>
78#include <linux/bpf_trace.h>
90e33d45 79#include <linux/mutex.h>
1da177e4 80
7c0f6ba6 81#include <linux/uaccess.h>
f2780d6d 82#include <linux/proc_fs.h>
1da177e4 83
4e24f2dd
CW
84static void tun_default_link_ksettings(struct net_device *dev,
85 struct ethtool_link_ksettings *cmd);
86
14daa021
RR
87/* Uncomment to enable debugging */
88/* #define TUN_DEBUG 1 */
89
1da177e4
LT
90#ifdef TUN_DEBUG
91static int debug;
14daa021 92
6b8a66ee
JP
93#define tun_debug(level, tun, fmt, args...) \
94do { \
95 if (tun->debug) \
96 netdev_printk(level, tun->dev, fmt, ##args); \
97} while (0)
98#define DBG1(level, fmt, args...) \
99do { \
100 if (debug == 2) \
101 printk(level fmt, ##args); \
102} while (0)
14daa021 103#else
6b8a66ee
JP
104#define tun_debug(level, tun, fmt, args...) \
105do { \
106 if (0) \
107 netdev_printk(level, tun->dev, fmt, ##args); \
108} while (0)
109#define DBG1(level, fmt, args...) \
110do { \
111 if (0) \
112 printk(level fmt, ##args); \
113} while (0)
14daa021
RR
114#endif
115
7df13219 116#define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
66ccbc9c 117
031f5e03
MT
118/* TUN device flags */
119
120/* IFF_ATTACH_QUEUE is never stored in device flags,
121 * overload it to mean fasync when stored there.
122 */
123#define TUN_FASYNC IFF_ATTACH_QUEUE
1cf8e410
MT
124/* High bits in flags field are unused. */
125#define TUN_VNET_LE 0x80000000
8b8e658b 126#define TUN_VNET_BE 0x40000000
031f5e03
MT
127
128#define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
90e33d45
PP
129 IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
130
0690899b
MT
131#define GOODCOPY_LEN 128
132
f271b2cc
MK
133#define FLT_EXACT_COUNT 8
134struct tap_filter {
135 unsigned int count; /* Number of addrs. Zero means disabled */
136 u32 mask[2]; /* Mask of the hashed addrs */
137 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
138};
139
baf71c5c
PG
140/* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
141 * to max number of VCPUs in guest. */
142#define MAX_TAP_QUEUES 256
b8732fb7 143#define MAX_TAP_FLOWS 4096
c8d68e6b 144
96442e42
JW
145#define TUN_FLOW_EXPIRE (3 * HZ)
146
608b9977
PA
147struct tun_pcpu_stats {
148 u64 rx_packets;
149 u64 rx_bytes;
150 u64 tx_packets;
151 u64 tx_bytes;
152 struct u64_stats_sync syncp;
153 u32 rx_dropped;
154 u32 tx_dropped;
155 u32 rx_frame_errors;
156};
157
54f968d6 158/* A tun_file connects an open character device to a tuntap netdevice. It
92d4ea6e 159 * also contains all socket related structures (except sock_fprog and tap_filter)
54f968d6
JW
160 * to serve as one transmit queue for tuntap device. The sock_fprog and
161 * tap_filter were kept in tun_struct since they were used for filtering for the
36fe8c09 162 * netdevice not for a specific queue (at least I didn't see the requirement for
54f968d6 163 * this).
6e914fc7
JW
164 *
165 * RCU usage:
36fe8c09 166 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
6e914fc7 167 * other can only be read while rcu_read_lock or rtnl_lock is held.
54f968d6 168 */
631ab46b 169struct tun_file {
54f968d6
JW
170 struct sock sk;
171 struct socket socket;
172 struct socket_wq wq;
6e914fc7 173 struct tun_struct __rcu *tun;
54f968d6
JW
174 struct fasync_struct *fasync;
175 /* only used for fasnyc */
176 unsigned int flags;
fb7589a1
PE
177 union {
178 u16 queue_index;
179 unsigned int ifindex;
180 };
94317099 181 struct napi_struct napi;
aec72f33 182 bool napi_enabled;
af3fb24e 183 bool napi_frags_enabled;
90e33d45 184 struct mutex napi_mutex; /* Protects access to the above napi */
4008e97f
JW
185 struct list_head next;
186 struct tun_struct *detached;
5990a305 187 struct ptr_ring tx_ring;
8bf5c4ee 188 struct xdp_rxq_info xdp_rxq;
631ab46b
EB
189};
190
f9e06c45
JW
191struct tun_page {
192 struct page *page;
193 int count;
194};
195
96442e42
JW
196struct tun_flow_entry {
197 struct hlist_node hash_link;
198 struct rcu_head rcu;
199 struct tun_struct *tun;
200
201 u32 rxhash;
9bc88939 202 u32 rps_rxhash;
96442e42 203 int queue_index;
83b1bc12 204 unsigned long updated ____cacheline_aligned_in_smp;
96442e42
JW
205};
206
207#define TUN_NUM_FLOW_ENTRIES 1024
f13b5468 208#define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
96442e42 209
cd5681d7 210struct tun_prog {
96f84061
JW
211 struct rcu_head rcu;
212 struct bpf_prog *prog;
213};
214
54f968d6 215/* Since the socket were moved to tun_file, to preserve the behavior of persist
36fe8c09 216 * device, socket filter, sndbuf and vnet header size were restore when the
54f968d6
JW
217 * file were attached to a persist device.
218 */
14daa021 219struct tun_struct {
c8d68e6b
JW
220 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
221 unsigned int numqueues;
f271b2cc 222 unsigned int flags;
0625c883
EB
223 kuid_t owner;
224 kgid_t group;
14daa021 225
14daa021 226 struct net_device *dev;
c8f44aff 227 netdev_features_t set_features;
88255375 228#define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
d591a1f3 229 NETIF_F_TSO6)
d9d52b51 230
eaea34b2 231 int align;
d9d52b51 232 int vnet_hdr_sz;
54f968d6
JW
233 int sndbuf;
234 struct tap_filter txflt;
235 struct sock_fprog fprog;
236 /* protected by rtnl lock */
237 bool filter_attached;
14daa021
RR
238#ifdef TUN_DEBUG
239 int debug;
1da177e4 240#endif
96442e42 241 spinlock_t lock;
96442e42
JW
242 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
243 struct timer_list flow_gc_timer;
244 unsigned long ageing_time;
4008e97f
JW
245 unsigned int numdisabled;
246 struct list_head disabled;
5dbbaf2d 247 void *security;
b8732fb7 248 u32 flow_count;
5503fcec 249 u32 rx_batched;
608b9977 250 struct tun_pcpu_stats __percpu *pcpu_stats;
761876c8 251 struct bpf_prog __rcu *xdp_prog;
cd5681d7 252 struct tun_prog __rcu *steering_prog;
aff3d70a 253 struct tun_prog __rcu *filter_prog;
4e24f2dd 254 struct ethtool_link_ksettings link_ksettings;
14daa021 255};
1da177e4 256
aff3d70a
JW
257struct veth {
258 __be16 h_vlan_proto;
259 __be16 h_vlan_TCI;
14daa021 260};
1da177e4 261
1ffcbc85 262bool tun_is_xdp_frame(void *ptr)
fc72d1d5
JW
263{
264 return (unsigned long)ptr & TUN_XDP_FLAG;
265}
1ffcbc85 266EXPORT_SYMBOL(tun_is_xdp_frame);
fc72d1d5
JW
267
268void *tun_xdp_to_ptr(void *ptr)
269{
270 return (void *)((unsigned long)ptr | TUN_XDP_FLAG);
271}
272EXPORT_SYMBOL(tun_xdp_to_ptr);
273
274void *tun_ptr_to_xdp(void *ptr)
275{
276 return (void *)((unsigned long)ptr & ~TUN_XDP_FLAG);
277}
278EXPORT_SYMBOL(tun_ptr_to_xdp);
279
94317099
PP
280static int tun_napi_receive(struct napi_struct *napi, int budget)
281{
282 struct tun_file *tfile = container_of(napi, struct tun_file, napi);
283 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
284 struct sk_buff_head process_queue;
285 struct sk_buff *skb;
286 int received = 0;
287
288 __skb_queue_head_init(&process_queue);
289
290 spin_lock(&queue->lock);
291 skb_queue_splice_tail_init(queue, &process_queue);
292 spin_unlock(&queue->lock);
293
294 while (received < budget && (skb = __skb_dequeue(&process_queue))) {
295 napi_gro_receive(napi, skb);
296 ++received;
297 }
298
299 if (!skb_queue_empty(&process_queue)) {
300 spin_lock(&queue->lock);
301 skb_queue_splice(&process_queue, queue);
302 spin_unlock(&queue->lock);
303 }
304
305 return received;
306}
307
308static int tun_napi_poll(struct napi_struct *napi, int budget)
309{
310 unsigned int received;
311
312 received = tun_napi_receive(napi, budget);
313
314 if (received < budget)
315 napi_complete_done(napi, received);
316
317 return received;
318}
319
320static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
af3fb24e 321 bool napi_en, bool napi_frags)
94317099 322{
aec72f33 323 tfile->napi_enabled = napi_en;
af3fb24e 324 tfile->napi_frags_enabled = napi_en && napi_frags;
94317099
PP
325 if (napi_en) {
326 netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
327 NAPI_POLL_WEIGHT);
328 napi_enable(&tfile->napi);
329 }
330}
331
06e55add 332static void tun_napi_disable(struct tun_file *tfile)
94317099 333{
aec72f33 334 if (tfile->napi_enabled)
94317099
PP
335 napi_disable(&tfile->napi);
336}
337
06e55add 338static void tun_napi_del(struct tun_file *tfile)
94317099 339{
aec72f33 340 if (tfile->napi_enabled)
94317099
PP
341 netif_napi_del(&tfile->napi);
342}
343
af3fb24e 344static bool tun_napi_frags_enabled(const struct tun_file *tfile)
90e33d45 345{
af3fb24e 346 return tfile->napi_frags_enabled;
90e33d45
PP
347}
348
8b8e658b
GK
349#ifdef CONFIG_TUN_VNET_CROSS_LE
350static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
351{
352 return tun->flags & TUN_VNET_BE ? false :
353 virtio_legacy_is_little_endian();
354}
355
356static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
357{
358 int be = !!(tun->flags & TUN_VNET_BE);
359
360 if (put_user(be, argp))
361 return -EFAULT;
362
363 return 0;
364}
365
366static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
367{
368 int be;
369
370 if (get_user(be, argp))
371 return -EFAULT;
372
373 if (be)
374 tun->flags |= TUN_VNET_BE;
375 else
376 tun->flags &= ~TUN_VNET_BE;
377
378 return 0;
379}
380#else
381static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
382{
383 return virtio_legacy_is_little_endian();
384}
385
386static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
387{
388 return -EINVAL;
389}
390
391static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
392{
393 return -EINVAL;
394}
395#endif /* CONFIG_TUN_VNET_CROSS_LE */
396
25bd55bb
GK
397static inline bool tun_is_little_endian(struct tun_struct *tun)
398{
7d824109 399 return tun->flags & TUN_VNET_LE ||
8b8e658b 400 tun_legacy_is_little_endian(tun);
25bd55bb
GK
401}
402
56f0dcc5
MT
403static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
404{
25bd55bb 405 return __virtio16_to_cpu(tun_is_little_endian(tun), val);
56f0dcc5
MT
406}
407
408static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
409{
25bd55bb 410 return __cpu_to_virtio16(tun_is_little_endian(tun), val);
56f0dcc5
MT
411}
412
96442e42
JW
413static inline u32 tun_hashfn(u32 rxhash)
414{
f13b5468 415 return rxhash & TUN_MASK_FLOW_ENTRIES;
96442e42
JW
416}
417
418static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
419{
420 struct tun_flow_entry *e;
96442e42 421
b67bfe0d 422 hlist_for_each_entry_rcu(e, head, hash_link) {
96442e42
JW
423 if (e->rxhash == rxhash)
424 return e;
425 }
426 return NULL;
427}
428
429static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
430 struct hlist_head *head,
431 u32 rxhash, u16 queue_index)
432{
9fdc6bef
ED
433 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
434
96442e42
JW
435 if (e) {
436 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
437 rxhash, queue_index);
438 e->updated = jiffies;
439 e->rxhash = rxhash;
9bc88939 440 e->rps_rxhash = 0;
96442e42
JW
441 e->queue_index = queue_index;
442 e->tun = tun;
443 hlist_add_head_rcu(&e->hash_link, head);
b8732fb7 444 ++tun->flow_count;
96442e42
JW
445 }
446 return e;
447}
448
96442e42
JW
449static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
450{
451 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
452 e->rxhash, e->queue_index);
453 hlist_del_rcu(&e->hash_link);
9fdc6bef 454 kfree_rcu(e, rcu);
b8732fb7 455 --tun->flow_count;
96442e42
JW
456}
457
458static void tun_flow_flush(struct tun_struct *tun)
459{
460 int i;
461
462 spin_lock_bh(&tun->lock);
463 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
464 struct tun_flow_entry *e;
b67bfe0d 465 struct hlist_node *n;
96442e42 466
b67bfe0d 467 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
96442e42
JW
468 tun_flow_delete(tun, e);
469 }
470 spin_unlock_bh(&tun->lock);
471}
472
473static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
474{
475 int i;
476
477 spin_lock_bh(&tun->lock);
478 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
479 struct tun_flow_entry *e;
b67bfe0d 480 struct hlist_node *n;
96442e42 481
b67bfe0d 482 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
96442e42
JW
483 if (e->queue_index == queue_index)
484 tun_flow_delete(tun, e);
485 }
486 }
487 spin_unlock_bh(&tun->lock);
488}
489
e99e88a9 490static void tun_flow_cleanup(struct timer_list *t)
96442e42 491{
e99e88a9 492 struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
96442e42
JW
493 unsigned long delay = tun->ageing_time;
494 unsigned long next_timer = jiffies + delay;
495 unsigned long count = 0;
496 int i;
497
498 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
499
7dbfb4ef 500 spin_lock(&tun->lock);
96442e42
JW
501 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
502 struct tun_flow_entry *e;
b67bfe0d 503 struct hlist_node *n;
96442e42 504
b67bfe0d 505 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
96442e42 506 unsigned long this_timer;
81d98fa4 507
96442e42 508 this_timer = e->updated + delay;
81d98fa4 509 if (time_before_eq(this_timer, jiffies)) {
96442e42 510 tun_flow_delete(tun, e);
81d98fa4
ED
511 continue;
512 }
513 count++;
514 if (time_before(this_timer, next_timer))
96442e42
JW
515 next_timer = this_timer;
516 }
517 }
518
519 if (count)
520 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
7dbfb4ef 521 spin_unlock(&tun->lock);
96442e42
JW
522}
523
49974420 524static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
9e85722d 525 struct tun_file *tfile)
96442e42
JW
526{
527 struct hlist_head *head;
528 struct tun_flow_entry *e;
529 unsigned long delay = tun->ageing_time;
9e85722d 530 u16 queue_index = tfile->queue_index;
96442e42 531
5c327f67 532 head = &tun->flows[tun_hashfn(rxhash)];
96442e42
JW
533
534 rcu_read_lock();
535
96442e42
JW
536 e = tun_flow_find(head, rxhash);
537 if (likely(e)) {
538 /* TODO: keep queueing to old queue until it's empty? */
83b1bc12
LR
539 if (e->queue_index != queue_index)
540 e->queue_index = queue_index;
541 if (e->updated != jiffies)
542 e->updated = jiffies;
9bc88939 543 sock_rps_record_flow_hash(e->rps_rxhash);
96442e42
JW
544 } else {
545 spin_lock_bh(&tun->lock);
b8732fb7
JW
546 if (!tun_flow_find(head, rxhash) &&
547 tun->flow_count < MAX_TAP_FLOWS)
96442e42
JW
548 tun_flow_create(tun, head, rxhash, queue_index);
549
550 if (!timer_pending(&tun->flow_gc_timer))
551 mod_timer(&tun->flow_gc_timer,
552 round_jiffies_up(jiffies + delay));
553 spin_unlock_bh(&tun->lock);
554 }
555
96442e42
JW
556 rcu_read_unlock();
557}
558
9bc88939
TH
559/**
560 * Save the hash received in the stack receive path and update the
561 * flow_hash table accordingly.
562 */
563static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
564{
567e4b79 565 if (unlikely(e->rps_rxhash != hash))
9bc88939 566 e->rps_rxhash = hash;
9bc88939
TH
567}
568
4b035271 569/* We try to identify a flow through its rxhash. The reason that
92d4ea6e 570 * we do not check rxq no. is because some cards(e.g 82599), chooses
c8d68e6b
JW
571 * the rxq based on the txq where the last packet of the flow comes. As
572 * the userspace application move between processors, we may get a
4b035271 573 * different rxq no. here.
c8d68e6b 574 */
96f84061 575static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
c8d68e6b 576{
96442e42 577 struct tun_flow_entry *e;
c8d68e6b
JW
578 u32 txq = 0;
579 u32 numqueues = 0;
580
6aa7de05 581 numqueues = READ_ONCE(tun->numqueues);
c8d68e6b 582
feec084a 583 txq = __skb_get_hash_symmetric(skb);
4b035271
WL
584 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
585 if (e) {
586 tun_flow_save_rps_rxhash(e, txq);
587 txq = e->queue_index;
588 } else {
589 /* use multiply and shift instead of expensive divide */
590 txq = ((u64)txq * numqueues) >> 32;
c8d68e6b
JW
591 }
592
c8d68e6b
JW
593 return txq;
594}
595
96f84061
JW
596static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
597{
cd5681d7 598 struct tun_prog *prog;
f4c325f0 599 u32 numqueues;
96f84061
JW
600 u16 ret = 0;
601
f4c325f0
JW
602 numqueues = READ_ONCE(tun->numqueues);
603 if (!numqueues)
604 return 0;
605
96f84061
JW
606 prog = rcu_dereference(tun->steering_prog);
607 if (prog)
608 ret = bpf_prog_run_clear_cb(prog->prog, skb);
609
f4c325f0 610 return ret % numqueues;
96f84061
JW
611}
612
613static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
4f49dec9
AD
614 struct net_device *sb_dev,
615 select_queue_fallback_t fallback)
96f84061
JW
616{
617 struct tun_struct *tun = netdev_priv(dev);
618 u16 ret;
619
620 rcu_read_lock();
621 if (rcu_dereference(tun->steering_prog))
622 ret = tun_ebpf_select_queue(tun, skb);
623 else
624 ret = tun_automq_select_queue(tun, skb);
625 rcu_read_unlock();
626
627 return ret;
628}
629
cde8b15f
JW
630static inline bool tun_not_capable(struct tun_struct *tun)
631{
632 const struct cred *cred = current_cred();
c260b772 633 struct net *net = dev_net(tun->dev);
cde8b15f
JW
634
635 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
636 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
c260b772 637 !ns_capable(net->user_ns, CAP_NET_ADMIN);
cde8b15f
JW
638}
639
c8d68e6b
JW
640static void tun_set_real_num_queues(struct tun_struct *tun)
641{
642 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
643 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
644}
645
4008e97f
JW
646static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
647{
648 tfile->detached = tun;
649 list_add_tail(&tfile->next, &tun->disabled);
650 ++tun->numdisabled;
651}
652
d32649d1 653static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
4008e97f
JW
654{
655 struct tun_struct *tun = tfile->detached;
656
657 tfile->detached = NULL;
658 list_del_init(&tfile->next);
659 --tun->numdisabled;
660 return tun;
661}
662
3a403076 663void tun_ptr_free(void *ptr)
fc72d1d5
JW
664{
665 if (!ptr)
666 return;
1ffcbc85
JDB
667 if (tun_is_xdp_frame(ptr)) {
668 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
fc72d1d5 669
03993094 670 xdp_return_frame(xdpf);
fc72d1d5
JW
671 } else {
672 __skb_array_destroy_skb(ptr);
673 }
674}
3a403076 675EXPORT_SYMBOL_GPL(tun_ptr_free);
fc72d1d5 676
4bfb0513
JW
677static void tun_queue_purge(struct tun_file *tfile)
678{
fc72d1d5 679 void *ptr;
1576d986 680
fc72d1d5
JW
681 while ((ptr = ptr_ring_consume(&tfile->tx_ring)) != NULL)
682 tun_ptr_free(ptr);
1576d986 683
5503fcec 684 skb_queue_purge(&tfile->sk.sk_write_queue);
4bfb0513
JW
685 skb_queue_purge(&tfile->sk.sk_error_queue);
686}
687
c8d68e6b
JW
688static void __tun_detach(struct tun_file *tfile, bool clean)
689{
690 struct tun_file *ntfile;
691 struct tun_struct *tun;
c8d68e6b 692
b8deabd3
JW
693 tun = rtnl_dereference(tfile->tun);
694
94317099 695 if (tun && clean) {
06e55add
ED
696 tun_napi_disable(tfile);
697 tun_napi_del(tfile);
94317099
PP
698 }
699
9e85722d 700 if (tun && !tfile->detached) {
c8d68e6b
JW
701 u16 index = tfile->queue_index;
702 BUG_ON(index >= tun->numqueues);
c8d68e6b
JW
703
704 rcu_assign_pointer(tun->tfiles[index],
705 tun->tfiles[tun->numqueues - 1]);
b8deabd3 706 ntfile = rtnl_dereference(tun->tfiles[index]);
c8d68e6b 707 ntfile->queue_index = index;
3fb3ee28
JW
708 rcu_assign_pointer(tun->tfiles[tun->numqueues - 1],
709 NULL);
c8d68e6b
JW
710
711 --tun->numqueues;
9e85722d 712 if (clean) {
c956674b 713 RCU_INIT_POINTER(tfile->tun, NULL);
4008e97f 714 sock_put(&tfile->sk);
9e85722d 715 } else
4008e97f 716 tun_disable_queue(tun, tfile);
c8d68e6b
JW
717
718 synchronize_net();
96442e42 719 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
c8d68e6b 720 /* Drop read queue */
4bfb0513 721 tun_queue_purge(tfile);
c8d68e6b 722 tun_set_real_num_queues(tun);
dd38bd85 723 } else if (tfile->detached && clean) {
4008e97f 724 tun = tun_enable_queue(tfile);
dd38bd85
JW
725 sock_put(&tfile->sk);
726 }
c8d68e6b
JW
727
728 if (clean) {
af668b3c
MT
729 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
730 netif_carrier_off(tun->dev);
731
40630b82 732 if (!(tun->flags & IFF_PERSIST) &&
af668b3c 733 tun->dev->reg_state == NETREG_REGISTERED)
4008e97f 734 unregister_netdevice(tun->dev);
af668b3c 735 }
b196d88a
JW
736 if (tun)
737 xdp_rxq_info_unreg(&tfile->xdp_rxq);
7063efd3 738 ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
140e807d 739 sock_put(&tfile->sk);
c8d68e6b
JW
740 }
741}
742
743static void tun_detach(struct tun_file *tfile, bool clean)
744{
83c1f36f
SD
745 struct tun_struct *tun;
746 struct net_device *dev;
747
c8d68e6b 748 rtnl_lock();
83c1f36f
SD
749 tun = rtnl_dereference(tfile->tun);
750 dev = tun ? tun->dev : NULL;
c8d68e6b 751 __tun_detach(tfile, clean);
83c1f36f
SD
752 if (dev)
753 netdev_state_change(dev);
c8d68e6b
JW
754 rtnl_unlock();
755}
756
757static void tun_detach_all(struct net_device *dev)
758{
759 struct tun_struct *tun = netdev_priv(dev);
4008e97f 760 struct tun_file *tfile, *tmp;
c8d68e6b
JW
761 int i, n = tun->numqueues;
762
763 for (i = 0; i < n; i++) {
b8deabd3 764 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b 765 BUG_ON(!tfile);
06e55add 766 tun_napi_disable(tfile);
addf8fc4 767 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
9e641bdc 768 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
c956674b 769 RCU_INIT_POINTER(tfile->tun, NULL);
c8d68e6b
JW
770 --tun->numqueues;
771 }
9e85722d 772 list_for_each_entry(tfile, &tun->disabled, next) {
addf8fc4 773 tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
9e641bdc 774 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
c956674b 775 RCU_INIT_POINTER(tfile->tun, NULL);
9e85722d 776 }
c8d68e6b
JW
777 BUG_ON(tun->numqueues != 0);
778
779 synchronize_net();
780 for (i = 0; i < n; i++) {
b8deabd3 781 tfile = rtnl_dereference(tun->tfiles[i]);
06e55add 782 tun_napi_del(tfile);
c8d68e6b 783 /* Drop read queue */
4bfb0513 784 tun_queue_purge(tfile);
b196d88a 785 xdp_rxq_info_unreg(&tfile->xdp_rxq);
c8d68e6b
JW
786 sock_put(&tfile->sk);
787 }
4008e97f
JW
788 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
789 tun_enable_queue(tfile);
4bfb0513 790 tun_queue_purge(tfile);
b196d88a 791 xdp_rxq_info_unreg(&tfile->xdp_rxq);
4008e97f
JW
792 sock_put(&tfile->sk);
793 }
794 BUG_ON(tun->numdisabled != 0);
dd38bd85 795
40630b82 796 if (tun->flags & IFF_PERSIST)
dd38bd85 797 module_put(THIS_MODULE);
c8d68e6b
JW
798}
799
94317099 800static int tun_attach(struct tun_struct *tun, struct file *file,
af3fb24e 801 bool skip_filter, bool napi, bool napi_frags)
a7385ba2 802{
631ab46b 803 struct tun_file *tfile = file->private_data;
1576d986 804 struct net_device *dev = tun->dev;
38231b7a 805 int err;
a7385ba2 806
5dbbaf2d
PM
807 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
808 if (err < 0)
809 goto out;
810
38231b7a 811 err = -EINVAL;
9e85722d 812 if (rtnl_dereference(tfile->tun) && !tfile->detached)
38231b7a
EB
813 goto out;
814
815 err = -EBUSY;
40630b82 816 if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
c8d68e6b
JW
817 goto out;
818
819 err = -E2BIG;
4008e97f
JW
820 if (!tfile->detached &&
821 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
38231b7a
EB
822 goto out;
823
824 err = 0;
54f968d6 825
92d4ea6e 826 /* Re-attach the filter to persist device */
849c9b6f 827 if (!skip_filter && (tun->filter_attached == true)) {
8ced425e
HFS
828 lock_sock(tfile->socket.sk);
829 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
830 release_sock(tfile->socket.sk);
54f968d6
JW
831 if (!err)
832 goto out;
833 }
1576d986
JW
834
835 if (!tfile->detached &&
b196d88a
JW
836 ptr_ring_resize(&tfile->tx_ring, dev->tx_queue_len,
837 GFP_KERNEL, tun_ptr_free)) {
1576d986
JW
838 err = -ENOMEM;
839 goto out;
840 }
841
c8d68e6b 842 tfile->queue_index = tun->numqueues;
addf8fc4 843 tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
8bf5c4ee
JDB
844
845 if (tfile->detached) {
846 /* Re-attach detached tfile, updating XDP queue_index */
847 WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
848
849 if (tfile->xdp_rxq.queue_index != tfile->queue_index)
850 tfile->xdp_rxq.queue_index = tfile->queue_index;
851 } else {
852 /* Setup XDP RX-queue info, for new tfile getting attached */
853 err = xdp_rxq_info_reg(&tfile->xdp_rxq,
854 tun->dev, tfile->queue_index);
855 if (err < 0)
856 goto out;
8d5d8852
JDB
857 err = xdp_rxq_info_reg_mem_model(&tfile->xdp_rxq,
858 MEM_TYPE_PAGE_SHARED, NULL);
859 if (err < 0) {
860 xdp_rxq_info_unreg(&tfile->xdp_rxq);
861 goto out;
862 }
8bf5c4ee
JDB
863 err = 0;
864 }
865
94317099 866 if (tfile->detached) {
4008e97f 867 tun_enable_queue(tfile);
94317099 868 } else {
4008e97f 869 sock_hold(&tfile->sk);
af3fb24e 870 tun_napi_init(tun, tfile, napi, napi_frags);
94317099 871 }
4008e97f 872
e4a2a304
JW
873 if (rtnl_dereference(tun->xdp_prog))
874 sock_set_flag(&tfile->sk, SOCK_XDP);
875
c8d68e6b
JW
876 /* device is allowed to go away first, so no need to hold extra
877 * refcnt.
878 */
879
0b7959b6
SF
880 /* Publish tfile->tun and tun->tfiles only after we've fully
881 * initialized tfile; otherwise we risk using half-initialized
882 * object.
883 */
884 rcu_assign_pointer(tfile->tun, tun);
885 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
886 tun->numqueues++;
3a03cb84 887 tun_set_real_num_queues(tun);
c8d68e6b
JW
888out:
889 return err;
631ab46b
EB
890}
891
9484dc74 892static struct tun_struct *tun_get(struct tun_file *tfile)
631ab46b 893{
6e914fc7 894 struct tun_struct *tun;
c70f1829 895
6e914fc7
JW
896 rcu_read_lock();
897 tun = rcu_dereference(tfile->tun);
898 if (tun)
899 dev_hold(tun->dev);
900 rcu_read_unlock();
c70f1829
EB
901
902 return tun;
631ab46b
EB
903}
904
631ab46b
EB
905static void tun_put(struct tun_struct *tun)
906{
6e914fc7 907 dev_put(tun->dev);
631ab46b
EB
908}
909
6b8a66ee 910/* TAP filtering */
f271b2cc
MK
911static void addr_hash_set(u32 *mask, const u8 *addr)
912{
913 int n = ether_crc(ETH_ALEN, addr) >> 26;
914 mask[n >> 5] |= (1 << (n & 31));
915}
916
917static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
918{
919 int n = ether_crc(ETH_ALEN, addr) >> 26;
920 return mask[n >> 5] & (1 << (n & 31));
921}
922
923static int update_filter(struct tap_filter *filter, void __user *arg)
924{
925 struct { u8 u[ETH_ALEN]; } *addr;
926 struct tun_filter uf;
927 int err, alen, n, nexact;
928
929 if (copy_from_user(&uf, arg, sizeof(uf)))
930 return -EFAULT;
931
932 if (!uf.count) {
933 /* Disabled */
934 filter->count = 0;
935 return 0;
936 }
937
938 alen = ETH_ALEN * uf.count;
28e8190d
ME
939 addr = memdup_user(arg + sizeof(uf), alen);
940 if (IS_ERR(addr))
941 return PTR_ERR(addr);
f271b2cc
MK
942
943 /* The filter is updated without holding any locks. Which is
944 * perfectly safe. We disable it first and in the worst
945 * case we'll accept a few undesired packets. */
946 filter->count = 0;
947 wmb();
948
949 /* Use first set of addresses as an exact filter */
950 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
951 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
952
953 nexact = n;
954
cfbf84fc
AW
955 /* Remaining multicast addresses are hashed,
956 * unicast will leave the filter disabled. */
f271b2cc 957 memset(filter->mask, 0, sizeof(filter->mask));
cfbf84fc
AW
958 for (; n < uf.count; n++) {
959 if (!is_multicast_ether_addr(addr[n].u)) {
960 err = 0; /* no filter */
3b8d2a69 961 goto free_addr;
cfbf84fc 962 }
f271b2cc 963 addr_hash_set(filter->mask, addr[n].u);
cfbf84fc 964 }
f271b2cc
MK
965
966 /* For ALLMULTI just set the mask to all ones.
967 * This overrides the mask populated above. */
968 if ((uf.flags & TUN_FLT_ALLMULTI))
969 memset(filter->mask, ~0, sizeof(filter->mask));
970
971 /* Now enable the filter */
972 wmb();
973 filter->count = nexact;
974
975 /* Return the number of exact filters */
976 err = nexact;
3b8d2a69 977free_addr:
f271b2cc
MK
978 kfree(addr);
979 return err;
980}
981
982/* Returns: 0 - drop, !=0 - accept */
983static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
984{
985 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
986 * at this point. */
987 struct ethhdr *eh = (struct ethhdr *) skb->data;
988 int i;
989
990 /* Exact match */
991 for (i = 0; i < filter->count; i++)
2e42e474 992 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
f271b2cc
MK
993 return 1;
994
995 /* Inexact match (multicast only) */
996 if (is_multicast_ether_addr(eh->h_dest))
997 return addr_hash_test(filter->mask, eh->h_dest);
998
999 return 0;
1000}
1001
1002/*
1003 * Checks whether the packet is accepted or not.
1004 * Returns: 0 - drop, !=0 - accept
1005 */
1006static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
1007{
1008 if (!filter->count)
1009 return 1;
1010
1011 return run_filter(filter, skb);
1012}
1013
1da177e4
LT
1014/* Network device part of the driver */
1015
7282d491 1016static const struct ethtool_ops tun_ethtool_ops;
1da177e4 1017
c70f1829
EB
1018/* Net device detach from fd. */
1019static void tun_net_uninit(struct net_device *dev)
1020{
c8d68e6b 1021 tun_detach_all(dev);
c70f1829
EB
1022}
1023
1da177e4
LT
1024/* Net device open. */
1025static int tun_net_open(struct net_device *dev)
1026{
b20e2d54
HFS
1027 struct tun_struct *tun = netdev_priv(dev);
1028 int i;
1029
c8d68e6b 1030 netif_tx_start_all_queues(dev);
b20e2d54
HFS
1031
1032 for (i = 0; i < tun->numqueues; i++) {
1033 struct tun_file *tfile;
1034
1035 tfile = rtnl_dereference(tun->tfiles[i]);
1036 tfile->socket.sk->sk_write_space(tfile->socket.sk);
1037 }
1038
1da177e4
LT
1039 return 0;
1040}
1041
1042/* Net device close. */
1043static int tun_net_close(struct net_device *dev)
1044{
c8d68e6b 1045 netif_tx_stop_all_queues(dev);
1da177e4
LT
1046 return 0;
1047}
1048
1049/* Net device start xmit */
96f84061 1050static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
1da177e4 1051{
3df97ba8 1052#ifdef CONFIG_RPS
96f84061 1053 if (tun->numqueues == 1 && static_key_false(&rps_needed)) {
9bc88939
TH
1054 /* Select queue was not called for the skbuff, so we extract the
1055 * RPS hash and save it into the flow_table here.
1056 */
4b035271 1057 struct tun_flow_entry *e;
9bc88939
TH
1058 __u32 rxhash;
1059
feec084a 1060 rxhash = __skb_get_hash_symmetric(skb);
4b035271
WL
1061 e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash);
1062 if (e)
1063 tun_flow_save_rps_rxhash(e, rxhash);
9bc88939 1064 }
3df97ba8 1065#endif
96f84061
JW
1066}
1067
aff3d70a
JW
1068static unsigned int run_ebpf_filter(struct tun_struct *tun,
1069 struct sk_buff *skb,
1070 int len)
1071{
1072 struct tun_prog *prog = rcu_dereference(tun->filter_prog);
1073
1074 if (prog)
1075 len = bpf_prog_run_clear_cb(prog->prog, skb);
1076
1077 return len;
1078}
1079
96f84061
JW
1080/* Net device start xmit */
1081static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
1082{
1083 struct tun_struct *tun = netdev_priv(dev);
1084 int txq = skb->queue_mapping;
1085 struct tun_file *tfile;
aff3d70a 1086 int len = skb->len;
96f84061
JW
1087
1088 rcu_read_lock();
1089 tfile = rcu_dereference(tun->tfiles[txq]);
96f84061
JW
1090
1091 /* Drop packet if interface is not attached */
3fb3ee28 1092 if (!tfile)
96f84061
JW
1093 goto drop;
1094
1095 if (!rcu_dereference(tun->steering_prog))
1096 tun_automq_xmit(tun, skb);
9bc88939 1097
6e914fc7
JW
1098 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
1099
c8d68e6b
JW
1100 BUG_ON(!tfile);
1101
f271b2cc
MK
1102 /* Drop if the filter does not like it.
1103 * This is a noop if the filter is disabled.
1104 * Filter can be enabled only for the TAP devices. */
1105 if (!check_filter(&tun->txflt, skb))
1106 goto drop;
1107
54f968d6
JW
1108 if (tfile->socket.sk->sk_filter &&
1109 sk_filter(tfile->socket.sk, skb))
99405162
MT
1110 goto drop;
1111
aff3d70a 1112 len = run_ebpf_filter(tun, skb, len);
81c89507 1113 if (len == 0 || pskb_trim(skb, len))
aff3d70a
JW
1114 goto drop;
1115
1f8b977a 1116 if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
7bf66305
JW
1117 goto drop;
1118
7b996243 1119 skb_tx_timestamp(skb);
eda29772 1120
0110d6f2 1121 /* Orphan the skb - required as we might hang on to it
7bf66305
JW
1122 * for indefinite time.
1123 */
0110d6f2
MT
1124 skb_orphan(skb);
1125
f8af75f3
ED
1126 nf_reset(skb);
1127
5990a305 1128 if (ptr_ring_produce(&tfile->tx_ring, skb))
1576d986 1129 goto drop;
1da177e4
LT
1130
1131 /* Notify and wake up reader process */
54f968d6
JW
1132 if (tfile->flags & TUN_FASYNC)
1133 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
9e641bdc 1134 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
6e914fc7
JW
1135
1136 rcu_read_unlock();
6ed10654 1137 return NETDEV_TX_OK;
1da177e4
LT
1138
1139drop:
608b9977 1140 this_cpu_inc(tun->pcpu_stats->tx_dropped);
149d36f7 1141 skb_tx_error(skb);
1da177e4 1142 kfree_skb(skb);
6e914fc7 1143 rcu_read_unlock();
baeababb 1144 return NET_XMIT_DROP;
1da177e4
LT
1145}
1146
f271b2cc 1147static void tun_net_mclist(struct net_device *dev)
1da177e4 1148{
f271b2cc
MK
1149 /*
1150 * This callback is supposed to deal with mc filter in
1151 * _rx_ path and has nothing to do with the _tx_ path.
1152 * In rx path we always accept everything userspace gives us.
1153 */
1da177e4
LT
1154}
1155
c8f44aff
MM
1156static netdev_features_t tun_net_fix_features(struct net_device *dev,
1157 netdev_features_t features)
88255375
MM
1158{
1159 struct tun_struct *tun = netdev_priv(dev);
1160
1161 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
1162}
eaea34b2
PA
1163
1164static void tun_set_headroom(struct net_device *dev, int new_hr)
1165{
1166 struct tun_struct *tun = netdev_priv(dev);
1167
1168 if (new_hr < NET_SKB_PAD)
1169 new_hr = NET_SKB_PAD;
1170
1171 tun->align = new_hr;
1172}
1173
bc1f4470 1174static void
608b9977
PA
1175tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
1176{
1177 u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
1178 struct tun_struct *tun = netdev_priv(dev);
1179 struct tun_pcpu_stats *p;
1180 int i;
1181
1182 for_each_possible_cpu(i) {
1183 u64 rxpackets, rxbytes, txpackets, txbytes;
1184 unsigned int start;
1185
1186 p = per_cpu_ptr(tun->pcpu_stats, i);
1187 do {
1188 start = u64_stats_fetch_begin(&p->syncp);
1189 rxpackets = p->rx_packets;
1190 rxbytes = p->rx_bytes;
1191 txpackets = p->tx_packets;
1192 txbytes = p->tx_bytes;
1193 } while (u64_stats_fetch_retry(&p->syncp, start));
1194
1195 stats->rx_packets += rxpackets;
1196 stats->rx_bytes += rxbytes;
1197 stats->tx_packets += txpackets;
1198 stats->tx_bytes += txbytes;
1199
1200 /* u32 counters */
1201 rx_dropped += p->rx_dropped;
1202 rx_frame_errors += p->rx_frame_errors;
1203 tx_dropped += p->tx_dropped;
1204 }
1205 stats->rx_dropped = rx_dropped;
1206 stats->rx_frame_errors = rx_frame_errors;
1207 stats->tx_dropped = tx_dropped;
608b9977
PA
1208}
1209
761876c8
JW
1210static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1211 struct netlink_ext_ack *extack)
1212{
1213 struct tun_struct *tun = netdev_priv(dev);
e4a2a304 1214 struct tun_file *tfile;
761876c8 1215 struct bpf_prog *old_prog;
e4a2a304 1216 int i;
761876c8
JW
1217
1218 old_prog = rtnl_dereference(tun->xdp_prog);
1219 rcu_assign_pointer(tun->xdp_prog, prog);
1220 if (old_prog)
1221 bpf_prog_put(old_prog);
1222
e4a2a304
JW
1223 for (i = 0; i < tun->numqueues; i++) {
1224 tfile = rtnl_dereference(tun->tfiles[i]);
1225 if (prog)
1226 sock_set_flag(&tfile->sk, SOCK_XDP);
1227 else
1228 sock_reset_flag(&tfile->sk, SOCK_XDP);
1229 }
1230 list_for_each_entry(tfile, &tun->disabled, next) {
1231 if (prog)
1232 sock_set_flag(&tfile->sk, SOCK_XDP);
1233 else
1234 sock_reset_flag(&tfile->sk, SOCK_XDP);
1235 }
1236
761876c8
JW
1237 return 0;
1238}
1239
1240static u32 tun_xdp_query(struct net_device *dev)
1241{
1242 struct tun_struct *tun = netdev_priv(dev);
1243 const struct bpf_prog *xdp_prog;
1244
1245 xdp_prog = rtnl_dereference(tun->xdp_prog);
1246 if (xdp_prog)
1247 return xdp_prog->aux->id;
1248
1249 return 0;
1250}
1251
f4e63525 1252static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
761876c8
JW
1253{
1254 switch (xdp->command) {
1255 case XDP_SETUP_PROG:
1256 return tun_xdp_set(dev, xdp->prog, xdp->extack);
1257 case XDP_QUERY_PROG:
1258 xdp->prog_id = tun_xdp_query(dev);
761876c8
JW
1259 return 0;
1260 default:
1261 return -EINVAL;
1262 }
1263}
1264
26d31925
ND
1265static int tun_net_change_carrier(struct net_device *dev, bool new_carrier)
1266{
1267 if (new_carrier) {
1268 struct tun_struct *tun = netdev_priv(dev);
1269
1270 if (!tun->numqueues)
1271 return -EPERM;
1272
1273 netif_carrier_on(dev);
1274 } else {
1275 netif_carrier_off(dev);
1276 }
1277 return 0;
1278}
1279
758e43b7 1280static const struct net_device_ops tun_netdev_ops = {
c70f1829 1281 .ndo_uninit = tun_net_uninit,
758e43b7
SH
1282 .ndo_open = tun_net_open,
1283 .ndo_stop = tun_net_close,
00829823 1284 .ndo_start_xmit = tun_net_xmit,
88255375 1285 .ndo_fix_features = tun_net_fix_features,
c8d68e6b 1286 .ndo_select_queue = tun_select_queue,
eaea34b2 1287 .ndo_set_rx_headroom = tun_set_headroom,
608b9977 1288 .ndo_get_stats64 = tun_net_get_stats64,
26d31925 1289 .ndo_change_carrier = tun_net_change_carrier,
758e43b7
SH
1290};
1291
0c9d917b
JDB
1292static void __tun_xdp_flush_tfile(struct tun_file *tfile)
1293{
1294 /* Notify and wake up reader process */
1295 if (tfile->flags & TUN_FASYNC)
1296 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
1297 tfile->socket.sk->sk_data_ready(tfile->socket.sk);
1298}
1299
42b33468
JDB
1300static int tun_xdp_xmit(struct net_device *dev, int n,
1301 struct xdp_frame **frames, u32 flags)
fc72d1d5
JW
1302{
1303 struct tun_struct *tun = netdev_priv(dev);
fc72d1d5
JW
1304 struct tun_file *tfile;
1305 u32 numqueues;
735fc405
JDB
1306 int drops = 0;
1307 int cnt = n;
1308 int i;
fc72d1d5 1309
0c9d917b 1310 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
42b33468
JDB
1311 return -EINVAL;
1312
fc72d1d5
JW
1313 rcu_read_lock();
1314
3fb3ee28 1315resample:
fc72d1d5
JW
1316 numqueues = READ_ONCE(tun->numqueues);
1317 if (!numqueues) {
735fc405
JDB
1318 rcu_read_unlock();
1319 return -ENXIO; /* Caller will free/return all frames */
fc72d1d5
JW
1320 }
1321
1322 tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
1323 numqueues]);
3fb3ee28
JW
1324 if (unlikely(!tfile))
1325 goto resample;
735fc405
JDB
1326
1327 spin_lock(&tfile->tx_ring.producer_lock);
1328 for (i = 0; i < n; i++) {
1329 struct xdp_frame *xdp = frames[i];
1330 /* Encode the XDP flag into lowest bit for consumer to differ
1331 * XDP buffer from sk_buff.
1332 */
1333 void *frame = tun_xdp_to_ptr(xdp);
1334
1335 if (__ptr_ring_produce(&tfile->tx_ring, frame)) {
1336 this_cpu_inc(tun->pcpu_stats->tx_dropped);
1337 xdp_return_frame_rx_napi(xdp);
1338 drops++;
1339 }
fc72d1d5 1340 }
735fc405 1341 spin_unlock(&tfile->tx_ring.producer_lock);
fc72d1d5 1342
0c9d917b
JDB
1343 if (flags & XDP_XMIT_FLUSH)
1344 __tun_xdp_flush_tfile(tfile);
1345
fc72d1d5 1346 rcu_read_unlock();
735fc405 1347 return cnt - drops;
fc72d1d5
JW
1348}
1349
44fa2dbd
JDB
1350static int tun_xdp_tx(struct net_device *dev, struct xdp_buff *xdp)
1351{
1352 struct xdp_frame *frame = convert_to_xdp_frame(xdp);
1353
1354 if (unlikely(!frame))
1355 return -EOVERFLOW;
1356
42421a56 1357 return tun_xdp_xmit(dev, 1, &frame, XDP_XMIT_FLUSH);
fc72d1d5
JW
1358}
1359
758e43b7 1360static const struct net_device_ops tap_netdev_ops = {
c70f1829 1361 .ndo_uninit = tun_net_uninit,
758e43b7
SH
1362 .ndo_open = tun_net_open,
1363 .ndo_stop = tun_net_close,
00829823 1364 .ndo_start_xmit = tun_net_xmit,
88255375 1365 .ndo_fix_features = tun_net_fix_features,
afc4b13d 1366 .ndo_set_rx_mode = tun_net_mclist,
758e43b7
SH
1367 .ndo_set_mac_address = eth_mac_addr,
1368 .ndo_validate_addr = eth_validate_addr,
c8d68e6b 1369 .ndo_select_queue = tun_select_queue,
5e52796a 1370 .ndo_features_check = passthru_features_check,
eaea34b2 1371 .ndo_set_rx_headroom = tun_set_headroom,
608b9977 1372 .ndo_get_stats64 = tun_net_get_stats64,
f4e63525 1373 .ndo_bpf = tun_xdp,
fc72d1d5 1374 .ndo_xdp_xmit = tun_xdp_xmit,
26d31925 1375 .ndo_change_carrier = tun_net_change_carrier,
758e43b7
SH
1376};
1377
944a1376 1378static void tun_flow_init(struct tun_struct *tun)
96442e42
JW
1379{
1380 int i;
1381
96442e42
JW
1382 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
1383 INIT_HLIST_HEAD(&tun->flows[i]);
1384
1385 tun->ageing_time = TUN_FLOW_EXPIRE;
e99e88a9
KC
1386 timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
1387 mod_timer(&tun->flow_gc_timer,
1388 round_jiffies_up(jiffies + tun->ageing_time));
96442e42
JW
1389}
1390
1391static void tun_flow_uninit(struct tun_struct *tun)
1392{
1393 del_timer_sync(&tun->flow_gc_timer);
1394 tun_flow_flush(tun);
96442e42
JW
1395}
1396
91572088
JW
1397#define MIN_MTU 68
1398#define MAX_MTU 65535
1399
1da177e4
LT
1400/* Initialize net device. */
1401static void tun_net_init(struct net_device *dev)
1402{
1403 struct tun_struct *tun = netdev_priv(dev);
6aa20a22 1404
1da177e4 1405 switch (tun->flags & TUN_TYPE_MASK) {
40630b82 1406 case IFF_TUN:
758e43b7
SH
1407 dev->netdev_ops = &tun_netdev_ops;
1408
1da177e4
LT
1409 /* Point-to-Point TUN Device */
1410 dev->hard_header_len = 0;
1411 dev->addr_len = 0;
1412 dev->mtu = 1500;
1413
1414 /* Zero header length */
6aa20a22 1415 dev->type = ARPHRD_NONE;
1da177e4 1416 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
1da177e4
LT
1417 break;
1418
40630b82 1419 case IFF_TAP:
7a0a9608 1420 dev->netdev_ops = &tap_netdev_ops;
1da177e4 1421 /* Ethernet TAP Device */
1da177e4 1422 ether_setup(dev);
550fd08c 1423 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
a676847b 1424 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
36226a8d 1425
f2cedb63 1426 eth_hw_addr_random(dev);
36226a8d 1427
1da177e4
LT
1428 break;
1429 }
91572088
JW
1430
1431 dev->min_mtu = MIN_MTU;
1432 dev->max_mtu = MAX_MTU - dev->hard_header_len;
1da177e4
LT
1433}
1434
2f3ab622
JW
1435static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
1436{
1437 struct sock *sk = tfile->socket.sk;
1438
1439 return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
1440}
1441
1da177e4
LT
1442/* Character device part */
1443
1444/* Poll */
afc9a42b 1445static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
6aa20a22 1446{
b2430de3 1447 struct tun_file *tfile = file->private_data;
9484dc74 1448 struct tun_struct *tun = tun_get(tfile);
3c8a9c63 1449 struct sock *sk;
afc9a42b 1450 __poll_t mask = 0;
1da177e4
LT
1451
1452 if (!tun)
a9a08845 1453 return EPOLLERR;
1da177e4 1454
54f968d6 1455 sk = tfile->socket.sk;
3c8a9c63 1456
6b8a66ee 1457 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
1da177e4 1458
9e641bdc 1459 poll_wait(file, sk_sleep(sk), wait);
6aa20a22 1460
5990a305 1461 if (!ptr_ring_empty(&tfile->tx_ring))
a9a08845 1462 mask |= EPOLLIN | EPOLLRDNORM;
1da177e4 1463
2f3ab622
JW
1464 /* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
1465 * guarantee EPOLLOUT to be raised by either here or
1466 * tun_sock_write_space(). Then process could get notification
1467 * after it writes to a down device and meets -EIO.
1468 */
1469 if (tun_sock_writeable(tun, tfile) ||
1470 (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
1471 tun_sock_writeable(tun, tfile)))
a9a08845 1472 mask |= EPOLLOUT | EPOLLWRNORM;
33dccbb0 1473
c70f1829 1474 if (tun->dev->reg_state != NETREG_REGISTERED)
a9a08845 1475 mask = EPOLLERR;
c70f1829 1476
631ab46b 1477 tun_put(tun);
1da177e4
LT
1478 return mask;
1479}
1480
90e33d45
PP
1481static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
1482 size_t len,
1483 const struct iov_iter *it)
1484{
1485 struct sk_buff *skb;
1486 size_t linear;
1487 int err;
1488 int i;
1489
1490 if (it->nr_segs > MAX_SKB_FRAGS + 1)
1491 return ERR_PTR(-ENOMEM);
1492
1493 local_bh_disable();
1494 skb = napi_get_frags(&tfile->napi);
1495 local_bh_enable();
1496 if (!skb)
1497 return ERR_PTR(-ENOMEM);
1498
1499 linear = iov_iter_single_seg_count(it);
1500 err = __skb_grow(skb, linear);
1501 if (err)
1502 goto free;
1503
1504 skb->len = len;
1505 skb->data_len = len - linear;
1506 skb->truesize += skb->data_len;
1507
1508 for (i = 1; i < it->nr_segs; i++) {
1509 size_t fragsz = it->iov[i].iov_len;
aa6daaca
ED
1510 struct page *page;
1511 void *frag;
90e33d45
PP
1512
1513 if (fragsz == 0 || fragsz > PAGE_SIZE) {
1514 err = -EINVAL;
1515 goto free;
1516 }
aa6daaca
ED
1517 frag = netdev_alloc_frag(fragsz);
1518 if (!frag) {
90e33d45
PP
1519 err = -ENOMEM;
1520 goto free;
1521 }
aa6daaca
ED
1522 page = virt_to_head_page(frag);
1523 skb_fill_page_desc(skb, i - 1, page,
1524 frag - page_address(page), fragsz);
90e33d45
PP
1525 }
1526
1527 return skb;
1528free:
1529 /* frees skb and all frags allocated with napi_alloc_frag() */
1530 napi_free_frags(&tfile->napi);
1531 return ERR_PTR(err);
1532}
1533
f42157cb
RR
1534/* prepad is the amount to reserve at front. len is length after that.
1535 * linear is a hint as to how much to copy (usually headers). */
54f968d6 1536static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
6f7c156c 1537 size_t prepad, size_t len,
1538 size_t linear, int noblock)
f42157cb 1539{
54f968d6 1540 struct sock *sk = tfile->socket.sk;
f42157cb 1541 struct sk_buff *skb;
33dccbb0 1542 int err;
f42157cb
RR
1543
1544 /* Under a page? Don't bother with paged skb. */
0eca93bc 1545 if (prepad + len < PAGE_SIZE || !linear)
33dccbb0 1546 linear = len;
f42157cb 1547
33dccbb0 1548 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
28d64271 1549 &err, 0);
f42157cb 1550 if (!skb)
33dccbb0 1551 return ERR_PTR(err);
f42157cb
RR
1552
1553 skb_reserve(skb, prepad);
1554 skb_put(skb, linear);
33dccbb0
HX
1555 skb->data_len = len - linear;
1556 skb->len += len - linear;
f42157cb
RR
1557
1558 return skb;
1559}
1560
5503fcec
JW
1561static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
1562 struct sk_buff *skb, int more)
1563{
1564 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1565 struct sk_buff_head process_queue;
1566 u32 rx_batched = tun->rx_batched;
1567 bool rcv = false;
1568
1569 if (!rx_batched || (!more && skb_queue_empty(queue))) {
1570 local_bh_disable();
8ebebcba 1571 skb_record_rx_queue(skb, tfile->queue_index);
5503fcec
JW
1572 netif_receive_skb(skb);
1573 local_bh_enable();
1574 return;
1575 }
1576
1577 spin_lock(&queue->lock);
1578 if (!more || skb_queue_len(queue) == rx_batched) {
1579 __skb_queue_head_init(&process_queue);
1580 skb_queue_splice_tail_init(queue, &process_queue);
1581 rcv = true;
1582 } else {
1583 __skb_queue_tail(queue, skb);
1584 }
1585 spin_unlock(&queue->lock);
1586
1587 if (rcv) {
1588 struct sk_buff *nskb;
1589
1590 local_bh_disable();
8ebebcba
MC
1591 while ((nskb = __skb_dequeue(&process_queue))) {
1592 skb_record_rx_queue(nskb, tfile->queue_index);
5503fcec 1593 netif_receive_skb(nskb);
8ebebcba
MC
1594 }
1595 skb_record_rx_queue(skb, tfile->queue_index);
5503fcec
JW
1596 netif_receive_skb(skb);
1597 local_bh_enable();
1598 }
1599}
1600
66ccbc9c
JW
1601static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
1602 int len, int noblock, bool zerocopy)
1603{
1604 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
1605 return false;
1606
1607 if (tfile->socket.sk->sk_sndbuf != INT_MAX)
1608 return false;
1609
1610 if (!noblock)
1611 return false;
1612
1613 if (zerocopy)
1614 return false;
1615
1616 if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
1617 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
1618 return false;
1619
1620 return true;
1621}
1622
ac1f1f6c 1623static struct sk_buff *__tun_build_skb(struct page_frag *alloc_frag, char *buf,
8ae1aff0 1624 int buflen, int len, int pad)
ac1f1f6c
JW
1625{
1626 struct sk_buff *skb = build_skb(buf, buflen);
1627
1628 if (!skb)
1629 return ERR_PTR(-ENOMEM);
1630
8ae1aff0 1631 skb_reserve(skb, pad);
ac1f1f6c
JW
1632 skb_put(skb, len);
1633
1634 get_page(alloc_frag->page);
1635 alloc_frag->offset += buflen;
1636
1637 return skb;
1638}
1639
8ae1aff0
JW
1640static int tun_xdp_act(struct tun_struct *tun, struct bpf_prog *xdp_prog,
1641 struct xdp_buff *xdp, u32 act)
1642{
1643 int err;
1644
1645 switch (act) {
1646 case XDP_REDIRECT:
1647 err = xdp_do_redirect(tun->dev, xdp, xdp_prog);
8ae1aff0
JW
1648 if (err)
1649 return err;
1650 break;
1651 case XDP_TX:
1652 err = tun_xdp_tx(tun->dev, xdp);
1653 if (err < 0)
1654 return err;
1655 break;
1656 case XDP_PASS:
1657 break;
1658 default:
1659 bpf_warn_invalid_xdp_action(act);
1660 /* fall through */
1661 case XDP_ABORTED:
1662 trace_xdp_exception(tun->dev, xdp_prog, act);
1663 /* fall through */
1664 case XDP_DROP:
1665 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1666 break;
1667 }
1668
1669 return act;
1670}
1671
761876c8
JW
1672static struct sk_buff *tun_build_skb(struct tun_struct *tun,
1673 struct tun_file *tfile,
66ccbc9c 1674 struct iov_iter *from,
761876c8 1675 struct virtio_net_hdr *hdr,
1cfe6e93 1676 int len, int *skb_xdp)
66ccbc9c 1677{
0bbd7dad 1678 struct page_frag *alloc_frag = &current->task_frag;
761876c8 1679 struct bpf_prog *xdp_prog;
7df13219 1680 int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
66ccbc9c
JW
1681 char *buf;
1682 size_t copied;
8ae1aff0
JW
1683 int pad = TUN_RX_PAD;
1684 int err = 0;
7df13219
JW
1685
1686 rcu_read_lock();
1687 xdp_prog = rcu_dereference(tun->xdp_prog);
1688 if (xdp_prog)
4f23aff8 1689 pad += XDP_PACKET_HEADROOM;
7df13219
JW
1690 buflen += SKB_DATA_ALIGN(len + pad);
1691 rcu_read_unlock();
66ccbc9c 1692
63b9ab65 1693 alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
66ccbc9c
JW
1694 if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
1695 return ERR_PTR(-ENOMEM);
1696
1697 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1698 copied = copy_page_from_iter(alloc_frag->page,
7df13219 1699 alloc_frag->offset + pad,
66ccbc9c
JW
1700 len, from);
1701 if (copied != len)
1702 return ERR_PTR(-EFAULT);
1703
7df13219
JW
1704 /* There's a small window that XDP may be set after the check
1705 * of xdp_prog above, this should be rare and for simplicity
1706 * we do XDP on skb in case the headroom is not enough.
1707 */
ac1f1f6c 1708 if (hdr->gso_type || !xdp_prog) {
1cfe6e93 1709 *skb_xdp = 1;
8ae1aff0 1710 return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
ac1f1f6c
JW
1711 }
1712
1713 *skb_xdp = 0;
761876c8 1714
6547e387 1715 local_bh_disable();
761876c8
JW
1716 rcu_read_lock();
1717 xdp_prog = rcu_dereference(tun->xdp_prog);
8ae1aff0 1718 if (xdp_prog) {
761876c8 1719 struct xdp_buff xdp;
761876c8
JW
1720 u32 act;
1721
1722 xdp.data_hard_start = buf;
7df13219 1723 xdp.data = buf + pad;
de8f3a83 1724 xdp_set_data_meta_invalid(&xdp);
761876c8 1725 xdp.data_end = xdp.data + len;
8bf5c4ee 1726 xdp.rxq = &tfile->xdp_rxq;
761876c8 1727
8ae1aff0
JW
1728 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1729 if (act == XDP_REDIRECT || act == XDP_TX) {
59655a5b
JW
1730 get_page(alloc_frag->page);
1731 alloc_frag->offset += buflen;
761876c8 1732 }
8ae1aff0
JW
1733 err = tun_xdp_act(tun, xdp_prog, &xdp, act);
1734 if (err < 0)
1735 goto err_xdp;
1a097910
JW
1736 if (err == XDP_REDIRECT)
1737 xdp_do_flush_map();
8ae1aff0
JW
1738 if (err != XDP_PASS)
1739 goto out;
1740
1741 pad = xdp.data - xdp.data_hard_start;
1742 len = xdp.data_end - xdp.data;
761876c8 1743 }
291aeb2b
JW
1744 rcu_read_unlock();
1745 local_bh_enable();
761876c8 1746
8ae1aff0 1747 return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
761876c8 1748
8ae1aff0 1749err_xdp:
761876c8 1750 put_page(alloc_frag->page);
f7053b6c 1751out:
761876c8 1752 rcu_read_unlock();
6547e387 1753 local_bh_enable();
761876c8 1754 return NULL;
66ccbc9c
JW
1755}
1756
1da177e4 1757/* Get packet from user space buffer */
54f968d6 1758static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
f5ff53b4 1759 void *msg_control, struct iov_iter *from,
5503fcec 1760 int noblock, bool more)
1da177e4 1761{
09640e63 1762 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1da177e4 1763 struct sk_buff *skb;
f5ff53b4 1764 size_t total_len = iov_iter_count(from);
eaea34b2 1765 size_t len = total_len, align = tun->align, linear;
f43798c2 1766 struct virtio_net_hdr gso = { 0 };
608b9977 1767 struct tun_pcpu_stats *stats;
96f8d9ec 1768 int good_linear;
0690899b
MT
1769 int copylen;
1770 bool zerocopy = false;
1771 int err;
96f84061 1772 u32 rxhash = 0;
1cfe6e93 1773 int skb_xdp = 1;
af3fb24e 1774 bool frags = tun_napi_frags_enabled(tfile);
1da177e4 1775
40630b82 1776 if (!(tun->flags & IFF_NO_PI)) {
15718ea0 1777 if (len < sizeof(pi))
1da177e4 1778 return -EINVAL;
15718ea0 1779 len -= sizeof(pi);
1da177e4 1780
cbbd26b8 1781 if (!copy_from_iter_full(&pi, sizeof(pi), from))
1da177e4
LT
1782 return -EFAULT;
1783 }
1784
40630b82 1785 if (tun->flags & IFF_VNET_HDR) {
e1edab87
WB
1786 int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1787
1788 if (len < vnet_hdr_sz)
f43798c2 1789 return -EINVAL;
e1edab87 1790 len -= vnet_hdr_sz;
f43798c2 1791
cbbd26b8 1792 if (!copy_from_iter_full(&gso, sizeof(gso), from))
f43798c2
RR
1793 return -EFAULT;
1794
4909122f 1795 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
56f0dcc5
MT
1796 tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
1797 gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
4909122f 1798
56f0dcc5 1799 if (tun16_to_cpu(tun, gso.hdr_len) > len)
f43798c2 1800 return -EINVAL;
e1edab87 1801 iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
f43798c2
RR
1802 }
1803
40630b82 1804 if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
a504b86e 1805 align += NET_IP_ALIGN;
0eca93bc 1806 if (unlikely(len < ETH_HLEN ||
56f0dcc5 1807 (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
e01bf1c8
RR
1808 return -EINVAL;
1809 }
6aa20a22 1810
96f8d9ec
JW
1811 good_linear = SKB_MAX_HEAD(align);
1812
88529176 1813 if (msg_control) {
f5ff53b4
AV
1814 struct iov_iter i = *from;
1815
88529176
JW
1816 /* There are 256 bytes to be copied in skb, so there is
1817 * enough room for skb expand head in case it is used.
0690899b
MT
1818 * The rest of the buffer is mapped from userspace.
1819 */
56f0dcc5 1820 copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
96f8d9ec
JW
1821 if (copylen > good_linear)
1822 copylen = good_linear;
3dd5c330 1823 linear = copylen;
f5ff53b4
AV
1824 iov_iter_advance(&i, copylen);
1825 if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
88529176
JW
1826 zerocopy = true;
1827 }
1828
90e33d45 1829 if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
1cfe6e93
JW
1830 /* For the packet that is not easy to be processed
1831 * (e.g gso or jumbo packet), we will do it at after
1832 * skb was created with generic XDP routine.
1833 */
1834 skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
66ccbc9c 1835 if (IS_ERR(skb)) {
608b9977 1836 this_cpu_inc(tun->pcpu_stats->rx_dropped);
66ccbc9c
JW
1837 return PTR_ERR(skb);
1838 }
761876c8
JW
1839 if (!skb)
1840 return total_len;
66ccbc9c
JW
1841 } else {
1842 if (!zerocopy) {
1843 copylen = len;
1844 if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
1845 linear = good_linear;
1846 else
1847 linear = tun16_to_cpu(tun, gso.hdr_len);
1848 }
1da177e4 1849
90e33d45
PP
1850 if (frags) {
1851 mutex_lock(&tfile->napi_mutex);
1852 skb = tun_napi_alloc_frags(tfile, copylen, from);
1853 /* tun_napi_alloc_frags() enforces a layout for the skb.
1854 * If zerocopy is enabled, then this layout will be
1855 * overwritten by zerocopy_sg_from_iter().
1856 */
1857 zerocopy = false;
1858 } else {
1859 skb = tun_alloc_skb(tfile, align, copylen, linear,
1860 noblock);
1861 }
1862
66ccbc9c
JW
1863 if (IS_ERR(skb)) {
1864 if (PTR_ERR(skb) != -EAGAIN)
1865 this_cpu_inc(tun->pcpu_stats->rx_dropped);
90e33d45
PP
1866 if (frags)
1867 mutex_unlock(&tfile->napi_mutex);
66ccbc9c
JW
1868 return PTR_ERR(skb);
1869 }
0690899b 1870
66ccbc9c
JW
1871 if (zerocopy)
1872 err = zerocopy_sg_from_iter(skb, from);
1873 else
1874 err = skb_copy_datagram_from_iter(skb, 0, from, len);
1875
1876 if (err) {
615a99ce
ED
1877 err = -EFAULT;
1878drop:
66ccbc9c
JW
1879 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1880 kfree_skb(skb);
90e33d45
PP
1881 if (frags) {
1882 tfile->napi.skb = NULL;
1883 mutex_unlock(&tfile->napi_mutex);
1884 }
1885
615a99ce 1886 return err;
66ccbc9c 1887 }
8f22757e 1888 }
1da177e4 1889
3e9e40e7 1890 if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
df10db98
PA
1891 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
1892 kfree_skb(skb);
90e33d45
PP
1893 if (frags) {
1894 tfile->napi.skb = NULL;
1895 mutex_unlock(&tfile->napi_mutex);
1896 }
1897
df10db98
PA
1898 return -EINVAL;
1899 }
1900
1da177e4 1901 switch (tun->flags & TUN_TYPE_MASK) {
40630b82
MT
1902 case IFF_TUN:
1903 if (tun->flags & IFF_NO_PI) {
2580c4c1
AP
1904 u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
1905
1906 switch (ip_version) {
1907 case 4:
f09f7ee2
AWC
1908 pi.proto = htons(ETH_P_IP);
1909 break;
2580c4c1 1910 case 6:
f09f7ee2
AWC
1911 pi.proto = htons(ETH_P_IPV6);
1912 break;
1913 default:
608b9977 1914 this_cpu_inc(tun->pcpu_stats->rx_dropped);
f09f7ee2
AWC
1915 kfree_skb(skb);
1916 return -EINVAL;
1917 }
1918 }
1919
459a98ed 1920 skb_reset_mac_header(skb);
1da177e4 1921 skb->protocol = pi.proto;
4c13eb66 1922 skb->dev = tun->dev;
1da177e4 1923 break;
40630b82 1924 case IFF_TAP:
90e33d45
PP
1925 if (!frags)
1926 skb->protocol = eth_type_trans(skb, tun->dev);
1da177e4 1927 break;
6403eab1 1928 }
1da177e4 1929
0690899b
MT
1930 /* copy skb_ubuf_info for callback when skb has no error */
1931 if (zerocopy) {
1932 skb_shinfo(skb)->destructor_arg = msg_control;
1933 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
c9af6db4 1934 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
af1cc7a2
JW
1935 } else if (msg_control) {
1936 struct ubuf_info *uarg = msg_control;
1937 uarg->callback(uarg, false);
0690899b
MT
1938 }
1939
72f65107 1940 skb_reset_network_header(skb);
40893fd0 1941 skb_probe_transport_header(skb, 0);
38502af7 1942
1cfe6e93 1943 if (skb_xdp) {
761876c8
JW
1944 struct bpf_prog *xdp_prog;
1945 int ret;
1946
6547e387 1947 local_bh_disable();
761876c8
JW
1948 rcu_read_lock();
1949 xdp_prog = rcu_dereference(tun->xdp_prog);
1950 if (xdp_prog) {
1951 ret = do_xdp_generic(xdp_prog, skb);
1952 if (ret != XDP_PASS) {
1953 rcu_read_unlock();
6547e387 1954 local_bh_enable();
761876c8
JW
1955 return total_len;
1956 }
1957 }
1958 rcu_read_unlock();
6547e387 1959 local_bh_enable();
761876c8
JW
1960 }
1961
cf1a1e07
PA
1962 /* Compute the costly rx hash only if needed for flow updates.
1963 * We may get a very small possibility of OOO during switching, not
1964 * worth to optimize.
1965 */
1966 if (!rcu_access_pointer(tun->steering_prog) && tun->numqueues > 1 &&
1967 !tfile->detached)
96f84061 1968 rxhash = __skb_get_hash_symmetric(skb);
94317099 1969
615a99ce
ED
1970 rcu_read_lock();
1971 if (unlikely(!(tun->dev->flags & IFF_UP))) {
1972 err = -EIO;
1072b096 1973 rcu_read_unlock();
615a99ce
ED
1974 goto drop;
1975 }
1976
90e33d45
PP
1977 if (frags) {
1978 /* Exercise flow dissector code path. */
1979 u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
1980
010f245b 1981 if (unlikely(headlen > skb_headlen(skb))) {
90e33d45
PP
1982 this_cpu_inc(tun->pcpu_stats->rx_dropped);
1983 napi_free_frags(&tfile->napi);
615a99ce 1984 rcu_read_unlock();
90e33d45
PP
1985 mutex_unlock(&tfile->napi_mutex);
1986 WARN_ON(1);
1987 return -ENOMEM;
1988 }
1989
1990 local_bh_disable();
1991 napi_gro_frags(&tfile->napi);
1992 local_bh_enable();
1993 mutex_unlock(&tfile->napi_mutex);
aec72f33 1994 } else if (tfile->napi_enabled) {
94317099
PP
1995 struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
1996 int queue_len;
1997
1998 spin_lock_bh(&queue->lock);
1999 __skb_queue_tail(queue, skb);
2000 queue_len = skb_queue_len(queue);
2001 spin_unlock(&queue->lock);
2002
2003 if (!more || queue_len > NAPI_POLL_WEIGHT)
2004 napi_schedule(&tfile->napi);
2005
2006 local_bh_enable();
2007 } else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
2008 tun_rx_batched(tun, tfile, skb, more);
2009 } else {
2010 netif_rx_ni(skb);
2011 }
615a99ce 2012 rcu_read_unlock();
6aa20a22 2013
608b9977
PA
2014 stats = get_cpu_ptr(tun->pcpu_stats);
2015 u64_stats_update_begin(&stats->syncp);
2016 stats->rx_packets++;
2017 stats->rx_bytes += len;
2018 u64_stats_update_end(&stats->syncp);
2019 put_cpu_ptr(stats);
1da177e4 2020
96f84061
JW
2021 if (rxhash)
2022 tun_flow_update(tun, rxhash, tfile);
2023
0690899b 2024 return total_len;
6aa20a22 2025}
1da177e4 2026
f5ff53b4 2027static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
1da177e4 2028{
33dccbb0 2029 struct file *file = iocb->ki_filp;
54f968d6 2030 struct tun_file *tfile = file->private_data;
9484dc74 2031 struct tun_struct *tun = tun_get(tfile);
631ab46b 2032 ssize_t result;
1da177e4
LT
2033
2034 if (!tun)
2035 return -EBADFD;
2036
5503fcec
JW
2037 result = tun_get_user(tun, tfile, NULL, from,
2038 file->f_flags & O_NONBLOCK, false);
631ab46b
EB
2039
2040 tun_put(tun);
2041 return result;
1da177e4
LT
2042}
2043
fc72d1d5
JW
2044static ssize_t tun_put_user_xdp(struct tun_struct *tun,
2045 struct tun_file *tfile,
1ffcbc85 2046 struct xdp_frame *xdp_frame,
fc72d1d5
JW
2047 struct iov_iter *iter)
2048{
2049 int vnet_hdr_sz = 0;
1ffcbc85 2050 size_t size = xdp_frame->len;
fc72d1d5
JW
2051 struct tun_pcpu_stats *stats;
2052 size_t ret;
2053
2054 if (tun->flags & IFF_VNET_HDR) {
2055 struct virtio_net_hdr gso = { 0 };
2056
2057 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
2058 if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
2059 return -EINVAL;
2060 if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
2061 sizeof(gso)))
2062 return -EFAULT;
2063 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
2064 }
2065
1ffcbc85 2066 ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
fc72d1d5
JW
2067
2068 stats = get_cpu_ptr(tun->pcpu_stats);
2069 u64_stats_update_begin(&stats->syncp);
2070 stats->tx_packets++;
2071 stats->tx_bytes += ret;
2072 u64_stats_update_end(&stats->syncp);
2073 put_cpu_ptr(tun->pcpu_stats);
2074
2075 return ret;
2076}
2077
1da177e4 2078/* Put packet to the user space buffer */
6f7c156c 2079static ssize_t tun_put_user(struct tun_struct *tun,
54f968d6 2080 struct tun_file *tfile,
6f7c156c 2081 struct sk_buff *skb,
e0b46d0e 2082 struct iov_iter *iter)
1da177e4
LT
2083{
2084 struct tun_pi pi = { 0, skb->protocol };
608b9977 2085 struct tun_pcpu_stats *stats;
e0b46d0e 2086 ssize_t total;
8c847d25 2087 int vlan_offset = 0;
a8f9bfdf 2088 int vlan_hlen = 0;
2eb783c4 2089 int vnet_hdr_sz = 0;
a8f9bfdf 2090
df8a39de 2091 if (skb_vlan_tag_present(skb))
a8f9bfdf 2092 vlan_hlen = VLAN_HLEN;
1da177e4 2093
40630b82 2094 if (tun->flags & IFF_VNET_HDR)
e1edab87 2095 vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
1da177e4 2096
e0b46d0e
HX
2097 total = skb->len + vlan_hlen + vnet_hdr_sz;
2098
40630b82 2099 if (!(tun->flags & IFF_NO_PI)) {
e0b46d0e 2100 if (iov_iter_count(iter) < sizeof(pi))
1da177e4
LT
2101 return -EINVAL;
2102
e0b46d0e
HX
2103 total += sizeof(pi);
2104 if (iov_iter_count(iter) < total) {
1da177e4
LT
2105 /* Packet will be striped */
2106 pi.flags |= TUN_PKT_STRIP;
2107 }
6aa20a22 2108
e0b46d0e 2109 if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
1da177e4 2110 return -EFAULT;
6aa20a22 2111 }
1da177e4 2112
2eb783c4 2113 if (vnet_hdr_sz) {
9403cd7c 2114 struct virtio_net_hdr gso;
34166093 2115
e0b46d0e 2116 if (iov_iter_count(iter) < vnet_hdr_sz)
f43798c2
RR
2117 return -EINVAL;
2118
3e9e40e7 2119 if (virtio_net_hdr_from_skb(skb, &gso,
fd3a8862
WB
2120 tun_is_little_endian(tun), true,
2121 vlan_hlen)) {
f43798c2 2122 struct skb_shared_info *sinfo = skb_shinfo(skb);
34166093
MR
2123 pr_err("unexpected GSO type: "
2124 "0x%x, gso_size %d, hdr_len %d\n",
2125 sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
2126 tun16_to_cpu(tun, gso.hdr_len));
2127 print_hex_dump(KERN_ERR, "tun: ",
2128 DUMP_PREFIX_NONE,
2129 16, 1, skb->head,
2130 min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
2131 WARN_ON_ONCE(1);
2132 return -EINVAL;
2133 }
f43798c2 2134
e0b46d0e 2135 if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
f43798c2 2136 return -EFAULT;
8c847d25
JW
2137
2138 iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
f43798c2
RR
2139 }
2140
a8f9bfdf 2141 if (vlan_hlen) {
e0b46d0e 2142 int ret;
aff3d70a 2143 struct veth veth;
6680ec68
JW
2144
2145 veth.h_vlan_proto = skb->vlan_proto;
df8a39de 2146 veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
6680ec68
JW
2147
2148 vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
6680ec68 2149
e0b46d0e
HX
2150 ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
2151 if (ret || !iov_iter_count(iter))
6680ec68
JW
2152 goto done;
2153
e0b46d0e
HX
2154 ret = copy_to_iter(&veth, sizeof(veth), iter);
2155 if (ret != sizeof(veth) || !iov_iter_count(iter))
6680ec68
JW
2156 goto done;
2157 }
1da177e4 2158
e0b46d0e 2159 skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
1da177e4 2160
6680ec68 2161done:
608b9977
PA
2162 /* caller is in process context, */
2163 stats = get_cpu_ptr(tun->pcpu_stats);
2164 u64_stats_update_begin(&stats->syncp);
2165 stats->tx_packets++;
2166 stats->tx_bytes += skb->len + vlan_hlen;
2167 u64_stats_update_end(&stats->syncp);
2168 put_cpu_ptr(tun->pcpu_stats);
1da177e4
LT
2169
2170 return total;
2171}
2172
fc72d1d5 2173static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
1576d986
JW
2174{
2175 DECLARE_WAITQUEUE(wait, current);
fc72d1d5 2176 void *ptr = NULL;
f48cc6b2 2177 int error = 0;
1576d986 2178
fc72d1d5
JW
2179 ptr = ptr_ring_consume(&tfile->tx_ring);
2180 if (ptr)
1576d986
JW
2181 goto out;
2182 if (noblock) {
f48cc6b2 2183 error = -EAGAIN;
1576d986
JW
2184 goto out;
2185 }
2186
2187 add_wait_queue(&tfile->wq.wait, &wait);
1576d986
JW
2188
2189 while (1) {
71828b22 2190 set_current_state(TASK_INTERRUPTIBLE);
fc72d1d5
JW
2191 ptr = ptr_ring_consume(&tfile->tx_ring);
2192 if (ptr)
1576d986
JW
2193 break;
2194 if (signal_pending(current)) {
f48cc6b2 2195 error = -ERESTARTSYS;
1576d986
JW
2196 break;
2197 }
2198 if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
f48cc6b2 2199 error = -EFAULT;
1576d986
JW
2200 break;
2201 }
2202
2203 schedule();
2204 }
2205
ecef67cb 2206 __set_current_state(TASK_RUNNING);
1576d986
JW
2207 remove_wait_queue(&tfile->wq.wait, &wait);
2208
2209out:
f48cc6b2 2210 *err = error;
fc72d1d5 2211 return ptr;
1576d986
JW
2212}
2213
54f968d6 2214static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
9b067034 2215 struct iov_iter *to,
fc72d1d5 2216 int noblock, void *ptr)
1da177e4 2217{
9b067034 2218 ssize_t ret;
1576d986 2219 int err;
1da177e4 2220
3872baf6 2221 tun_debug(KERN_INFO, tun, "tun_do_read\n");
1da177e4 2222
c33ee15b 2223 if (!iov_iter_count(to)) {
fc72d1d5 2224 tun_ptr_free(ptr);
9b067034 2225 return 0;
c33ee15b 2226 }
1da177e4 2227
fc72d1d5 2228 if (!ptr) {
ac77cfd4 2229 /* Read frames from ring */
fc72d1d5
JW
2230 ptr = tun_ring_recv(tfile, noblock, &err);
2231 if (!ptr)
ac77cfd4
JW
2232 return err;
2233 }
e0b46d0e 2234
1ffcbc85
JDB
2235 if (tun_is_xdp_frame(ptr)) {
2236 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
fc72d1d5 2237
1ffcbc85 2238 ret = tun_put_user_xdp(tun, tfile, xdpf, to);
03993094 2239 xdp_return_frame(xdpf);
fc72d1d5
JW
2240 } else {
2241 struct sk_buff *skb = ptr;
2242
2243 ret = tun_put_user(tun, tfile, skb, to);
2244 if (unlikely(ret < 0))
2245 kfree_skb(skb);
2246 else
2247 consume_skb(skb);
2248 }
1da177e4 2249
05c2828c
MT
2250 return ret;
2251}
2252
9b067034 2253static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
05c2828c
MT
2254{
2255 struct file *file = iocb->ki_filp;
2256 struct tun_file *tfile = file->private_data;
9484dc74 2257 struct tun_struct *tun = tun_get(tfile);
9b067034 2258 ssize_t len = iov_iter_count(to), ret;
05c2828c
MT
2259
2260 if (!tun)
2261 return -EBADFD;
ac77cfd4 2262 ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
42404c09 2263 ret = min_t(ssize_t, ret, len);
d0b7da8a
ZYW
2264 if (ret > 0)
2265 iocb->ki_pos = ret;
631ab46b 2266 tun_put(tun);
1da177e4
LT
2267 return ret;
2268}
2269
cd5681d7 2270static void tun_prog_free(struct rcu_head *rcu)
96f84061 2271{
cd5681d7 2272 struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
96f84061
JW
2273
2274 bpf_prog_destroy(prog->prog);
2275 kfree(prog);
2276}
2277
9d6474e4
JW
2278static int __tun_set_ebpf(struct tun_struct *tun,
2279 struct tun_prog __rcu **prog_p,
cd5681d7 2280 struct bpf_prog *prog)
96f84061 2281{
cd5681d7 2282 struct tun_prog *old, *new = NULL;
96f84061
JW
2283
2284 if (prog) {
2285 new = kmalloc(sizeof(*new), GFP_KERNEL);
2286 if (!new)
2287 return -ENOMEM;
2288 new->prog = prog;
2289 }
2290
124da8f6 2291 spin_lock_bh(&tun->lock);
cd5681d7 2292 old = rcu_dereference_protected(*prog_p,
124da8f6 2293 lockdep_is_held(&tun->lock));
cd5681d7 2294 rcu_assign_pointer(*prog_p, new);
124da8f6 2295 spin_unlock_bh(&tun->lock);
96f84061
JW
2296
2297 if (old)
cd5681d7 2298 call_rcu(&old->rcu, tun_prog_free);
96f84061
JW
2299
2300 return 0;
2301}
2302
96442e42
JW
2303static void tun_free_netdev(struct net_device *dev)
2304{
2305 struct tun_struct *tun = netdev_priv(dev);
2306
4008e97f 2307 BUG_ON(!(list_empty(&tun->disabled)));
608b9977 2308 free_percpu(tun->pcpu_stats);
96442e42 2309 tun_flow_uninit(tun);
5dbbaf2d 2310 security_tun_dev_free_security(tun->security);
cd5681d7 2311 __tun_set_ebpf(tun, &tun->steering_prog, NULL);
aff3d70a 2312 __tun_set_ebpf(tun, &tun->filter_prog, NULL);
96442e42
JW
2313}
2314
1da177e4
LT
2315static void tun_setup(struct net_device *dev)
2316{
2317 struct tun_struct *tun = netdev_priv(dev);
2318
0625c883
EB
2319 tun->owner = INVALID_UID;
2320 tun->group = INVALID_GID;
4e24f2dd 2321 tun_default_link_ksettings(dev, &tun->link_ksettings);
1da177e4 2322
1da177e4 2323 dev->ethtool_ops = &tun_ethtool_ops;
cf124db5
DM
2324 dev->needs_free_netdev = true;
2325 dev->priv_destructor = tun_free_netdev;
016adb72
JW
2326 /* We prefer our own queue length */
2327 dev->tx_queue_len = TUN_READQ_SIZE;
1da177e4
LT
2328}
2329
f019a7a5
EB
2330/* Trivial set of netlink ops to allow deleting tun or tap
2331 * device with netlink.
2332 */
a8b8a889
MS
2333static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
2334 struct netlink_ext_ack *extack)
f019a7a5 2335{
35b827b6
ND
2336 NL_SET_ERR_MSG(extack,
2337 "tun/tap creation via rtnetlink is not supported.");
2338 return -EOPNOTSUPP;
f019a7a5
EB
2339}
2340
1ec010e7
SD
2341static size_t tun_get_size(const struct net_device *dev)
2342{
2343 BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
2344 BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
2345
2346 return nla_total_size(sizeof(uid_t)) + /* OWNER */
2347 nla_total_size(sizeof(gid_t)) + /* GROUP */
2348 nla_total_size(sizeof(u8)) + /* TYPE */
2349 nla_total_size(sizeof(u8)) + /* PI */
2350 nla_total_size(sizeof(u8)) + /* VNET_HDR */
2351 nla_total_size(sizeof(u8)) + /* PERSIST */
2352 nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
2353 nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
2354 nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
2355 0;
2356}
2357
2358static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
2359{
2360 struct tun_struct *tun = netdev_priv(dev);
2361
2362 if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
2363 goto nla_put_failure;
2364 if (uid_valid(tun->owner) &&
2365 nla_put_u32(skb, IFLA_TUN_OWNER,
2366 from_kuid_munged(current_user_ns(), tun->owner)))
2367 goto nla_put_failure;
2368 if (gid_valid(tun->group) &&
2369 nla_put_u32(skb, IFLA_TUN_GROUP,
2370 from_kgid_munged(current_user_ns(), tun->group)))
2371 goto nla_put_failure;
2372 if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
2373 goto nla_put_failure;
2374 if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
2375 goto nla_put_failure;
2376 if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
2377 goto nla_put_failure;
2378 if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
2379 !!(tun->flags & IFF_MULTI_QUEUE)))
2380 goto nla_put_failure;
2381 if (tun->flags & IFF_MULTI_QUEUE) {
2382 if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
2383 goto nla_put_failure;
2384 if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
2385 tun->numdisabled))
2386 goto nla_put_failure;
2387 }
2388
2389 return 0;
2390
2391nla_put_failure:
2392 return -EMSGSIZE;
2393}
2394
f019a7a5
EB
2395static struct rtnl_link_ops tun_link_ops __read_mostly = {
2396 .kind = DRV_NAME,
2397 .priv_size = sizeof(struct tun_struct),
2398 .setup = tun_setup,
2399 .validate = tun_validate,
1ec010e7
SD
2400 .get_size = tun_get_size,
2401 .fill_info = tun_fill_info,
f019a7a5
EB
2402};
2403
33dccbb0
HX
2404static void tun_sock_write_space(struct sock *sk)
2405{
54f968d6 2406 struct tun_file *tfile;
43815482 2407 wait_queue_head_t *wqueue;
33dccbb0
HX
2408
2409 if (!sock_writeable(sk))
2410 return;
2411
9cd3e072 2412 if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
33dccbb0
HX
2413 return;
2414
43815482
ED
2415 wqueue = sk_sleep(sk);
2416 if (wqueue && waitqueue_active(wqueue))
a9a08845
LT
2417 wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
2418 EPOLLWRNORM | EPOLLWRBAND);
c722c625 2419
54f968d6
JW
2420 tfile = container_of(sk, struct tun_file, sk);
2421 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
33dccbb0
HX
2422}
2423
f9e06c45
JW
2424static void tun_put_page(struct tun_page *tpage)
2425{
2426 if (tpage->page)
2427 __page_frag_cache_drain(tpage->page, tpage->count);
2428}
2429
043d222f
JW
2430static int tun_xdp_one(struct tun_struct *tun,
2431 struct tun_file *tfile,
f9e06c45
JW
2432 struct xdp_buff *xdp, int *flush,
2433 struct tun_page *tpage)
043d222f 2434{
4e4b08e5 2435 unsigned int datasize = xdp->data_end - xdp->data;
043d222f
JW
2436 struct tun_xdp_hdr *hdr = xdp->data_hard_start;
2437 struct virtio_net_hdr *gso = &hdr->gso;
2438 struct tun_pcpu_stats *stats;
2439 struct bpf_prog *xdp_prog;
2440 struct sk_buff *skb = NULL;
2441 u32 rxhash = 0, act;
2442 int buflen = hdr->buflen;
2443 int err = 0;
2444 bool skb_xdp = false;
f9e06c45 2445 struct page *page;
043d222f
JW
2446
2447 xdp_prog = rcu_dereference(tun->xdp_prog);
2448 if (xdp_prog) {
2449 if (gso->gso_type) {
2450 skb_xdp = true;
2451 goto build;
2452 }
2453 xdp_set_data_meta_invalid(xdp);
2454 xdp->rxq = &tfile->xdp_rxq;
2455
2456 act = bpf_prog_run_xdp(xdp_prog, xdp);
2457 err = tun_xdp_act(tun, xdp_prog, xdp, act);
2458 if (err < 0) {
2459 put_page(virt_to_head_page(xdp->data));
2460 return err;
2461 }
2462
2463 switch (err) {
2464 case XDP_REDIRECT:
2465 *flush = true;
2466 /* fall through */
2467 case XDP_TX:
2468 return 0;
2469 case XDP_PASS:
2470 break;
2471 default:
f9e06c45
JW
2472 page = virt_to_head_page(xdp->data);
2473 if (tpage->page == page) {
2474 ++tpage->count;
2475 } else {
2476 tun_put_page(tpage);
2477 tpage->page = page;
2478 tpage->count = 1;
2479 }
043d222f
JW
2480 return 0;
2481 }
2482 }
2483
2484build:
2485 skb = build_skb(xdp->data_hard_start, buflen);
2486 if (!skb) {
2487 err = -ENOMEM;
2488 goto out;
2489 }
2490
2491 skb_reserve(skb, xdp->data - xdp->data_hard_start);
2492 skb_put(skb, xdp->data_end - xdp->data);
2493
2494 if (virtio_net_hdr_to_skb(skb, gso, tun_is_little_endian(tun))) {
2495 this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
2496 kfree_skb(skb);
2497 err = -EINVAL;
2498 goto out;
2499 }
2500
2501 skb->protocol = eth_type_trans(skb, tun->dev);
2502 skb_reset_network_header(skb);
2503 skb_probe_transport_header(skb, 0);
2504
2505 if (skb_xdp) {
2506 err = do_xdp_generic(xdp_prog, skb);
2507 if (err != XDP_PASS)
2508 goto out;
2509 }
2510
f29eb2a9
PA
2511 if (!rcu_dereference(tun->steering_prog) && tun->numqueues > 1 &&
2512 !tfile->detached)
043d222f
JW
2513 rxhash = __skb_get_hash_symmetric(skb);
2514
8ebebcba 2515 skb_record_rx_queue(skb, tfile->queue_index);
043d222f
JW
2516 netif_receive_skb(skb);
2517
6342ca64
PB
2518 /* No need for get_cpu_ptr() here since this function is
2519 * always called with bh disabled
2520 */
2521 stats = this_cpu_ptr(tun->pcpu_stats);
043d222f
JW
2522 u64_stats_update_begin(&stats->syncp);
2523 stats->rx_packets++;
4e4b08e5 2524 stats->rx_bytes += datasize;
043d222f 2525 u64_stats_update_end(&stats->syncp);
043d222f
JW
2526
2527 if (rxhash)
2528 tun_flow_update(tun, rxhash, tfile);
2529
2530out:
2531 return err;
2532}
2533
1b784140 2534static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
05c2828c 2535{
043d222f 2536 int ret, i;
54f968d6 2537 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
9484dc74 2538 struct tun_struct *tun = tun_get(tfile);
fe8dd45b 2539 struct tun_msg_ctl *ctl = m->msg_control;
043d222f 2540 struct xdp_buff *xdp;
54f968d6
JW
2541
2542 if (!tun)
2543 return -EBADFD;
f5ff53b4 2544
043d222f 2545 if (ctl && (ctl->type == TUN_MSG_PTR)) {
6f0271d9 2546 struct tun_page tpage;
043d222f
JW
2547 int n = ctl->num;
2548 int flush = 0;
2549
6f0271d9
DM
2550 memset(&tpage, 0, sizeof(tpage));
2551
043d222f
JW
2552 local_bh_disable();
2553 rcu_read_lock();
2554
2555 for (i = 0; i < n; i++) {
2556 xdp = &((struct xdp_buff *)ctl->ptr)[i];
f9e06c45 2557 tun_xdp_one(tun, tfile, xdp, &flush, &tpage);
043d222f
JW
2558 }
2559
2560 if (flush)
2561 xdp_do_flush_map();
2562
2563 rcu_read_unlock();
2564 local_bh_enable();
2565
f9e06c45
JW
2566 tun_put_page(&tpage);
2567
043d222f
JW
2568 ret = total_len;
2569 goto out;
2570 }
fe8dd45b
JW
2571
2572 ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
5503fcec
JW
2573 m->msg_flags & MSG_DONTWAIT,
2574 m->msg_flags & MSG_MORE);
043d222f 2575out:
54f968d6
JW
2576 tun_put(tun);
2577 return ret;
05c2828c
MT
2578}
2579
1b784140 2580static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
05c2828c
MT
2581 int flags)
2582{
54f968d6 2583 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
9484dc74 2584 struct tun_struct *tun = tun_get(tfile);
fc72d1d5 2585 void *ptr = m->msg_control;
05c2828c 2586 int ret;
54f968d6 2587
c33ee15b
WX
2588 if (!tun) {
2589 ret = -EBADFD;
fc72d1d5 2590 goto out_free;
c33ee15b 2591 }
54f968d6 2592
eda29772 2593 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
3811ae76 2594 ret = -EINVAL;
c33ee15b 2595 goto out_put_tun;
3811ae76 2596 }
eda29772
RC
2597 if (flags & MSG_ERRQUEUE) {
2598 ret = sock_recv_errqueue(sock->sk, m, total_len,
2599 SOL_PACKET, TUN_TX_TIMESTAMP);
2600 goto out;
2601 }
fc72d1d5 2602 ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
87897931 2603 if (ret > (ssize_t)total_len) {
42404c09
DM
2604 m->msg_flags |= MSG_TRUNC;
2605 ret = flags & MSG_TRUNC ? ret : total_len;
2606 }
3811ae76 2607out:
54f968d6 2608 tun_put(tun);
05c2828c 2609 return ret;
c33ee15b
WX
2610
2611out_put_tun:
2612 tun_put(tun);
fc72d1d5
JW
2613out_free:
2614 tun_ptr_free(ptr);
c33ee15b 2615 return ret;
05c2828c
MT
2616}
2617
fc72d1d5
JW
2618static int tun_ptr_peek_len(void *ptr)
2619{
2620 if (likely(ptr)) {
1ffcbc85
JDB
2621 if (tun_is_xdp_frame(ptr)) {
2622 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
fc72d1d5 2623
1ffcbc85 2624 return xdpf->len;
fc72d1d5
JW
2625 }
2626 return __skb_array_len_with_tag(ptr);
2627 } else {
2628 return 0;
2629 }
2630}
2631
1576d986
JW
2632static int tun_peek_len(struct socket *sock)
2633{
2634 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
2635 struct tun_struct *tun;
2636 int ret = 0;
2637
9484dc74 2638 tun = tun_get(tfile);
1576d986
JW
2639 if (!tun)
2640 return 0;
2641
fc72d1d5 2642 ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
1576d986
JW
2643 tun_put(tun);
2644
2645 return ret;
2646}
2647
05c2828c
MT
2648/* Ops structure to mimic raw sockets with tun */
2649static const struct proto_ops tun_socket_ops = {
1576d986 2650 .peek_len = tun_peek_len,
05c2828c
MT
2651 .sendmsg = tun_sendmsg,
2652 .recvmsg = tun_recvmsg,
2653};
2654
33dccbb0
HX
2655static struct proto tun_proto = {
2656 .name = "tun",
2657 .owner = THIS_MODULE,
54f968d6 2658 .obj_size = sizeof(struct tun_file),
33dccbb0 2659};
f019a7a5 2660
980c9e8c
DW
2661static int tun_flags(struct tun_struct *tun)
2662{
031f5e03 2663 return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
980c9e8c
DW
2664}
2665
2666static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
2667 char *buf)
2668{
2669 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
2670 return sprintf(buf, "0x%x\n", tun_flags(tun));
2671}
2672
2673static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
2674 char *buf)
2675{
2676 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
0625c883
EB
2677 return uid_valid(tun->owner)?
2678 sprintf(buf, "%u\n",
2679 from_kuid_munged(current_user_ns(), tun->owner)):
2680 sprintf(buf, "-1\n");
980c9e8c
DW
2681}
2682
2683static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
2684 char *buf)
2685{
2686 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
0625c883
EB
2687 return gid_valid(tun->group) ?
2688 sprintf(buf, "%u\n",
2689 from_kgid_munged(current_user_ns(), tun->group)):
2690 sprintf(buf, "-1\n");
980c9e8c
DW
2691}
2692
2693static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
2694static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
2695static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
2696
c4d33e24
TI
2697static struct attribute *tun_dev_attrs[] = {
2698 &dev_attr_tun_flags.attr,
2699 &dev_attr_owner.attr,
2700 &dev_attr_group.attr,
2701 NULL
2702};
2703
2704static const struct attribute_group tun_attr_group = {
2705 .attrs = tun_dev_attrs
2706};
2707
d647a591 2708static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1da177e4
LT
2709{
2710 struct tun_struct *tun;
54f968d6 2711 struct tun_file *tfile = file->private_data;
1da177e4
LT
2712 struct net_device *dev;
2713 int err;
2714
7c0c3b1a
JW
2715 if (tfile->detached)
2716 return -EINVAL;
2717
90e33d45
PP
2718 if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
2719 if (!capable(CAP_NET_ADMIN))
2720 return -EPERM;
2721
2722 if (!(ifr->ifr_flags & IFF_NAPI) ||
2723 (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
2724 return -EINVAL;
2725 }
2726
74a3e5a7
EB
2727 dev = __dev_get_by_name(net, ifr->ifr_name);
2728 if (dev) {
f85ba780
DW
2729 if (ifr->ifr_flags & IFF_TUN_EXCL)
2730 return -EBUSY;
74a3e5a7
EB
2731 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
2732 tun = netdev_priv(dev);
2733 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
2734 tun = netdev_priv(dev);
2735 else
2736 return -EINVAL;
2737
8e6d91ae 2738 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
40630b82 2739 !!(tun->flags & IFF_MULTI_QUEUE))
8e6d91ae
JW
2740 return -EINVAL;
2741
cde8b15f 2742 if (tun_not_capable(tun))
2b980dbd 2743 return -EPERM;
5dbbaf2d 2744 err = security_tun_dev_open(tun->security);
2b980dbd
PM
2745 if (err < 0)
2746 return err;
2747
94317099 2748 err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
af3fb24e
ED
2749 ifr->ifr_flags & IFF_NAPI,
2750 ifr->ifr_flags & IFF_NAPI_FRAGS);
a7385ba2
EB
2751 if (err < 0)
2752 return err;
4008e97f 2753
40630b82 2754 if (tun->flags & IFF_MULTI_QUEUE &&
e8dbad66
JW
2755 (tun->numqueues + tun->numdisabled > 1)) {
2756 /* One or more queue has already been attached, no need
2757 * to initialize the device again.
2758 */
83c1f36f 2759 netdev_state_change(dev);
e8dbad66
JW
2760 return 0;
2761 }
9fffc5c6
SD
2762
2763 tun->flags = (tun->flags & ~TUN_FEATURES) |
2764 (ifr->ifr_flags & TUN_FEATURES);
83c1f36f
SD
2765
2766 netdev_state_change(dev);
2767 } else {
1da177e4
LT
2768 char *name;
2769 unsigned long flags = 0;
edfb6a14
JW
2770 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
2771 MAX_TAP_QUEUES : 1;
1da177e4 2772
c260b772 2773 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
ca6bb5d7 2774 return -EPERM;
2b980dbd
PM
2775 err = security_tun_dev_create();
2776 if (err < 0)
2777 return err;
ca6bb5d7 2778
1da177e4
LT
2779 /* Set dev type */
2780 if (ifr->ifr_flags & IFF_TUN) {
2781 /* TUN device */
40630b82 2782 flags |= IFF_TUN;
1da177e4
LT
2783 name = "tun%d";
2784 } else if (ifr->ifr_flags & IFF_TAP) {
2785 /* TAP device */
40630b82 2786 flags |= IFF_TAP;
1da177e4 2787 name = "tap%d";
6aa20a22 2788 } else
36989b90 2789 return -EINVAL;
6aa20a22 2790
1da177e4
LT
2791 if (*ifr->ifr_name)
2792 name = ifr->ifr_name;
2793
c8d68e6b 2794 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
c835a677
TG
2795 NET_NAME_UNKNOWN, tun_setup, queues,
2796 queues);
edfb6a14 2797
1da177e4
LT
2798 if (!dev)
2799 return -ENOMEM;
0ad646c8 2800 err = dev_get_valid_name(net, dev, name);
5c25f65f 2801 if (err < 0)
0ad646c8 2802 goto err_free_dev;
1da177e4 2803
fc54c658 2804 dev_net_set(dev, net);
f019a7a5 2805 dev->rtnl_link_ops = &tun_link_ops;
fb7589a1 2806 dev->ifindex = tfile->ifindex;
c4d33e24 2807 dev->sysfs_groups[0] = &tun_attr_group;
758e43b7 2808
1da177e4
LT
2809 tun = netdev_priv(dev);
2810 tun->dev = dev;
2811 tun->flags = flags;
f271b2cc 2812 tun->txflt.count = 0;
d9d52b51 2813 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
33dccbb0 2814
eaea34b2 2815 tun->align = NET_SKB_PAD;
54f968d6
JW
2816 tun->filter_attached = false;
2817 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
5503fcec 2818 tun->rx_batched = 0;
96f84061 2819 RCU_INIT_POINTER(tun->steering_prog, NULL);
33dccbb0 2820
608b9977
PA
2821 tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
2822 if (!tun->pcpu_stats) {
2823 err = -ENOMEM;
2824 goto err_free_dev;
2825 }
2826
96442e42
JW
2827 spin_lock_init(&tun->lock);
2828
5dbbaf2d
PM
2829 err = security_tun_dev_alloc_security(&tun->security);
2830 if (err < 0)
608b9977 2831 goto err_free_stat;
2b980dbd 2832
1da177e4 2833 tun_net_init(dev);
944a1376 2834 tun_flow_init(tun);
96442e42 2835
88255375 2836 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
6680ec68
JW
2837 TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
2838 NETIF_F_HW_VLAN_STAG_TX;
2a2bbf17 2839 dev->features = dev->hw_features | NETIF_F_LLTX;
6671b224
FLVC
2840 dev->vlan_features = dev->features &
2841 ~(NETIF_F_HW_VLAN_CTAG_TX |
2842 NETIF_F_HW_VLAN_STAG_TX);
88255375 2843
9fffc5c6
SD
2844 tun->flags = (tun->flags & ~TUN_FEATURES) |
2845 (ifr->ifr_flags & TUN_FEATURES);
2846
4008e97f 2847 INIT_LIST_HEAD(&tun->disabled);
af3fb24e
ED
2848 err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI,
2849 ifr->ifr_flags & IFF_NAPI_FRAGS);
eb0fb363 2850 if (err < 0)
662ca437 2851 goto err_free_flow;
eb0fb363 2852
1da177e4
LT
2853 err = register_netdevice(tun->dev);
2854 if (err < 0)
662ca437 2855 goto err_detach;
1da177e4
LT
2856 }
2857
af668b3c
MT
2858 netif_carrier_on(tun->dev);
2859
6b8a66ee 2860 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1da177e4 2861
e35259a9
MK
2862 /* Make sure persistent devices do not get stuck in
2863 * xoff state.
2864 */
2865 if (netif_running(tun->dev))
c8d68e6b 2866 netif_tx_wake_all_queues(tun->dev);
e35259a9 2867
1da177e4
LT
2868 strcpy(ifr->ifr_name, tun->dev->name);
2869 return 0;
2870
662ca437
JW
2871err_detach:
2872 tun_detach_all(dev);
ff244c6b
ED
2873 /* register_netdevice() already called tun_free_netdev() */
2874 goto err_free_dev;
2875
662ca437
JW
2876err_free_flow:
2877 tun_flow_uninit(tun);
2878 security_tun_dev_free_security(tun->security);
608b9977
PA
2879err_free_stat:
2880 free_percpu(tun->pcpu_stats);
662ca437 2881err_free_dev:
1da177e4 2882 free_netdev(dev);
1da177e4
LT
2883 return err;
2884}
2885
9ce99cf6 2886static void tun_get_iff(struct net *net, struct tun_struct *tun,
876bfd4d 2887 struct ifreq *ifr)
e3b99556 2888{
6b8a66ee 2889 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
e3b99556
MM
2890
2891 strcpy(ifr->ifr_name, tun->dev->name);
2892
980c9e8c 2893 ifr->ifr_flags = tun_flags(tun);
e3b99556 2894
e3b99556
MM
2895}
2896
5228ddc9
RR
2897/* This is like a cut-down ethtool ops, except done via tun fd so no
2898 * privs required. */
88255375 2899static int set_offload(struct tun_struct *tun, unsigned long arg)
5228ddc9 2900{
c8f44aff 2901 netdev_features_t features = 0;
5228ddc9
RR
2902
2903 if (arg & TUN_F_CSUM) {
88255375 2904 features |= NETIF_F_HW_CSUM;
5228ddc9
RR
2905 arg &= ~TUN_F_CSUM;
2906
2907 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
2908 if (arg & TUN_F_TSO_ECN) {
2909 features |= NETIF_F_TSO_ECN;
2910 arg &= ~TUN_F_TSO_ECN;
2911 }
2912 if (arg & TUN_F_TSO4)
2913 features |= NETIF_F_TSO;
2914 if (arg & TUN_F_TSO6)
2915 features |= NETIF_F_TSO6;
2916 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
2917 }
0c19f846
WB
2918
2919 arg &= ~TUN_F_UFO;
5228ddc9
RR
2920 }
2921
2922 /* This gives the user a way to test for new features in future by
2923 * trying to set them. */
2924 if (arg)
2925 return -EINVAL;
2926
88255375 2927 tun->set_features = features;
09050957
YI
2928 tun->dev->wanted_features &= ~TUN_USER_FEATURES;
2929 tun->dev->wanted_features |= features;
88255375 2930 netdev_update_features(tun->dev);
5228ddc9
RR
2931
2932 return 0;
2933}
2934
c8d68e6b
JW
2935static void tun_detach_filter(struct tun_struct *tun, int n)
2936{
2937 int i;
2938 struct tun_file *tfile;
2939
2940 for (i = 0; i < n; i++) {
b8deabd3 2941 tfile = rtnl_dereference(tun->tfiles[i]);
8ced425e
HFS
2942 lock_sock(tfile->socket.sk);
2943 sk_detach_filter(tfile->socket.sk);
2944 release_sock(tfile->socket.sk);
c8d68e6b
JW
2945 }
2946
2947 tun->filter_attached = false;
2948}
2949
2950static int tun_attach_filter(struct tun_struct *tun)
2951{
2952 int i, ret = 0;
2953 struct tun_file *tfile;
2954
2955 for (i = 0; i < tun->numqueues; i++) {
b8deabd3 2956 tfile = rtnl_dereference(tun->tfiles[i]);
8ced425e
HFS
2957 lock_sock(tfile->socket.sk);
2958 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
2959 release_sock(tfile->socket.sk);
c8d68e6b
JW
2960 if (ret) {
2961 tun_detach_filter(tun, i);
2962 return ret;
2963 }
2964 }
2965
2966 tun->filter_attached = true;
2967 return ret;
2968}
2969
2970static void tun_set_sndbuf(struct tun_struct *tun)
2971{
2972 struct tun_file *tfile;
2973 int i;
2974
2975 for (i = 0; i < tun->numqueues; i++) {
b8deabd3 2976 tfile = rtnl_dereference(tun->tfiles[i]);
c8d68e6b
JW
2977 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
2978 }
2979}
2980
cde8b15f
JW
2981static int tun_set_queue(struct file *file, struct ifreq *ifr)
2982{
2983 struct tun_file *tfile = file->private_data;
2984 struct tun_struct *tun;
cde8b15f
JW
2985 int ret = 0;
2986
2987 rtnl_lock();
2988
2989 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
4008e97f 2990 tun = tfile->detached;
5dbbaf2d 2991 if (!tun) {
cde8b15f 2992 ret = -EINVAL;
5dbbaf2d
PM
2993 goto unlock;
2994 }
2995 ret = security_tun_dev_attach_queue(tun->security);
2996 if (ret < 0)
2997 goto unlock;
af3fb24e
ED
2998 ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
2999 tun->flags & IFF_NAPI_FRAGS);
4008e97f 3000 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
b8deabd3 3001 tun = rtnl_dereference(tfile->tun);
40630b82 3002 if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
4008e97f
JW
3003 ret = -EINVAL;
3004 else
3005 __tun_detach(tfile, false);
3006 } else
cde8b15f
JW
3007 ret = -EINVAL;
3008
83c1f36f
SD
3009 if (ret >= 0)
3010 netdev_state_change(tun->dev);
3011
5dbbaf2d 3012unlock:
cde8b15f
JW
3013 rtnl_unlock();
3014 return ret;
3015}
3016
cd5681d7
JW
3017static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog **prog_p,
3018 void __user *data)
96f84061
JW
3019{
3020 struct bpf_prog *prog;
3021 int fd;
3022
3023 if (copy_from_user(&fd, data, sizeof(fd)))
3024 return -EFAULT;
3025
3026 if (fd == -1) {
3027 prog = NULL;
3028 } else {
3029 prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
3030 if (IS_ERR(prog))
3031 return PTR_ERR(prog);
3032 }
3033
cd5681d7 3034 return __tun_set_ebpf(tun, prog_p, prog);
96f84061
JW
3035}
3036
50857e2a
AB
3037static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
3038 unsigned long arg, int ifreq_len)
1da177e4 3039{
36b50bab 3040 struct tun_file *tfile = file->private_data;
f663706a 3041 struct net *net = sock_net(&tfile->sk);
631ab46b 3042 struct tun_struct *tun;
1da177e4 3043 void __user* argp = (void __user*)arg;
26d31925 3044 unsigned int ifindex, carrier;
1da177e4 3045 struct ifreq ifr;
0625c883
EB
3046 kuid_t owner;
3047 kgid_t group;
33dccbb0 3048 int sndbuf;
d9d52b51 3049 int vnet_hdr_sz;
1cf8e410 3050 int le;
f271b2cc 3051 int ret;
83c1f36f 3052 bool do_notify = false;
1da177e4 3053
f2780d6d
KT
3054 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
3055 (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
50857e2a 3056 if (copy_from_user(&ifr, argp, ifreq_len))
1da177e4 3057 return -EFAULT;
8bbb1813 3058 } else {
a117dacd 3059 memset(&ifr, 0, sizeof(ifr));
8bbb1813 3060 }
631ab46b
EB
3061 if (cmd == TUNGETFEATURES) {
3062 /* Currently this just means: "what IFF flags are valid?".
3063 * This is needed because we never checked for invalid flags on
031f5e03
MT
3064 * TUNSETIFF.
3065 */
3066 return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
631ab46b 3067 (unsigned int __user*)argp);
f663706a 3068 } else if (cmd == TUNSETQUEUE) {
cde8b15f 3069 return tun_set_queue(file, &ifr);
f663706a
KT
3070 } else if (cmd == SIOCGSKNS) {
3071 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3072 return -EPERM;
3073 return open_related_ns(&net->ns, get_net_ns);
3074 }
631ab46b 3075
c8d68e6b 3076 ret = 0;
876bfd4d
HX
3077 rtnl_lock();
3078
9484dc74 3079 tun = tun_get(tfile);
0f16bc13
GF
3080 if (cmd == TUNSETIFF) {
3081 ret = -EEXIST;
3082 if (tun)
3083 goto unlock;
3084
1da177e4
LT
3085 ifr.ifr_name[IFNAMSIZ-1] = '\0';
3086
f2780d6d 3087 ret = tun_set_iff(net, file, &ifr);
1da177e4 3088
876bfd4d
HX
3089 if (ret)
3090 goto unlock;
1da177e4 3091
50857e2a 3092 if (copy_to_user(argp, &ifr, ifreq_len))
876bfd4d
HX
3093 ret = -EFAULT;
3094 goto unlock;
1da177e4 3095 }
fb7589a1
PE
3096 if (cmd == TUNSETIFINDEX) {
3097 ret = -EPERM;
3098 if (tun)
3099 goto unlock;
3100
3101 ret = -EFAULT;
3102 if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
3103 goto unlock;
3104
3105 ret = 0;
3106 tfile->ifindex = ifindex;
3107 goto unlock;
3108 }
1da177e4 3109
876bfd4d 3110 ret = -EBADFD;
1da177e4 3111 if (!tun)
876bfd4d 3112 goto unlock;
1da177e4 3113
1e588338 3114 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
1da177e4 3115
631ab46b 3116 ret = 0;
1da177e4 3117 switch (cmd) {
e3b99556 3118 case TUNGETIFF:
9ce99cf6 3119 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
e3b99556 3120
3d407a80
PE
3121 if (tfile->detached)
3122 ifr.ifr_flags |= IFF_DETACH_QUEUE;
849c9b6f
PE
3123 if (!tfile->socket.sk->sk_filter)
3124 ifr.ifr_flags |= IFF_NOFILTER;
3d407a80 3125
50857e2a 3126 if (copy_to_user(argp, &ifr, ifreq_len))
631ab46b 3127 ret = -EFAULT;
e3b99556
MM
3128 break;
3129
1da177e4
LT
3130 case TUNSETNOCSUM:
3131 /* Disable/Enable checksum */
1da177e4 3132
88255375
MM
3133 /* [unimplemented] */
3134 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
6b8a66ee 3135 arg ? "disabled" : "enabled");
1da177e4
LT
3136 break;
3137
3138 case TUNSETPERSIST:
54f968d6
JW
3139 /* Disable/Enable persist mode. Keep an extra reference to the
3140 * module to prevent the module being unprobed.
3141 */
40630b82
MT
3142 if (arg && !(tun->flags & IFF_PERSIST)) {
3143 tun->flags |= IFF_PERSIST;
54f968d6 3144 __module_get(THIS_MODULE);
83c1f36f 3145 do_notify = true;
dd38bd85 3146 }
40630b82
MT
3147 if (!arg && (tun->flags & IFF_PERSIST)) {
3148 tun->flags &= ~IFF_PERSIST;
54f968d6 3149 module_put(THIS_MODULE);
83c1f36f 3150 do_notify = true;
54f968d6 3151 }
1da177e4 3152
6b8a66ee
JP
3153 tun_debug(KERN_INFO, tun, "persist %s\n",
3154 arg ? "enabled" : "disabled");
1da177e4
LT
3155 break;
3156
3157 case TUNSETOWNER:
3158 /* Set owner of the device */
0625c883
EB
3159 owner = make_kuid(current_user_ns(), arg);
3160 if (!uid_valid(owner)) {
3161 ret = -EINVAL;
3162 break;
3163 }
3164 tun->owner = owner;
83c1f36f 3165 do_notify = true;
1e588338 3166 tun_debug(KERN_INFO, tun, "owner set to %u\n",
0625c883 3167 from_kuid(&init_user_ns, tun->owner));
1da177e4
LT
3168 break;
3169
8c644623
GG
3170 case TUNSETGROUP:
3171 /* Set group of the device */
0625c883
EB
3172 group = make_kgid(current_user_ns(), arg);
3173 if (!gid_valid(group)) {
3174 ret = -EINVAL;
3175 break;
3176 }
3177 tun->group = group;
83c1f36f 3178 do_notify = true;
1e588338 3179 tun_debug(KERN_INFO, tun, "group set to %u\n",
0625c883 3180 from_kgid(&init_user_ns, tun->group));
8c644623
GG
3181 break;
3182
ff4cc3ac
MK
3183 case TUNSETLINK:
3184 /* Only allow setting the type when the interface is down */
3185 if (tun->dev->flags & IFF_UP) {
6b8a66ee
JP
3186 tun_debug(KERN_INFO, tun,
3187 "Linktype set failed because interface is up\n");
48abfe05 3188 ret = -EBUSY;
ff4cc3ac
MK
3189 } else {
3190 tun->dev->type = (int) arg;
6b8a66ee
JP
3191 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
3192 tun->dev->type);
48abfe05 3193 ret = 0;
ff4cc3ac 3194 }
631ab46b 3195 break;
ff4cc3ac 3196
1da177e4
LT
3197#ifdef TUN_DEBUG
3198 case TUNSETDEBUG:
3199 tun->debug = arg;
3200 break;
3201#endif
5228ddc9 3202 case TUNSETOFFLOAD:
88255375 3203 ret = set_offload(tun, arg);
631ab46b 3204 break;
5228ddc9 3205
f271b2cc
MK
3206 case TUNSETTXFILTER:
3207 /* Can be set only for TAPs */
631ab46b 3208 ret = -EINVAL;
40630b82 3209 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
631ab46b 3210 break;
c0e5a8c2 3211 ret = update_filter(&tun->txflt, (void __user *)arg);
631ab46b 3212 break;
1da177e4
LT
3213
3214 case SIOCGIFHWADDR:
b595076a 3215 /* Get hw address */
f271b2cc
MK
3216 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
3217 ifr.ifr_hwaddr.sa_family = tun->dev->type;
50857e2a 3218 if (copy_to_user(argp, &ifr, ifreq_len))
631ab46b
EB
3219 ret = -EFAULT;
3220 break;
1da177e4
LT
3221
3222 case SIOCSIFHWADDR:
f271b2cc 3223 /* Set hw address */
6b8a66ee
JP
3224 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
3225 ifr.ifr_hwaddr.sa_data);
40102371 3226
3a37a963 3227 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr, NULL);
631ab46b 3228 break;
33dccbb0
HX
3229
3230 case TUNGETSNDBUF:
54f968d6 3231 sndbuf = tfile->socket.sk->sk_sndbuf;
33dccbb0
HX
3232 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
3233 ret = -EFAULT;
3234 break;
3235
3236 case TUNSETSNDBUF:
3237 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
3238 ret = -EFAULT;
3239 break;
3240 }
93161922
CG
3241 if (sndbuf <= 0) {
3242 ret = -EINVAL;
3243 break;
3244 }
33dccbb0 3245
c8d68e6b
JW
3246 tun->sndbuf = sndbuf;
3247 tun_set_sndbuf(tun);
33dccbb0
HX
3248 break;
3249
d9d52b51
MT
3250 case TUNGETVNETHDRSZ:
3251 vnet_hdr_sz = tun->vnet_hdr_sz;
3252 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
3253 ret = -EFAULT;
3254 break;
3255
3256 case TUNSETVNETHDRSZ:
3257 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
3258 ret = -EFAULT;
3259 break;
3260 }
3261 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
3262 ret = -EINVAL;
3263 break;
3264 }
3265
3266 tun->vnet_hdr_sz = vnet_hdr_sz;
3267 break;
3268
1cf8e410
MT
3269 case TUNGETVNETLE:
3270 le = !!(tun->flags & TUN_VNET_LE);
3271 if (put_user(le, (int __user *)argp))
3272 ret = -EFAULT;
3273 break;
3274
3275 case TUNSETVNETLE:
3276 if (get_user(le, (int __user *)argp)) {
3277 ret = -EFAULT;
3278 break;
3279 }
3280 if (le)
3281 tun->flags |= TUN_VNET_LE;
3282 else
3283 tun->flags &= ~TUN_VNET_LE;
3284 break;
3285
8b8e658b
GK
3286 case TUNGETVNETBE:
3287 ret = tun_get_vnet_be(tun, argp);
3288 break;
3289
3290 case TUNSETVNETBE:
3291 ret = tun_set_vnet_be(tun, argp);
3292 break;
3293
99405162
MT
3294 case TUNATTACHFILTER:
3295 /* Can be set only for TAPs */
3296 ret = -EINVAL;
40630b82 3297 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
99405162
MT
3298 break;
3299 ret = -EFAULT;
54f968d6 3300 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
99405162
MT
3301 break;
3302
c8d68e6b 3303 ret = tun_attach_filter(tun);
99405162
MT
3304 break;
3305
3306 case TUNDETACHFILTER:
3307 /* Can be set only for TAPs */
3308 ret = -EINVAL;
40630b82 3309 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
99405162 3310 break;
c8d68e6b
JW
3311 ret = 0;
3312 tun_detach_filter(tun, tun->numqueues);
99405162
MT
3313 break;
3314
76975e9c
PE
3315 case TUNGETFILTER:
3316 ret = -EINVAL;
40630b82 3317 if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
76975e9c
PE
3318 break;
3319 ret = -EFAULT;
3320 if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
3321 break;
3322 ret = 0;
3323 break;
3324
96f84061 3325 case TUNSETSTEERINGEBPF:
cd5681d7 3326 ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
96f84061
JW
3327 break;
3328
aff3d70a
JW
3329 case TUNSETFILTEREBPF:
3330 ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
3331 break;
3332
26d31925
ND
3333 case TUNSETCARRIER:
3334 ret = -EFAULT;
3335 if (copy_from_user(&carrier, argp, sizeof(carrier)))
3336 goto unlock;
3337
3338 ret = tun_net_change_carrier(tun->dev, (bool)carrier);
3339 break;
3340
1da177e4 3341 default:
631ab46b
EB
3342 ret = -EINVAL;
3343 break;
ee289b64 3344 }
1da177e4 3345
83c1f36f
SD
3346 if (do_notify)
3347 netdev_state_change(tun->dev);
3348
876bfd4d
HX
3349unlock:
3350 rtnl_unlock();
3351 if (tun)
3352 tun_put(tun);
631ab46b 3353 return ret;
1da177e4
LT
3354}
3355
50857e2a
AB
3356static long tun_chr_ioctl(struct file *file,
3357 unsigned int cmd, unsigned long arg)
3358{
3359 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
3360}
3361
3362#ifdef CONFIG_COMPAT
3363static long tun_chr_compat_ioctl(struct file *file,
3364 unsigned int cmd, unsigned long arg)
3365{
3366 switch (cmd) {
3367 case TUNSETIFF:
3368 case TUNGETIFF:
3369 case TUNSETTXFILTER:
3370 case TUNGETSNDBUF:
3371 case TUNSETSNDBUF:
3372 case SIOCGIFHWADDR:
3373 case SIOCSIFHWADDR:
3374 arg = (unsigned long)compat_ptr(arg);
3375 break;
3376 default:
3377 arg = (compat_ulong_t)arg;
3378 break;
3379 }
3380
3381 /*
3382 * compat_ifreq is shorter than ifreq, so we must not access beyond
3383 * the end of that structure. All fields that are used in this
3384 * driver are compatible though, we don't need to convert the
3385 * contents.
3386 */
3387 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
3388}
3389#endif /* CONFIG_COMPAT */
3390
1da177e4
LT
3391static int tun_chr_fasync(int fd, struct file *file, int on)
3392{
54f968d6 3393 struct tun_file *tfile = file->private_data;
1da177e4
LT
3394 int ret;
3395
54f968d6 3396 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
9d319522 3397 goto out;
6aa20a22 3398
1da177e4 3399 if (on) {
01919134 3400 __f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
54f968d6 3401 tfile->flags |= TUN_FASYNC;
6aa20a22 3402 } else
54f968d6 3403 tfile->flags &= ~TUN_FASYNC;
9d319522
JC
3404 ret = 0;
3405out:
9d319522 3406 return ret;
1da177e4
LT
3407}
3408
3409static int tun_chr_open(struct inode *inode, struct file * file)
3410{
140e807d 3411 struct net *net = current->nsproxy->net_ns;
631ab46b 3412 struct tun_file *tfile;
deed49fb 3413
6b8a66ee 3414 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
631ab46b 3415
140e807d 3416 tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
11aa9c28 3417 &tun_proto, 0);
631ab46b
EB
3418 if (!tfile)
3419 return -ENOMEM;
b196d88a
JW
3420 if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
3421 sk_free(&tfile->sk);
3422 return -ENOMEM;
3423 }
3424
c7256f57 3425 mutex_init(&tfile->napi_mutex);
c956674b 3426 RCU_INIT_POINTER(tfile->tun, NULL);
54f968d6 3427 tfile->flags = 0;
fb7589a1 3428 tfile->ifindex = 0;
54f968d6 3429
54f968d6 3430 init_waitqueue_head(&tfile->wq.wait);
9e641bdc 3431 RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
54f968d6
JW
3432
3433 tfile->socket.file = file;
3434 tfile->socket.ops = &tun_socket_ops;
3435
3436 sock_init_data(&tfile->socket, &tfile->sk);
54f968d6
JW
3437
3438 tfile->sk.sk_write_space = tun_sock_write_space;
3439 tfile->sk.sk_sndbuf = INT_MAX;
3440
631ab46b 3441 file->private_data = tfile;
4008e97f 3442 INIT_LIST_HEAD(&tfile->next);
54f968d6 3443
19a6afb2
JW
3444 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
3445
1da177e4
LT
3446 return 0;
3447}
3448
3449static int tun_chr_close(struct inode *inode, struct file *file)
3450{
631ab46b 3451 struct tun_file *tfile = file->private_data;
1da177e4 3452
c8d68e6b 3453 tun_detach(tfile, true);
1da177e4
LT
3454
3455 return 0;
3456}
3457
93e14b6d 3458#ifdef CONFIG_PROC_FS
9484dc74 3459static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
93e14b6d 3460{
9484dc74 3461 struct tun_file *tfile = file->private_data;
93e14b6d
MY
3462 struct tun_struct *tun;
3463 struct ifreq ifr;
3464
3465 memset(&ifr, 0, sizeof(ifr));
3466
3467 rtnl_lock();
9484dc74 3468 tun = tun_get(tfile);
93e14b6d
MY
3469 if (tun)
3470 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
3471 rtnl_unlock();
3472
3473 if (tun)
3474 tun_put(tun);
3475
a3816ab0 3476 seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
93e14b6d
MY
3477}
3478#endif
3479
d54b1fdb 3480static const struct file_operations tun_fops = {
6aa20a22 3481 .owner = THIS_MODULE,
1da177e4 3482 .llseek = no_llseek,
9b067034 3483 .read_iter = tun_chr_read_iter,
f5ff53b4 3484 .write_iter = tun_chr_write_iter,
1da177e4 3485 .poll = tun_chr_poll,
50857e2a
AB
3486 .unlocked_ioctl = tun_chr_ioctl,
3487#ifdef CONFIG_COMPAT
3488 .compat_ioctl = tun_chr_compat_ioctl,
3489#endif
1da177e4
LT
3490 .open = tun_chr_open,
3491 .release = tun_chr_close,
93e14b6d
MY
3492 .fasync = tun_chr_fasync,
3493#ifdef CONFIG_PROC_FS
3494 .show_fdinfo = tun_chr_show_fdinfo,
3495#endif
1da177e4
LT
3496};
3497
3498static struct miscdevice tun_miscdev = {
3499 .minor = TUN_MINOR,
3500 .name = "tun",
e454cea2 3501 .nodename = "net/tun",
1da177e4 3502 .fops = &tun_fops,
1da177e4
LT
3503};
3504
3505/* ethtool interface */
3506
4e24f2dd
CW
3507static void tun_default_link_ksettings(struct net_device *dev,
3508 struct ethtool_link_ksettings *cmd)
29ccc49d
PR
3509{
3510 ethtool_link_ksettings_zero_link_mode(cmd, supported);
3511 ethtool_link_ksettings_zero_link_mode(cmd, advertising);
3512 cmd->base.speed = SPEED_10;
3513 cmd->base.duplex = DUPLEX_FULL;
3514 cmd->base.port = PORT_TP;
3515 cmd->base.phy_address = 0;
3516 cmd->base.autoneg = AUTONEG_DISABLE;
4e24f2dd
CW
3517}
3518
3519static int tun_get_link_ksettings(struct net_device *dev,
3520 struct ethtool_link_ksettings *cmd)
3521{
3522 struct tun_struct *tun = netdev_priv(dev);
3523
3524 memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
3525 return 0;
3526}
3527
3528static int tun_set_link_ksettings(struct net_device *dev,
3529 const struct ethtool_link_ksettings *cmd)
3530{
3531 struct tun_struct *tun = netdev_priv(dev);
3532
3533 memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
1da177e4
LT
3534 return 0;
3535}
3536
3537static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
3538{
3539 struct tun_struct *tun = netdev_priv(dev);
3540
33a5ba14
RJ
3541 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
3542 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
1da177e4
LT
3543
3544 switch (tun->flags & TUN_TYPE_MASK) {
40630b82 3545 case IFF_TUN:
33a5ba14 3546 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
1da177e4 3547 break;
40630b82 3548 case IFF_TAP:
33a5ba14 3549 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
1da177e4
LT
3550 break;
3551 }
3552}
3553
3554static u32 tun_get_msglevel(struct net_device *dev)
3555{
3556#ifdef TUN_DEBUG
3557 struct tun_struct *tun = netdev_priv(dev);
3558 return tun->debug;
3559#else
3560 return -EOPNOTSUPP;
3561#endif
3562}
3563
3564static void tun_set_msglevel(struct net_device *dev, u32 value)
3565{
3566#ifdef TUN_DEBUG
3567 struct tun_struct *tun = netdev_priv(dev);
3568 tun->debug = value;
3569#endif
3570}
3571
5503fcec
JW
3572static int tun_get_coalesce(struct net_device *dev,
3573 struct ethtool_coalesce *ec)
3574{
3575 struct tun_struct *tun = netdev_priv(dev);
3576
3577 ec->rx_max_coalesced_frames = tun->rx_batched;
3578
3579 return 0;
3580}
3581
3582static int tun_set_coalesce(struct net_device *dev,
3583 struct ethtool_coalesce *ec)
3584{
3585 struct tun_struct *tun = netdev_priv(dev);
3586
3587 if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
3588 tun->rx_batched = NAPI_POLL_WEIGHT;
3589 else
3590 tun->rx_batched = ec->rx_max_coalesced_frames;
3591
3592 return 0;
3593}
3594
7282d491 3595static const struct ethtool_ops tun_ethtool_ops = {
1da177e4
LT
3596 .get_drvinfo = tun_get_drvinfo,
3597 .get_msglevel = tun_get_msglevel,
3598 .set_msglevel = tun_set_msglevel,
bee31369 3599 .get_link = ethtool_op_get_link,
eda29772 3600 .get_ts_info = ethtool_op_get_ts_info,
5503fcec
JW
3601 .get_coalesce = tun_get_coalesce,
3602 .set_coalesce = tun_set_coalesce,
29ccc49d 3603 .get_link_ksettings = tun_get_link_ksettings,
4e24f2dd 3604 .set_link_ksettings = tun_set_link_ksettings,
1da177e4
LT
3605};
3606
1576d986
JW
3607static int tun_queue_resize(struct tun_struct *tun)
3608{
3609 struct net_device *dev = tun->dev;
3610 struct tun_file *tfile;
5990a305 3611 struct ptr_ring **rings;
1576d986
JW
3612 int n = tun->numqueues + tun->numdisabled;
3613 int ret, i;
3614
5990a305
JW
3615 rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
3616 if (!rings)
1576d986
JW
3617 return -ENOMEM;
3618
3619 for (i = 0; i < tun->numqueues; i++) {
3620 tfile = rtnl_dereference(tun->tfiles[i]);
5990a305 3621 rings[i] = &tfile->tx_ring;
1576d986
JW
3622 }
3623 list_for_each_entry(tfile, &tun->disabled, next)
5990a305 3624 rings[i++] = &tfile->tx_ring;
1576d986 3625
5990a305
JW
3626 ret = ptr_ring_resize_multiple(rings, n,
3627 dev->tx_queue_len, GFP_KERNEL,
fc72d1d5 3628 tun_ptr_free);
1576d986 3629
5990a305 3630 kfree(rings);
1576d986
JW
3631 return ret;
3632}
3633
3634static int tun_device_event(struct notifier_block *unused,
3635 unsigned long event, void *ptr)
3636{
3637 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3638 struct tun_struct *tun = netdev_priv(dev);
3639
86dfb4ac
CG
3640 if (dev->rtnl_link_ops != &tun_link_ops)
3641 return NOTIFY_DONE;
3642
1576d986
JW
3643 switch (event) {
3644 case NETDEV_CHANGE_TX_QUEUE_LEN:
3645 if (tun_queue_resize(tun))
3646 return NOTIFY_BAD;
3647 break;
3648 default:
3649 break;
3650 }
3651
3652 return NOTIFY_DONE;
3653}
3654
3655static struct notifier_block tun_notifier_block __read_mostly = {
3656 .notifier_call = tun_device_event,
3657};
79d17604 3658
1da177e4
LT
3659static int __init tun_init(void)
3660{
3661 int ret = 0;
3662
6b8a66ee 3663 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
1da177e4 3664
f019a7a5 3665 ret = rtnl_link_register(&tun_link_ops);
79d17604 3666 if (ret) {
6b8a66ee 3667 pr_err("Can't register link_ops\n");
f019a7a5 3668 goto err_linkops;
79d17604
PE
3669 }
3670
1da177e4 3671 ret = misc_register(&tun_miscdev);
79d17604 3672 if (ret) {
6b8a66ee 3673 pr_err("Can't register misc device %d\n", TUN_MINOR);
79d17604
PE
3674 goto err_misc;
3675 }
1576d986 3676
5edfbd3c
TZ
3677 ret = register_netdevice_notifier(&tun_notifier_block);
3678 if (ret) {
3679 pr_err("Can't register netdevice notifier\n");
3680 goto err_notifier;
3681 }
3682
f019a7a5 3683 return 0;
5edfbd3c
TZ
3684
3685err_notifier:
3686 misc_deregister(&tun_miscdev);
79d17604 3687err_misc:
f019a7a5
EB
3688 rtnl_link_unregister(&tun_link_ops);
3689err_linkops:
1da177e4
LT
3690 return ret;
3691}
3692
3693static void tun_cleanup(void)
3694{
6aa20a22 3695 misc_deregister(&tun_miscdev);
f019a7a5 3696 rtnl_link_unregister(&tun_link_ops);
1576d986 3697 unregister_netdevice_notifier(&tun_notifier_block);
1da177e4
LT
3698}
3699
05c2828c
MT
3700/* Get an underlying socket object from tun file. Returns error unless file is
3701 * attached to a device. The returned object works like a packet socket, it
3702 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
3703 * holding a reference to the file for as long as the socket is in use. */
3704struct socket *tun_get_socket(struct file *file)
3705{
6e914fc7 3706 struct tun_file *tfile;
05c2828c
MT
3707 if (file->f_op != &tun_fops)
3708 return ERR_PTR(-EINVAL);
6e914fc7
JW
3709 tfile = file->private_data;
3710 if (!tfile)
05c2828c 3711 return ERR_PTR(-EBADFD);
54f968d6 3712 return &tfile->socket;
05c2828c
MT
3713}
3714EXPORT_SYMBOL_GPL(tun_get_socket);
3715
5990a305 3716struct ptr_ring *tun_get_tx_ring(struct file *file)
83339c6b
JW
3717{
3718 struct tun_file *tfile;
3719
3720 if (file->f_op != &tun_fops)
3721 return ERR_PTR(-EINVAL);
3722 tfile = file->private_data;
3723 if (!tfile)
3724 return ERR_PTR(-EBADFD);
5990a305 3725 return &tfile->tx_ring;
83339c6b 3726}
5990a305 3727EXPORT_SYMBOL_GPL(tun_get_tx_ring);
83339c6b 3728
1da177e4
LT
3729module_init(tun_init);
3730module_exit(tun_cleanup);
3731MODULE_DESCRIPTION(DRV_DESCRIPTION);
3732MODULE_AUTHOR(DRV_COPYRIGHT);
3733MODULE_LICENSE("GPL");
3734MODULE_ALIAS_MISCDEV(TUN_MINOR);
578454ff 3735MODULE_ALIAS("devname:net/tun");