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