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